]> git.proxmox.com Git - rustc.git/blame - src/librustc_ast_lowering/lib.rs
New upstream version 1.44.1+dfsg1
[rustc.git] / src / librustc_ast_lowering / lib.rs
CommitLineData
041b39d2
XL
1//! Lowers the AST to the HIR.
2//!
3//! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
4//! much like a fold. Where lowering involves a bit more work things get more
5//! interesting and there are some invariants you should know about. These mostly
9fa01778 6//! concern spans and IDs.
041b39d2
XL
7//!
8//! Spans are assigned to AST nodes during parsing and then are modified during
9//! expansion to indicate the origin of a node and the process it went through
9fa01778 10//! being expanded. IDs are assigned to AST nodes just before lowering.
041b39d2 11//!
9fa01778 12//! For the simpler lowering steps, IDs and spans should be preserved. Unlike
041b39d2
XL
13//! expansion we do not preserve the process of lowering in the spans, so spans
14//! should not be modified here. When creating a new node (as opposed to
9fa01778 15//! 'folding' an existing one), then you create a new ID using `next_id()`.
041b39d2 16//!
9fa01778 17//! You must ensure that IDs are unique. That means that you should only use the
dc9dc135 18//! ID from an AST node in a single HIR node (you can assume that AST node-IDs
9fa01778
XL
19//! are unique). Every new node must have a unique ID. Avoid cloning HIR nodes.
20//! If you do, you must then set the new node's ID to a fresh one.
041b39d2
XL
21//!
22//! Spans are used for error messages and for tools to map semantics back to
9fa01778 23//! source code. It is therefore not as important with spans as IDs to be strict
041b39d2
XL
24//! about use (you can't break the compiler by screwing up a span). Obviously, a
25//! HIR node can only have a single span. But multiple nodes can have the same
26//! span and spans don't need to be kept in order, etc. Where code is preserved
27//! by lowering, it should have the same span as in the AST. Where HIR nodes are
28//! new it is probably best to give a span for the whole AST node being lowered.
29//! All nodes should have real spans, don't use dummy spans. Tools are likely to
30//! get confused if the spans from leaf AST nodes occur in multiple places
31//! in the HIR, especially for multiple identifiers.
e9174d1e 32
dfeec247
XL
33#![feature(array_value_iter)]
34#![feature(crate_visibility_modifier)]
ba9703b0
XL
35#![feature(marker_trait_attr)]
36#![feature(specialization)]
37#![feature(or_patterns)]
74b04a01 38#![recursion_limit = "256"]
416331ca 39
74b04a01
XL
40use rustc_ast::ast;
41use rustc_ast::ast::*;
42use rustc_ast::attr;
43use rustc_ast::node_id::NodeMap;
44use rustc_ast::token::{self, Nonterminal, Token};
45use rustc_ast::tokenstream::{TokenStream, TokenTree};
46use rustc_ast::visit::{self, AssocCtxt, Visitor};
47use rustc_ast::walk_list;
48use rustc_ast_pretty::pprust;
dfeec247 49use rustc_data_structures::captures::Captures;
b7449926 50use rustc_data_structures::fx::FxHashSet;
dc9dc135 51use rustc_data_structures::sync::Lrc;
dfeec247
XL
52use rustc_errors::struct_span_err;
53use rustc_hir as hir;
54use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res};
ba9703b0
XL
55use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
56use rustc_hir::definitions::{DefKey, DefPathData, Definitions};
dfeec247
XL
57use rustc_hir::intravisit;
58use rustc_hir::{ConstArg, GenericArg, ParamName};
59use rustc_index::vec::IndexVec;
60use rustc_session::config::nightly_options;
74b04a01
XL
61use rustc_session::lint::{builtin::BARE_TRAIT_OBJECTS, BuiltinLintDiagnostics, LintBuffer};
62use rustc_session::parse::ParseSess;
dfeec247
XL
63use rustc_session::Session;
64use rustc_span::hygiene::ExpnId;
65use rustc_span::source_map::{respan, DesugaringKind, ExpnData, ExpnKind};
66use rustc_span::symbol::{kw, sym, Symbol};
67use rustc_span::Span;
b039eaaf 68
dfeec247
XL
69use log::{debug, trace};
70use smallvec::{smallvec, SmallVec};
71use std::collections::BTreeMap;
72use std::mem;
73
74macro_rules! arena_vec {
75 ($this:expr; $($x:expr),*) => ({
76 let a = [$($x),*];
77 $this.arena.alloc_from_iter(std::array::IntoIter::new(a))
78 });
79}
80
81mod expr;
82mod item;
83mod pat;
84mod path;
60c5eb7d 85
cc61c64b
XL
86const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
87
ba9703b0
XL
88rustc_hir::arena_types!(::arena::declare_arena, [], 'tcx);
89
dfeec247 90struct LoweringContext<'a, 'hir: 'a> {
48663c56 91 crate_root: Option<Symbol>,
041b39d2 92
e1599b0c 93 /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
9e0c209e 94 sess: &'a Session,
041b39d2 95
8faf50e0 96 resolver: &'a mut dyn Resolver,
476ff2be 97
e74abb32
XL
98 /// HACK(Centril): there is a cyclic dependency between the parser and lowering
99 /// if we don't have this function pointer. To avoid that dependency so that
ba9703b0 100 /// librustc_middle is independent of the parser, we use dynamic dispatch here.
e74abb32
XL
101 nt_to_tokenstream: NtToTokenstream,
102
dfeec247
XL
103 /// Used to allocate HIR nodes
104 arena: &'hir Arena<'hir>,
105
476ff2be 106 /// The items being lowered are collected here.
dfeec247 107 items: BTreeMap<hir::HirId, hir::Item<'hir>>,
476ff2be 108
dfeec247
XL
109 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem<'hir>>,
110 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem<'hir>>,
111 bodies: BTreeMap<hir::BodyId, hir::Body<'hir>>,
112 exported_macros: Vec<hir::MacroDef<'hir>>,
416331ca 113 non_exported_macro_attrs: Vec<ast::Attribute>,
8bb4bdeb 114
532ac7d7 115 trait_impls: BTreeMap<DefId, Vec<hir::HirId>>,
8bb4bdeb 116
e74abb32 117 modules: BTreeMap<hir::HirId, hir::ModuleItems>,
0731742a 118
dc9dc135 119 generator_kind: Option<hir::GeneratorKind>,
48663c56 120
ba9703b0
XL
121 /// When inside an `async` context, this is the `HirId` of the
122 /// `task_context` local bound to the resume argument of the generator.
123 task_context: Option<hir::HirId>,
124
48663c56
XL
125 /// Used to get the current `fn`'s def span to point to when using `await`
126 /// outside of an `async fn`.
127 current_item: Option<Span>,
ea8adc8c 128
cc61c64b 129 catch_scopes: Vec<NodeId>,
8bb4bdeb
XL
130 loop_scopes: Vec<NodeId>,
131 is_in_loop_condition: bool,
abe05a73 132 is_in_trait_impl: bool,
dc9dc135 133 is_in_dyn_type: bool,
32a655c1 134
0531ce1d
XL
135 /// What to do when we encounter either an "anonymous lifetime
136 /// reference". The term "anonymous" is meant to encompass both
137 /// `'_` lifetimes as well as fully elided cases where nothing is
138 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
139 anonymous_lifetime_mode: AnonymousLifetimeMode,
140
532ac7d7
XL
141 /// Used to create lifetime definitions from in-band lifetime usages.
142 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
143 /// When a named lifetime is encountered in a function or impl header and
144 /// has not been defined
145 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
146 /// to this list. The results of this list are then added to the list of
147 /// lifetime definitions in the corresponding impl or function generics.
8faf50e0 148 lifetimes_to_define: Vec<(Span, ParamName)>,
0531ce1d 149
e1599b0c 150 /// `true` if in-band lifetimes are being collected. This is used to
532ac7d7
XL
151 /// indicate whether or not we're in a place where new lifetimes will result
152 /// in in-band lifetime definitions, such a function or an impl header,
153 /// including implicit lifetimes from `impl_header_lifetime_elision`.
ff7c6d11 154 is_collecting_in_band_lifetimes: bool,
0531ce1d 155
532ac7d7
XL
156 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
157 /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
158 /// against this list to see if it is already in-scope, or if a definition
159 /// needs to be created for it.
e1599b0c 160 ///
ba9703b0 161 /// We always store a `normalize_to_macros_2_0()` version of the param-name in this
e1599b0c
XL
162 /// vector.
163 in_scope_lifetimes: Vec<ParamName>,
ff7c6d11 164
e74abb32 165 current_module: hir::HirId,
0731742a 166
32a655c1 167 type_def_lifetime_params: DefIdMap<usize>,
cc61c64b 168
ba9703b0 169 current_hir_id_owner: Vec<(LocalDefId, u32)>,
cc61c64b 170 item_local_id_counters: NodeMap<u32>,
ba9703b0 171 node_id_to_hir_id: IndexVec<NodeId, Option<hir::HirId>>,
dc9dc135
XL
172
173 allow_try_trait: Option<Lrc<[Symbol]>>,
174 allow_gen_future: Option<Lrc<[Symbol]>>,
b039eaaf
SL
175}
176
a7813a04 177pub trait Resolver {
dfeec247
XL
178 fn def_key(&mut self, id: DefId) -> DefKey;
179
180 fn item_generics_num_lifetimes(&self, def: DefId, sess: &Session) -> usize;
e74abb32 181
e1599b0c 182 /// Obtains resolution for a `NodeId` with a single resolution.
48663c56
XL
183 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
184
e1599b0c 185 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
48663c56 186 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
a7813a04 187
e1599b0c 188 /// Obtains resolution for a label with the given `NodeId`.
48663c56 189 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
94b46f34 190
041b39d2
XL
191 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
192 /// This should only return `None` during testing.
9e0c209e 193 fn definitions(&mut self) -> &mut Definitions;
2c00a5a8 194
dc9dc135 195 /// Given suffix `["b", "c", "d"]`, creates an AST path for `[::crate_root]::b::c::d` and
0731742a 196 /// resolves it based on `is_value`.
0531ce1d
XL
197 fn resolve_str_path(
198 &mut self,
199 span: Span,
48663c56
XL
200 crate_root: Option<Symbol>,
201 components: &[Symbol],
416331ca 202 ns: Namespace,
dc9dc135 203 ) -> (ast::Path, Res<NodeId>);
416331ca 204
dfeec247 205 fn lint_buffer(&mut self) -> &mut LintBuffer;
60c5eb7d
XL
206
207 fn next_node_id(&mut self) -> NodeId;
a7813a04 208}
b039eaaf 209
e74abb32
XL
210type NtToTokenstream = fn(&Nonterminal, &ParseSess, Span) -> TokenStream;
211
dc9dc135
XL
212/// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
213/// and if so, what meaning it has.
8faf50e0 214#[derive(Debug)]
dfeec247 215enum ImplTraitContext<'b, 'a> {
abe05a73
XL
216 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
217 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
218 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
219 ///
0bf4aa26 220 /// Newly generated parameters should be inserted into the given `Vec`.
dfeec247 221 Universal(&'b mut Vec<hir::GenericParam<'a>>),
abe05a73 222
416331ca 223 /// Treat `impl Trait` as shorthand for a new opaque type.
abe05a73 224 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
416331ca 225 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
94b46f34 226 ///
0bf4aa26 227 /// We optionally store a `DefId` for the parent item here so we can look up necessary
dc9dc135
XL
228 /// information later. It is `None` when no information about the context should be stored
229 /// (e.g., for consts and statics).
74b04a01 230 OpaqueTy(Option<DefId> /* fn def-ID */, hir::OpaqueTyOrigin),
abe05a73
XL
231
232 /// `impl Trait` is not accepted in this position.
0bf4aa26
XL
233 Disallowed(ImplTraitPosition),
234}
235
dc9dc135 236/// Position in which `impl Trait` is disallowed.
0bf4aa26
XL
237#[derive(Debug, Copy, Clone, PartialEq, Eq)]
238enum ImplTraitPosition {
dc9dc135 239 /// Disallowed in `let` / `const` / `static` bindings.
0bf4aa26 240 Binding,
dc9dc135
XL
241
242 /// All other posiitons.
0bf4aa26 243 Other,
abe05a73
XL
244}
245
dfeec247 246impl<'a> ImplTraitContext<'_, 'a> {
0bf4aa26
XL
247 #[inline]
248 fn disallowed() -> Self {
249 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
250 }
251
dfeec247 252 fn reborrow<'this>(&'this mut self) -> ImplTraitContext<'this, 'a> {
8faf50e0
XL
253 use self::ImplTraitContext::*;
254 match self {
255 Universal(params) => Universal(params),
74b04a01 256 OpaqueTy(fn_def_id, origin) => OpaqueTy(*fn_def_id, *origin),
0bf4aa26 257 Disallowed(pos) => Disallowed(*pos),
8faf50e0
XL
258 }
259 }
260}
261
dfeec247
XL
262pub fn lower_crate<'a, 'hir>(
263 sess: &'a Session,
dfeec247
XL
264 krate: &'a Crate,
265 resolver: &'a mut dyn Resolver,
e74abb32 266 nt_to_tokenstream: NtToTokenstream,
dfeec247
XL
267 arena: &'hir Arena<'hir>,
268) -> hir::Crate<'hir> {
dfeec247 269 let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering");
e74abb32 270
a7813a04 271 LoweringContext {
416331ca 272 crate_root: sess.parse_sess.injected_crate_name.try_get().copied(),
041b39d2 273 sess,
041b39d2 274 resolver,
e74abb32 275 nt_to_tokenstream,
dfeec247 276 arena,
476ff2be 277 items: BTreeMap::new(),
32a655c1 278 trait_items: BTreeMap::new(),
476ff2be 279 impl_items: BTreeMap::new(),
8bb4bdeb
XL
280 bodies: BTreeMap::new(),
281 trait_impls: BTreeMap::new(),
0731742a 282 modules: BTreeMap::new(),
8bb4bdeb 283 exported_macros: Vec::new(),
416331ca 284 non_exported_macro_attrs: Vec::new(),
cc61c64b 285 catch_scopes: Vec::new(),
8bb4bdeb
XL
286 loop_scopes: Vec::new(),
287 is_in_loop_condition: false,
dc9dc135
XL
288 is_in_trait_impl: false,
289 is_in_dyn_type: false,
0531ce1d 290 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
a1dfa0c6 291 type_def_lifetime_params: Default::default(),
e74abb32 292 current_module: hir::CRATE_HIR_ID,
ba9703b0 293 current_hir_id_owner: vec![(LocalDefId { local_def_index: CRATE_DEF_INDEX }, 0)],
a1dfa0c6 294 item_local_id_counters: Default::default(),
cc61c64b 295 node_id_to_hir_id: IndexVec::new(),
dc9dc135 296 generator_kind: None,
ba9703b0 297 task_context: None,
48663c56 298 current_item: None,
ff7c6d11
XL
299 lifetimes_to_define: Vec::new(),
300 is_collecting_in_band_lifetimes: false,
301 in_scope_lifetimes: Vec::new(),
dc9dc135
XL
302 allow_try_trait: Some([sym::try_trait][..].into()),
303 allow_gen_future: Some([sym::gen_future][..].into()),
dfeec247
XL
304 }
305 .lower_crate(krate)
a7813a04
XL
306}
307
8faf50e0 308#[derive(Copy, Clone, PartialEq)]
476ff2be
SL
309enum ParamMode {
310 /// Any path in a type context.
311 Explicit,
dc9dc135
XL
312 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
313 ExplicitNamed,
476ff2be 314 /// The `module::Type` in `module::Type::method` in an expression.
0531ce1d 315 Optional,
476ff2be
SL
316}
317
3b2f2976
XL
318enum ParenthesizedGenericArgs {
319 Ok,
3b2f2976
XL
320 Err,
321}
322
0531ce1d 323/// What to do when we encounter an **anonymous** lifetime
9fa01778 324/// reference. Anonymous lifetime references come in two flavors. You
0531ce1d
XL
325/// have implicit, or fully elided, references to lifetimes, like the
326/// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
9fa01778 327/// or `Ref<'_, T>`. These often behave the same, but not always:
0531ce1d
XL
328///
329/// - certain usages of implicit references are deprecated, like
330/// `Ref<T>`, and we sometimes just give hard errors in those cases
331/// as well.
332/// - for object bounds there is a difference: `Box<dyn Foo>` is not
333/// the same as `Box<dyn Foo + '_>`.
334///
335/// We describe the effects of the various modes in terms of three cases:
336///
337/// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
338/// of a `&` (e.g., the missing lifetime in something like `&T`)
339/// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
340/// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
341/// elided bounds follow special rules. Note that this only covers
342/// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
343/// '_>` is a case of "modern" elision.
344/// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
345/// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
346/// non-deprecated equivalent.
347///
348/// Currently, the handling of lifetime elision is somewhat spread out
349/// between HIR lowering and -- as described below -- the
350/// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
351/// an "elided" or "underscore" lifetime name. In the future, we probably want to move
352/// everything into HIR lowering.
e1599b0c 353#[derive(Copy, Clone, Debug)]
0531ce1d
XL
354enum AnonymousLifetimeMode {
355 /// For **Modern** cases, create a new anonymous region parameter
356 /// and reference that.
357 ///
358 /// For **Dyn Bound** cases, pass responsibility to
359 /// `resolve_lifetime` code.
360 ///
361 /// For **Deprecated** cases, report an error.
362 CreateParameter,
363
0bf4aa26
XL
364 /// Give a hard error when either `&` or `'_` is written. Used to
365 /// rule out things like `where T: Foo<'_>`. Does not imply an
366 /// error on default object bounds (e.g., `Box<dyn Foo>`).
367 ReportError,
368
0531ce1d
XL
369 /// Pass responsibility to `resolve_lifetime` code for all cases.
370 PassThrough,
371}
372
dfeec247
XL
373struct ImplTraitTypeIdVisitor<'a> {
374 ids: &'a mut SmallVec<[NodeId; 1]>,
375}
0bf4aa26 376
dfeec247
XL
377impl Visitor<'_> for ImplTraitTypeIdVisitor<'_> {
378 fn visit_ty(&mut self, ty: &Ty) {
e74abb32 379 match ty.kind {
dfeec247 380 TyKind::Typeof(_) | TyKind::BareFn(_) => return,
0bf4aa26 381
532ac7d7 382 TyKind::ImplTrait(id, _) => self.ids.push(id),
dfeec247 383 _ => {}
0bf4aa26
XL
384 }
385 visit::walk_ty(self, ty);
386 }
387
dfeec247 388 fn visit_path_segment(&mut self, path_span: Span, path_segment: &PathSegment) {
0bf4aa26
XL
389 if let Some(ref p) = path_segment.args {
390 if let GenericArgs::Parenthesized(_) = **p {
391 return;
392 }
393 }
394 visit::walk_path_segment(self, path_span, path_segment)
395 }
396}
397
dfeec247
XL
398impl<'a, 'hir> LoweringContext<'a, 'hir> {
399 fn lower_crate(mut self, c: &Crate) -> hir::Crate<'hir> {
32a655c1
SL
400 /// Full-crate AST visitor that inserts into a fresh
401 /// `LoweringContext` any information that may be
0731742a
XL
402 /// needed from arbitrary locations in the crate,
403 /// e.g., the number of lifetime generic parameters
32a655c1 404 /// declared for every type and trait definition.
dfeec247
XL
405 struct MiscCollector<'tcx, 'lowering, 'hir> {
406 lctx: &'tcx mut LoweringContext<'lowering, 'hir>,
48663c56 407 hir_id_owner: Option<NodeId>,
32a655c1 408 }
476ff2be 409
dfeec247 410 impl MiscCollector<'_, '_, '_> {
ba9703b0 411 fn allocate_use_tree_hir_id_counters(&mut self, tree: &UseTree, owner: LocalDefId) {
532ac7d7
XL
412 match tree.kind {
413 UseTreeKind::Simple(_, id1, id2) => {
414 for &id in &[id1, id2] {
415 self.lctx.resolver.definitions().create_def_with_parent(
416 owner,
417 id,
418 DefPathData::Misc,
416331ca 419 ExpnId::root(),
532ac7d7
XL
420 tree.prefix.span,
421 );
422 self.lctx.allocate_hir_id_counter(id);
423 }
424 }
425 UseTreeKind::Glob => (),
426 UseTreeKind::Nested(ref trees) => {
427 for &(ref use_tree, id) in trees {
48663c56 428 let hir_id = self.lctx.allocate_hir_id_counter(id);
532ac7d7
XL
429 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
430 }
431 }
432 }
433 }
48663c56 434
dfeec247
XL
435 fn with_hir_id_owner<T>(
436 &mut self,
437 owner: Option<NodeId>,
438 f: impl FnOnce(&mut Self) -> T,
439 ) -> T {
48663c56
XL
440 let old = mem::replace(&mut self.hir_id_owner, owner);
441 let r = f(self);
442 self.hir_id_owner = old;
443 r
444 }
532ac7d7
XL
445 }
446
dfeec247 447 impl<'tcx> Visitor<'tcx> for MiscCollector<'tcx, '_, '_> {
dc9dc135 448 fn visit_pat(&mut self, p: &'tcx Pat) {
e74abb32 449 if let PatKind::Paren(..) | PatKind::Rest = p.kind {
48663c56 450 // Doesn't generate a HIR node
e1599b0c
XL
451 } else if let Some(owner) = self.hir_id_owner {
452 self.lctx.lower_node_id_with_owner(p.id, owner);
453 }
48663c56
XL
454
455 visit::walk_pat(self, p)
456 }
457
dc9dc135 458 fn visit_item(&mut self, item: &'tcx Item) {
48663c56 459 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
cc61c64b 460
e74abb32 461 match item.kind {
0531ce1d
XL
462 ItemKind::Struct(_, ref generics)
463 | ItemKind::Union(_, ref generics)
464 | ItemKind::Enum(_, ref generics)
74b04a01 465 | ItemKind::TyAlias(_, ref generics, ..)
0531ce1d 466 | ItemKind::Trait(_, _, ref generics, ..) => {
32a655c1 467 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
0531ce1d
XL
468 let count = generics
469 .params
470 .iter()
8faf50e0
XL
471 .filter(|param| match param.kind {
472 ast::GenericParamKind::Lifetime { .. } => true,
473 _ => false,
474 })
ff7c6d11 475 .count();
ba9703b0 476 self.lctx.type_def_lifetime_params.insert(def_id.to_def_id(), count);
32a655c1 477 }
532ac7d7
XL
478 ItemKind::Use(ref use_tree) => {
479 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
480 }
32a655c1
SL
481 _ => {}
482 }
48663c56
XL
483
484 self.with_hir_id_owner(Some(item.id), |this| {
485 visit::walk_item(this, item);
486 });
32a655c1 487 }
cc61c64b 488
74b04a01 489 fn visit_assoc_item(&mut self, item: &'tcx AssocItem, ctxt: AssocCtxt) {
532ac7d7 490 self.lctx.allocate_hir_id_counter(item.id);
74b04a01
XL
491 let owner = match (&item.kind, ctxt) {
492 // Ignore patterns in trait methods without bodies.
493 (AssocItemKind::Fn(_, _, _, None), AssocCtxt::Trait) => None,
494 _ => Some(item.id),
495 };
496 self.with_hir_id_owner(owner, |this| visit::walk_assoc_item(this, item, ctxt));
48663c56
XL
497 }
498
dc9dc135 499 fn visit_foreign_item(&mut self, i: &'tcx ForeignItem) {
48663c56 500 // Ignore patterns in foreign items
dfeec247 501 self.with_hir_id_owner(None, |this| visit::walk_foreign_item(this, i));
48663c56
XL
502 }
503
dc9dc135 504 fn visit_ty(&mut self, t: &'tcx Ty) {
e74abb32 505 match t.kind {
48663c56
XL
506 // Mirrors the case in visit::walk_ty
507 TyKind::BareFn(ref f) => {
dfeec247 508 walk_list!(self, visit_generic_param, &f.generic_params);
48663c56 509 // Mirrors visit::walk_fn_decl
e1599b0c 510 for parameter in &f.decl.inputs {
48663c56
XL
511 // We don't lower the ids of argument patterns
512 self.with_hir_id_owner(None, |this| {
e1599b0c 513 this.visit_pat(&parameter.pat);
48663c56 514 });
e1599b0c 515 self.visit_ty(&parameter.ty)
48663c56
XL
516 }
517 self.visit_fn_ret_ty(&f.decl.output)
518 }
519 _ => visit::walk_ty(self, t),
520 }
cc61c64b 521 }
476ff2be 522 }
476ff2be 523
cc61c64b 524 self.lower_node_id(CRATE_NODE_ID);
ba9703b0 525 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == Some(hir::CRATE_HIR_ID));
cc61c64b 526
48663c56 527 visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
416331ca 528 visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
32a655c1
SL
529
530 let module = self.lower_mod(&c.module);
531 let attrs = self.lower_attrs(&c.attrs);
8bb4bdeb 532 let body_ids = body_ids(&self.bodies);
ba9703b0
XL
533 let proc_macros =
534 c.proc_macros.iter().map(|id| self.node_id_to_hir_id[*id].unwrap()).collect();
32a655c1 535
dfeec247 536 self.resolver.definitions().init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
cc61c64b 537
32a655c1 538 hir::Crate {
ba9703b0 539 item: hir::CrateItem { module, attrs, span: c.span },
dfeec247
XL
540 exported_macros: self.arena.alloc_from_iter(self.exported_macros),
541 non_exported_macro_attrs: self.arena.alloc_from_iter(self.non_exported_macro_attrs),
32a655c1
SL
542 items: self.items,
543 trait_items: self.trait_items,
544 impl_items: self.impl_items,
545 bodies: self.bodies,
041b39d2 546 body_ids,
8bb4bdeb 547 trait_impls: self.trait_impls,
0731742a 548 modules: self.modules,
74b04a01 549 proc_macros,
32a655c1 550 }
476ff2be 551 }
a7813a04 552
dfeec247 553 fn insert_item(&mut self, item: hir::Item<'hir>) {
532ac7d7 554 let id = item.hir_id;
dc9dc135 555 // FIXME: Use `debug_asset-rt`.
532ac7d7 556 assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
0731742a
XL
557 self.items.insert(id, item);
558 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
559 }
560
48663c56 561 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
dc9dc135 562 // Set up the counter if needed.
532ac7d7 563 self.item_local_id_counters.entry(owner).or_insert(0);
0731742a 564 // Always allocate the first `HirId` for the owner itself.
532ac7d7 565 let lowered = self.lower_node_id_with_owner(owner, owner);
48663c56 566 debug_assert_eq!(lowered.local_id.as_u32(), 0);
532ac7d7 567 lowered
cc61c64b
XL
568 }
569
dfeec247
XL
570 fn lower_node_id_generic(
571 &mut self,
572 ast_node_id: NodeId,
573 alloc_hir_id: impl FnOnce(&mut Self) -> hir::HirId,
574 ) -> hir::HirId {
ba9703b0 575 assert_ne!(ast_node_id, DUMMY_NODE_ID);
cc61c64b
XL
576
577 let min_size = ast_node_id.as_usize() + 1;
578
579 if min_size > self.node_id_to_hir_id.len() {
ba9703b0 580 self.node_id_to_hir_id.resize(min_size, None);
cc61c64b
XL
581 }
582
ba9703b0
XL
583 if let Some(existing_hir_id) = self.node_id_to_hir_id[ast_node_id] {
584 existing_hir_id
585 } else {
0731742a 586 // Generate a new `HirId`.
3b2f2976 587 let hir_id = alloc_hir_id(self);
ba9703b0 588 self.node_id_to_hir_id[ast_node_id] = Some(hir_id);
48663c56
XL
589
590 hir_id
cc61c64b 591 }
cc61c64b
XL
592 }
593
dfeec247
XL
594 fn with_hir_id_owner<T>(&mut self, owner: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
595 let counter = self
596 .item_local_id_counters
0531ce1d 597 .insert(owner, HIR_ID_COUNTER_LOCKED)
dc9dc135 598 .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
ba9703b0
XL
599 let def_id = self.resolver.definitions().local_def_id(owner);
600 self.current_hir_id_owner.push((def_id, counter));
94b46f34 601 let ret = f(self);
ba9703b0 602 let (new_def_id, new_counter) = self.current_hir_id_owner.pop().unwrap();
cc61c64b 603
ba9703b0 604 debug_assert!(def_id == new_def_id);
cc61c64b
XL
605 debug_assert!(new_counter >= counter);
606
dfeec247 607 let prev = self.item_local_id_counters.insert(owner, new_counter).unwrap();
cc61c64b 608 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
94b46f34 609 ret
cc61c64b
XL
610 }
611
0731742a
XL
612 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
613 /// the `LoweringContext`'s `NodeId => HirId` map.
614 /// Take care not to call this method if the resulting `HirId` is then not
cc61c64b 615 /// actually used in the HIR, as that would trigger an assertion in the
0731742a
XL
616 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
617 /// properly. Calling the method twice with the same `NodeId` is fine though.
48663c56 618 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
cc61c64b 619 self.lower_node_id_generic(ast_node_id, |this| {
ba9703b0 620 let &mut (owner, ref mut local_id_counter) =
0531ce1d 621 this.current_hir_id_owner.last_mut().unwrap();
cc61c64b
XL
622 let local_id = *local_id_counter;
623 *local_id_counter += 1;
ba9703b0 624 hir::HirId { owner, local_id: hir::ItemLocalId::from_u32(local_id) }
cc61c64b
XL
625 })
626 }
627
48663c56 628 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
cc61c64b 629 self.lower_node_id_generic(ast_node_id, |this| {
94b46f34
XL
630 let local_id_counter = this
631 .item_local_id_counters
632 .get_mut(&owner)
dc9dc135 633 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
cc61c64b
XL
634 let local_id = *local_id_counter;
635
636 // We want to be sure not to modify the counter in the map while it
637 // is also on the stack. Otherwise we'll get lost updates when writing
638 // back from the stack to the map.
639 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
640
641 *local_id_counter += 1;
ba9703b0 642 let owner = this.resolver.definitions().opt_local_def_id(owner).expect(
dfeec247 643 "you forgot to call `create_def_with_parent` or are lowering node-IDs \
ba9703b0 644 that do not belong to the current owner",
dfeec247
XL
645 );
646
ba9703b0 647 hir::HirId { owner, local_id: hir::ItemLocalId::from_u32(local_id) }
cc61c64b
XL
648 })
649 }
650
48663c56 651 fn next_id(&mut self) -> hir::HirId {
60c5eb7d
XL
652 let node_id = self.resolver.next_node_id();
653 self.lower_node_id(node_id)
3157f602
XL
654 }
655
48663c56
XL
656 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
657 res.map_id(|id| {
658 self.lower_node_id_generic(id, |_| {
e1599b0c 659 panic!("expected `NodeId` to be lowered already for res {:#?}", res);
48663c56 660 })
476ff2be
SL
661 })
662 }
663
48663c56
XL
664 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
665 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
94b46f34 666 if pr.unresolved_segments() != 0 {
ba9703b0 667 panic!("path not fully resolved: {:?}", pr);
94b46f34 668 }
48663c56 669 pr.base_res()
94b46f34
XL
670 })
671 }
672
48663c56
XL
673 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
674 self.resolver.get_import_res(id).present_items()
54a0048b 675 }
e9174d1e 676
dfeec247 677 fn diagnostic(&self) -> &rustc_errors::Handler {
48663c56 678 self.sess.diagnostic()
a7813a04 679 }
7453a54e 680
dc9dc135
XL
681 /// Reuses the span but adds information like the kind of the desugaring and features that are
682 /// allowed inside this span.
683 fn mark_span_with_reason(
684 &self,
416331ca 685 reason: DesugaringKind,
dc9dc135
XL
686 span: Span,
687 allow_internal_unstable: Option<Lrc<[Symbol]>>,
688 ) -> Span {
e1599b0c 689 span.fresh_expansion(ExpnData {
dc9dc135 690 allow_internal_unstable,
e1599b0c 691 ..ExpnData::default(ExpnKind::Desugaring(reason), span, self.sess.edition())
416331ca 692 })
dc9dc135
XL
693 }
694
94b46f34
XL
695 fn with_anonymous_lifetime_mode<R>(
696 &mut self,
697 anonymous_lifetime_mode: AnonymousLifetimeMode,
698 op: impl FnOnce(&mut Self) -> R,
699 ) -> R {
e1599b0c
XL
700 debug!(
701 "with_anonymous_lifetime_mode(anonymous_lifetime_mode={:?})",
702 anonymous_lifetime_mode,
703 );
94b46f34
XL
704 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
705 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
706 let result = op(self);
707 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
dfeec247
XL
708 debug!(
709 "with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}",
710 old_anonymous_lifetime_mode
711 );
94b46f34
XL
712 result
713 }
714
dc9dc135 715 /// Creates a new `hir::GenericParam` for every new lifetime and
0531ce1d
XL
716 /// type parameter encountered while evaluating `f`. Definitions
717 /// are created with the parent provided. If no `parent_id` is
718 /// provided, no definitions will be returned.
719 ///
720 /// Presuming that in-band lifetimes are enabled, then
721 /// `self.anonymous_lifetime_mode` will be updated to match the
e1599b0c 722 /// parameter while `f` is running (and restored afterwards).
dfeec247 723 fn collect_in_band_defs<T>(
ff7c6d11 724 &mut self,
ba9703b0 725 parent_def_id: LocalDefId,
0531ce1d 726 anonymous_lifetime_mode: AnonymousLifetimeMode,
dfeec247
XL
727 f: impl FnOnce(&mut Self) -> (Vec<hir::GenericParam<'hir>>, T),
728 ) -> (Vec<hir::GenericParam<'hir>>, T) {
ff7c6d11
XL
729 assert!(!self.is_collecting_in_band_lifetimes);
730 assert!(self.lifetimes_to_define.is_empty());
0531ce1d 731 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
ff7c6d11 732
0bf4aa26
XL
733 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
734 self.is_collecting_in_band_lifetimes = true;
ff7c6d11 735
8faf50e0 736 let (in_band_ty_params, res) = f(self);
ff7c6d11
XL
737
738 self.is_collecting_in_band_lifetimes = false;
0531ce1d 739 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
ff7c6d11 740
ff7c6d11
XL
741 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
742
0531ce1d
XL
743 let params = lifetimes_to_define
744 .into_iter()
ba9703b0 745 .map(|(span, hir_name)| self.lifetime_to_generic_param(span, hir_name, parent_def_id))
8faf50e0 746 .chain(in_band_ty_params.into_iter())
0531ce1d 747 .collect();
ff7c6d11
XL
748
749 (params, res)
750 }
751
532ac7d7
XL
752 /// Converts a lifetime into a new generic parameter.
753 fn lifetime_to_generic_param(
754 &mut self,
755 span: Span,
756 hir_name: ParamName,
ba9703b0 757 parent_def_id: LocalDefId,
dfeec247 758 ) -> hir::GenericParam<'hir> {
60c5eb7d 759 let node_id = self.resolver.next_node_id();
532ac7d7
XL
760
761 // Get the name we'll use to make the def-path. Note
762 // that collisions are ok here and this shouldn't
763 // really show up for end-user.
764 let (str_name, kind) = match hir_name {
dfeec247
XL
765 ParamName::Plain(ident) => (ident.name, hir::LifetimeParamKind::InBand),
766 ParamName::Fresh(_) => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Elided),
767 ParamName::Error => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Error),
532ac7d7
XL
768 };
769
770 // Add a definition for the in-band lifetime def.
771 self.resolver.definitions().create_def_with_parent(
ba9703b0 772 parent_def_id,
532ac7d7 773 node_id,
48663c56 774 DefPathData::LifetimeNs(str_name),
416331ca 775 ExpnId::root(),
532ac7d7
XL
776 span,
777 );
778
779 hir::GenericParam {
48663c56 780 hir_id: self.lower_node_id(node_id),
532ac7d7 781 name: hir_name,
dfeec247
XL
782 attrs: &[],
783 bounds: &[],
532ac7d7
XL
784 span,
785 pure_wrt_drop: false,
dfeec247 786 kind: hir::GenericParamKind::Lifetime { kind },
532ac7d7
XL
787 }
788 }
789
0531ce1d
XL
790 /// When there is a reference to some lifetime `'a`, and in-band
791 /// lifetimes are enabled, then we want to push that lifetime into
792 /// the vector of names to define later. In that case, it will get
793 /// added to the appropriate generics.
8faf50e0 794 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
0531ce1d
XL
795 if !self.is_collecting_in_band_lifetimes {
796 return;
797 }
798
b7449926
XL
799 if !self.sess.features_untracked().in_band_lifetimes {
800 return;
801 }
802
ba9703b0 803 if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.normalize_to_macros_2_0())) {
0531ce1d
XL
804 return;
805 }
806
8faf50e0 807 let hir_name = ParamName::Plain(ident);
0531ce1d 808
ba9703b0
XL
809 if self.lifetimes_to_define.iter().any(|(_, lt_name)| {
810 lt_name.normalize_to_macros_2_0() == hir_name.normalize_to_macros_2_0()
811 }) {
0531ce1d
XL
812 return;
813 }
814
8faf50e0 815 self.lifetimes_to_define.push((ident.span, hir_name));
0531ce1d
XL
816 }
817
818 /// When we have either an elided or `'_` lifetime in an impl
0bf4aa26 819 /// header, we convert it to an in-band lifetime.
8faf50e0 820 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
0531ce1d 821 assert!(self.is_collecting_in_band_lifetimes);
e1599b0c 822 let index = self.lifetimes_to_define.len() + self.in_scope_lifetimes.len();
8faf50e0 823 let hir_name = ParamName::Fresh(index);
0531ce1d
XL
824 self.lifetimes_to_define.push((span, hir_name));
825 hir_name
826 }
827
8faf50e0 828 // Evaluates `f` with the lifetimes in `params` in-scope.
ff7c6d11
XL
829 // This is used to track which lifetimes have already been defined, and
830 // which are new in-band lifetimes that need to have a definition created
831 // for them.
dfeec247
XL
832 fn with_in_scope_lifetime_defs<T>(
833 &mut self,
834 params: &[GenericParam],
835 f: impl FnOnce(&mut Self) -> T,
836 ) -> T {
ff7c6d11 837 let old_len = self.in_scope_lifetimes.len();
8faf50e0 838 let lt_def_names = params.iter().filter_map(|param| match param.kind {
ba9703b0
XL
839 GenericParamKind::Lifetime { .. } => {
840 Some(ParamName::Plain(param.ident.normalize_to_macros_2_0()))
841 }
8faf50e0
XL
842 _ => None,
843 });
ff7c6d11
XL
844 self.in_scope_lifetimes.extend(lt_def_names);
845
846 let res = f(self);
847
848 self.in_scope_lifetimes.truncate(old_len);
849 res
850 }
851
0531ce1d
XL
852 /// Appends in-band lifetime defs and argument-position `impl
853 /// Trait` defs to the existing set of generics.
854 ///
855 /// Presuming that in-band lifetimes are enabled, then
856 /// `self.anonymous_lifetime_mode` will be updated to match the
e1599b0c 857 /// parameter while `f` is running (and restored afterwards).
dfeec247 858 fn add_in_band_defs<T>(
ff7c6d11
XL
859 &mut self,
860 generics: &Generics,
ba9703b0 861 parent_def_id: LocalDefId,
0531ce1d 862 anonymous_lifetime_mode: AnonymousLifetimeMode,
dfeec247
XL
863 f: impl FnOnce(&mut Self, &mut Vec<hir::GenericParam<'hir>>) -> T,
864 ) -> (hir::Generics<'hir>, T) {
865 let (in_band_defs, (mut lowered_generics, res)) =
866 self.with_in_scope_lifetime_defs(&generics.params, |this| {
ba9703b0 867 this.collect_in_band_defs(parent_def_id, anonymous_lifetime_mode, |this| {
8faf50e0 868 let mut params = Vec::new();
532ac7d7
XL
869 // Note: it is necessary to lower generics *before* calling `f`.
870 // When lowering `async fn`, there's a final step when lowering
871 // the return type that assumes that all in-scope lifetimes have
872 // already been added to either `in_scope_lifetimes` or
873 // `lifetimes_to_define`. If we swapped the order of these two,
874 // in-band-lifetimes introduced by generics or where-clauses
875 // wouldn't have been added yet.
dfeec247
XL
876 let generics =
877 this.lower_generics_mut(generics, ImplTraitContext::Universal(&mut params));
8faf50e0
XL
878 let res = f(this, &mut params);
879 (params, (generics, res))
0531ce1d 880 })
dfeec247 881 });
ff7c6d11 882
dfeec247
XL
883 let mut lowered_params: Vec<_> =
884 lowered_generics.params.into_iter().chain(in_band_defs).collect();
ff7c6d11 885
dc9dc135
XL
886 // FIXME(const_generics): the compiler doesn't always cope with
887 // unsorted generic parameters at the moment, so we make sure
888 // that they're ordered correctly here for now. (When we chain
889 // the `in_band_defs`, we might make the order unsorted.)
dfeec247
XL
890 lowered_params.sort_by_key(|param| match param.kind {
891 hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime,
892 hir::GenericParamKind::Type { .. } => ParamKindOrd::Type,
893 hir::GenericParamKind::Const { .. } => ParamKindOrd::Const,
dc9dc135
XL
894 });
895
416331ca 896 lowered_generics.params = lowered_params.into();
8bb4bdeb 897
dfeec247 898 let lowered_generics = lowered_generics.into_generics(self.arena);
416331ca 899 (lowered_generics, res)
8bb4bdeb
XL
900 }
901
dfeec247 902 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
dc9dc135
XL
903 let was_in_dyn_type = self.is_in_dyn_type;
904 self.is_in_dyn_type = in_scope;
905
906 let result = f(self);
907
908 self.is_in_dyn_type = was_in_dyn_type;
909
910 result
911 }
912
dfeec247 913 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
8bb4bdeb
XL
914 let was_in_loop_condition = self.is_in_loop_condition;
915 self.is_in_loop_condition = false;
916
416331ca
XL
917 let catch_scopes = mem::take(&mut self.catch_scopes);
918 let loop_scopes = mem::take(&mut self.loop_scopes);
0bf4aa26 919 let ret = f(self);
cc61c64b
XL
920 self.catch_scopes = catch_scopes;
921 self.loop_scopes = loop_scopes;
8bb4bdeb
XL
922
923 self.is_in_loop_condition = was_in_loop_condition;
924
0bf4aa26 925 ret
8bb4bdeb
XL
926 }
927
dfeec247
XL
928 fn lower_attrs(&mut self, attrs: &[Attribute]) -> &'hir [Attribute] {
929 self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)))
416331ca
XL
930 }
931
ea8adc8c 932 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
13cf67c4
XL
933 // Note that we explicitly do not walk the path. Since we don't really
934 // lower attributes (we use the AST version) there is nowhere to keep
0731742a 935 // the `HirId`s. We don't actually need HIR version of attributes anyway.
60c5eb7d 936 let kind = match attr.kind {
dfeec247
XL
937 AttrKind::Normal(ref item) => AttrKind::Normal(AttrItem {
938 path: item.path.clone(),
939 args: self.lower_mac_args(&item.args),
940 }),
941 AttrKind::DocComment(comment) => AttrKind::DocComment(comment),
60c5eb7d
XL
942 };
943
dfeec247 944 Attribute { kind, id: attr.id, style: attr.style, span: attr.span }
ea8adc8c
XL
945 }
946
60c5eb7d
XL
947 fn lower_mac_args(&mut self, args: &MacArgs) -> MacArgs {
948 match *args {
949 MacArgs::Empty => MacArgs::Empty,
dfeec247
XL
950 MacArgs::Delimited(dspan, delim, ref tokens) => {
951 MacArgs::Delimited(dspan, delim, self.lower_token_stream(tokens.clone()))
952 }
953 MacArgs::Eq(eq_span, ref tokens) => {
954 MacArgs::Eq(eq_span, self.lower_token_stream(tokens.clone()))
955 }
60c5eb7d
XL
956 }
957 }
958
ea8adc8c 959 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
dfeec247 960 tokens.into_trees().flat_map(|tree| self.lower_token_tree(tree).into_trees()).collect()
ea8adc8c
XL
961 }
962
963 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
964 match tree {
dc9dc135 965 TokenTree::Token(token) => self.lower_token(token),
dfeec247
XL
966 TokenTree::Delimited(span, delim, tts) => {
967 TokenTree::Delimited(span, delim, self.lower_token_stream(tts)).into()
968 }
ea8adc8c
XL
969 }
970 }
971
dc9dc135
XL
972 fn lower_token(&mut self, token: Token) -> TokenStream {
973 match token.kind {
974 token::Interpolated(nt) => {
e74abb32 975 let tts = (self.nt_to_tokenstream)(&nt, &self.sess.parse_sess, token.span);
9fa01778
XL
976 self.lower_token_stream(tts)
977 }
dc9dc135 978 _ => TokenTree::Token(token).into(),
ea8adc8c 979 }
7453a54e 980 }
7453a54e 981
dc9dc135
XL
982 /// Given an associated type constraint like one of these:
983 ///
984 /// ```
985 /// T: Iterator<Item: Debug>
986 /// ^^^^^^^^^^^
987 /// T: Iterator<Item = Debug>
988 /// ^^^^^^^^^^^^
989 /// ```
990 ///
991 /// returns a `hir::TypeBinding` representing `Item`.
e1599b0c
XL
992 fn lower_assoc_ty_constraint(
993 &mut self,
994 constraint: &AssocTyConstraint,
dfeec247
XL
995 itctx: ImplTraitContext<'_, 'hir>,
996 ) -> hir::TypeBinding<'hir> {
e1599b0c 997 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
dc9dc135 998
e1599b0c 999 let kind = match constraint.kind {
dfeec247
XL
1000 AssocTyConstraintKind::Equality { ref ty } => {
1001 hir::TypeBindingKind::Equality { ty: self.lower_ty(ty, itctx) }
1002 }
dc9dc135
XL
1003 AssocTyConstraintKind::Bound { ref bounds } => {
1004 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1005 let (desugar_to_impl_trait, itctx) = match itctx {
1006 // We are in the return position:
1007 //
1008 // fn foo() -> impl Iterator<Item: Debug>
1009 //
1010 // so desugar to
1011 //
1012 // fn foo() -> impl Iterator<Item = impl Debug>
74b04a01 1013 ImplTraitContext::OpaqueTy(..) => (true, itctx),
dc9dc135
XL
1014
1015 // We are in the argument position, but within a dyn type:
1016 //
1017 // fn foo(x: dyn Iterator<Item: Debug>)
1018 //
1019 // so desugar to
1020 //
1021 // fn foo(x: dyn Iterator<Item = impl Debug>)
74b04a01 1022 ImplTraitContext::Universal(..) if self.is_in_dyn_type => (true, itctx),
dc9dc135
XL
1023
1024 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1025 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1026 // "impl trait context" to permit `impl Debug` in this position (it desugars
416331ca 1027 // then to an opaque type).
dc9dc135
XL
1028 //
1029 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
dfeec247 1030 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => {
74b04a01 1031 (true, ImplTraitContext::OpaqueTy(None, hir::OpaqueTyOrigin::Misc))
dfeec247 1032 }
dc9dc135 1033
e1599b0c 1034 // We are in the parameter position, but not within a dyn type:
dc9dc135
XL
1035 //
1036 // fn foo(x: impl Iterator<Item: Debug>)
1037 //
1038 // so we leave it as is and this gets expanded in astconv to a bound like
1039 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1040 // `impl Iterator`.
1041 _ => (false, itctx),
1042 };
1043
1044 if desugar_to_impl_trait {
1045 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1046 // constructing the HIR for `impl bounds...` and then lowering that.
1047
60c5eb7d 1048 let impl_trait_node_id = self.resolver.next_node_id();
ba9703b0 1049 let parent_def_id = self.current_hir_id_owner.last().unwrap().0;
dc9dc135 1050 self.resolver.definitions().create_def_with_parent(
ba9703b0 1051 parent_def_id,
dc9dc135
XL
1052 impl_trait_node_id,
1053 DefPathData::ImplTrait,
416331ca 1054 ExpnId::root(),
e1599b0c 1055 constraint.span,
dc9dc135
XL
1056 );
1057
1058 self.with_dyn_type_scope(false, |this| {
60c5eb7d 1059 let node_id = this.resolver.next_node_id();
dc9dc135
XL
1060 let ty = this.lower_ty(
1061 &Ty {
60c5eb7d 1062 id: node_id,
e74abb32 1063 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
e1599b0c 1064 span: constraint.span,
dc9dc135
XL
1065 },
1066 itctx,
1067 );
1068
dfeec247 1069 hir::TypeBindingKind::Equality { ty }
dc9dc135
XL
1070 })
1071 } else {
1072 // Desugar `AssocTy: Bounds` into a type binding where the
1073 // later desugars into a trait predicate.
1074 let bounds = self.lower_param_bounds(bounds, itctx);
1075
dfeec247 1076 hir::TypeBindingKind::Constraint { bounds }
dc9dc135
XL
1077 }
1078 }
1079 };
1080
a7813a04 1081 hir::TypeBinding {
e1599b0c
XL
1082 hir_id: self.lower_node_id(constraint.id),
1083 ident: constraint.ident,
dc9dc135 1084 kind,
e1599b0c 1085 span: constraint.span,
a7813a04 1086 }
92a42be0 1087 }
e9174d1e 1088
60c5eb7d
XL
1089 fn lower_generic_arg(
1090 &mut self,
1091 arg: &ast::GenericArg,
dfeec247
XL
1092 itctx: ImplTraitContext<'_, 'hir>,
1093 ) -> hir::GenericArg<'hir> {
8faf50e0
XL
1094 match arg {
1095 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(&lt)),
60c5eb7d 1096 ast::GenericArg::Type(ty) => {
74b04a01 1097 // We parse const arguments as path types as we cannot distinguish them during
60c5eb7d
XL
1098 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1099 // type and value namespaces. If we resolved the path in the value namespace, we
1100 // transform it into a generic const argument.
1101 if let TyKind::Path(ref qself, ref path) = ty.kind {
1102 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1103 let res = partial_res.base_res();
1104 if !res.matches_ns(Namespace::TypeNS) {
1105 debug!(
1106 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1107 ty,
1108 );
1109
1110 // Construct a AnonConst where the expr is the "ty"'s path.
1111
ba9703b0 1112 let parent_def_id = self.current_hir_id_owner.last().unwrap().0;
60c5eb7d
XL
1113 let node_id = self.resolver.next_node_id();
1114
1115 // Add a definition for the in-band const def.
1116 self.resolver.definitions().create_def_with_parent(
ba9703b0 1117 parent_def_id,
60c5eb7d
XL
1118 node_id,
1119 DefPathData::AnonConst,
1120 ExpnId::root(),
1121 ty.span,
1122 );
1123
1124 let path_expr = Expr {
1125 id: ty.id,
1126 kind: ExprKind::Path(qself.clone(), path.clone()),
1127 span: ty.span,
dfeec247 1128 attrs: AttrVec::new(),
60c5eb7d
XL
1129 };
1130
dfeec247
XL
1131 let ct = self.with_new_scopes(|this| hir::AnonConst {
1132 hir_id: this.lower_node_id(node_id),
1133 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
60c5eb7d 1134 });
dfeec247 1135 return GenericArg::Const(ConstArg { value: ct, span: ty.span });
60c5eb7d
XL
1136 }
1137 }
1138 }
1139 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1140 }
dfeec247
XL
1141 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1142 value: self.lower_anon_const(&ct),
1143 span: ct.value.span,
1144 }),
8faf50e0
XL
1145 }
1146 }
1147
dfeec247
XL
1148 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_, 'hir>) -> &'hir hir::Ty<'hir> {
1149 self.arena.alloc(self.lower_ty_direct(t, itctx))
8faf50e0
XL
1150 }
1151
dc9dc135
XL
1152 fn lower_path_ty(
1153 &mut self,
1154 t: &Ty,
1155 qself: &Option<QSelf>,
1156 path: &Path,
1157 param_mode: ParamMode,
dfeec247
XL
1158 itctx: ImplTraitContext<'_, 'hir>,
1159 ) -> hir::Ty<'hir> {
dc9dc135
XL
1160 let id = self.lower_node_id(t.id);
1161 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1162 let ty = self.ty_path(id, t.span, qpath);
e74abb32 1163 if let hir::TyKind::TraitObject(..) = ty.kind {
dc9dc135
XL
1164 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1165 }
1166 ty
1167 }
1168
dfeec247
XL
1169 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1170 hir::Ty { hir_id: self.next_id(), kind, span }
1171 }
1172
1173 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1174 self.ty(span, hir::TyKind::Tup(tys))
1175 }
1176
1177 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_, 'hir>) -> hir::Ty<'hir> {
e74abb32 1178 let kind = match t.kind {
8faf50e0
XL
1179 TyKind::Infer => hir::TyKind::Infer,
1180 TyKind::Err => hir::TyKind::Err,
1181 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1182 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
cc61c64b 1183 TyKind::Rptr(ref region, ref mt) => {
0bf4aa26 1184 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
cc61c64b
XL
1185 let lifetime = match *region {
1186 Some(ref lt) => self.lower_lifetime(lt),
0531ce1d 1187 None => self.elided_ref_lifetime(span),
cc61c64b 1188 };
8faf50e0 1189 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
cc61c64b 1190 }
dfeec247
XL
1191 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(&f.generic_params, |this| {
1192 this.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
1193 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1194 generic_params: this.lower_generic_params(
1195 &f.generic_params,
1196 &NodeMap::default(),
1197 ImplTraitContext::disallowed(),
1198 ),
74b04a01 1199 unsafety: this.lower_unsafety(f.unsafety),
dfeec247
XL
1200 abi: this.lower_extern(f.ext),
1201 decl: this.lower_fn_decl(&f.decl, None, false, None),
1202 param_names: this.lower_fn_params_to_names(&f.decl),
1203 }))
1204 })
1205 }),
8faf50e0 1206 TyKind::Never => hir::TyKind::Never,
cc61c64b 1207 TyKind::Tup(ref tys) => {
dfeec247
XL
1208 hir::TyKind::Tup(self.arena.alloc_from_iter(
1209 tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())),
1210 ))
cc61c64b
XL
1211 }
1212 TyKind::Paren(ref ty) => {
8faf50e0 1213 return self.lower_ty_direct(ty, itctx);
cc61c64b
XL
1214 }
1215 TyKind::Path(ref qself, ref path) => {
dc9dc135 1216 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
cc61c64b 1217 }
48663c56
XL
1218 TyKind::ImplicitSelf => {
1219 let res = self.expect_full_res(t.id);
1220 let res = self.lower_res(res);
1221 hir::TyKind::Path(hir::QPath::Resolved(
1222 None,
dfeec247 1223 self.arena.alloc(hir::Path {
48663c56 1224 res,
dfeec247 1225 segments: arena_vec![self; hir::PathSegment::from_ident(
e1599b0c 1226 Ident::with_dummy_span(kw::SelfUpper)
48663c56
XL
1227 )],
1228 span: t.span,
1229 }),
1230 ))
dfeec247 1231 }
cc61c64b 1232 TyKind::Array(ref ty, ref length) => {
8faf50e0 1233 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
cc61c64b 1234 }
dfeec247 1235 TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
0531ce1d 1236 TyKind::TraitObject(ref bounds, kind) => {
cc61c64b 1237 let mut lifetime_bound = None;
dc9dc135 1238 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
dfeec247
XL
1239 let bounds =
1240 this.arena.alloc_from_iter(bounds.iter().filter_map(
1241 |bound| match *bound {
ba9703b0
XL
1242 GenericBound::Trait(
1243 ref ty,
1244 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1245 ) => Some(this.lower_poly_trait_ref(ty, itctx.reborrow())),
dfeec247
XL
1246 // `?const ?Bound` will cause an error during AST validation
1247 // anyways, so treat it like `?Bound` as compilation proceeds.
ba9703b0
XL
1248 GenericBound::Trait(
1249 _,
1250 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1251 ) => None,
dfeec247
XL
1252 GenericBound::Outlives(ref lifetime) => {
1253 if lifetime_bound.is_none() {
1254 lifetime_bound = Some(this.lower_lifetime(lifetime));
1255 }
1256 None
1257 }
1258 },
1259 ));
dc9dc135
XL
1260 let lifetime_bound =
1261 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1262 (bounds, lifetime_bound)
1263 });
0531ce1d
XL
1264 if kind != TraitObjectSyntax::Dyn {
1265 self.maybe_lint_bare_trait(t.span, t.id, false);
1266 }
8faf50e0 1267 hir::TyKind::TraitObject(bounds, lifetime_bound)
cc61c64b 1268 }
8faf50e0 1269 TyKind::ImplTrait(def_node_id, ref bounds) => {
ff7c6d11 1270 let span = t.span;
abe05a73 1271 match itctx {
74b04a01
XL
1272 ImplTraitContext::OpaqueTy(fn_def_id, origin) => {
1273 self.lower_opaque_impl_trait(span, fn_def_id, origin, def_node_id, |this| {
dfeec247
XL
1274 this.lower_param_bounds(bounds, itctx)
1275 })
8faf50e0
XL
1276 }
1277 ImplTraitContext::Universal(in_band_ty_params) => {
0731742a 1278 // Add a definition for the in-band `Param`.
ba9703b0 1279 let def_id = self.resolver.definitions().local_def_id(def_node_id);
ff7c6d11 1280
8faf50e0
XL
1281 let hir_bounds = self.lower_param_bounds(
1282 bounds,
1283 ImplTraitContext::Universal(in_band_ty_params),
ff7c6d11 1284 );
0731742a 1285 // Set the name to `impl Bound1 + Bound2`.
e1599b0c 1286 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
8faf50e0 1287 in_band_ty_params.push(hir::GenericParam {
48663c56 1288 hir_id: self.lower_node_id(def_node_id),
8faf50e0
XL
1289 name: ParamName::Plain(ident),
1290 pure_wrt_drop: false,
dfeec247 1291 attrs: &[],
ff7c6d11 1292 bounds: hir_bounds,
ff7c6d11 1293 span,
8faf50e0
XL
1294 kind: hir::GenericParamKind::Type {
1295 default: None,
1296 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
dfeec247 1297 },
ff7c6d11
XL
1298 });
1299
8faf50e0 1300 hir::TyKind::Path(hir::QPath::Resolved(
0531ce1d 1301 None,
dfeec247 1302 self.arena.alloc(hir::Path {
0531ce1d 1303 span,
ba9703b0 1304 res: Res::Def(DefKind::TyParam, def_id.to_def_id()),
dfeec247 1305 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
0531ce1d
XL
1306 }),
1307 ))
1308 }
0bf4aa26 1309 ImplTraitContext::Disallowed(pos) => {
dfeec247 1310 let allowed_in = if self.sess.features_untracked().impl_trait_in_bindings {
0bf4aa26
XL
1311 "bindings or function and inherent method return types"
1312 } else {
1313 "function and inherent method return types"
1314 };
1315 let mut err = struct_span_err!(
0531ce1d
XL
1316 self.sess,
1317 t.span,
1318 E0562,
0bf4aa26
XL
1319 "`impl Trait` not allowed outside of {}",
1320 allowed_in,
0531ce1d 1321 );
dfeec247
XL
1322 if pos == ImplTraitPosition::Binding && nightly_options::is_nightly_build()
1323 {
1324 err.help(
1325 "add `#![feature(impl_trait_in_bindings)]` to the crate \
1326 attributes to enable",
1327 );
0bf4aa26
XL
1328 }
1329 err.emit();
8faf50e0 1330 hir::TyKind::Err
abe05a73
XL
1331 }
1332 }
cc61c64b 1333 }
ba9703b0 1334 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
dfeec247
XL
1335 TyKind::CVarArgs => {
1336 self.sess.delay_span_bug(
1337 t.span,
1338 "`TyKind::CVarArgs` should have been handled elsewhere",
1339 );
1340 hir::TyKind::Err
1341 }
cc61c64b
XL
1342 };
1343
dfeec247 1344 hir::Ty { kind, span: t.span, hir_id: self.lower_node_id(t.id) }
8faf50e0
XL
1345 }
1346
416331ca 1347 fn lower_opaque_impl_trait(
8faf50e0
XL
1348 &mut self,
1349 span: Span,
0bf4aa26 1350 fn_def_id: Option<DefId>,
74b04a01 1351 origin: hir::OpaqueTyOrigin,
416331ca 1352 opaque_ty_node_id: NodeId,
dfeec247
XL
1353 lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1354 ) -> hir::TyKind<'hir> {
e1599b0c
XL
1355 debug!(
1356 "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
dfeec247 1357 fn_def_id, opaque_ty_node_id, span,
e1599b0c
XL
1358 );
1359
8faf50e0
XL
1360 // Make sure we know that some funky desugaring has been going on here.
1361 // This is a first: there is code in other places like for loop
1362 // desugaring that explicitly states that we don't want to track that.
dc9dc135 1363 // Not tracking it makes lints in rustc and clippy very fragile, as
8faf50e0 1364 // frequently opened issues show.
dfeec247 1365 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
8faf50e0 1366
ba9703b0 1367 let opaque_ty_def_id = self.resolver.definitions().local_def_id(opaque_ty_node_id);
8faf50e0 1368
416331ca 1369 self.allocate_hir_id_counter(opaque_ty_node_id);
8faf50e0 1370
416331ca 1371 let hir_bounds = self.with_hir_id_owner(opaque_ty_node_id, lower_bounds);
8faf50e0 1372
ba9703b0
XL
1373 let (lifetimes, lifetime_defs) =
1374 self.lifetimes_from_impl_trait_bounds(opaque_ty_node_id, opaque_ty_def_id, &hir_bounds);
8faf50e0 1375
dfeec247 1376 debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes,);
e1599b0c 1377
dfeec247 1378 debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs,);
e1599b0c 1379
dfeec247 1380 self.with_hir_id_owner(opaque_ty_node_id, move |lctx| {
416331ca 1381 let opaque_ty_item = hir::OpaqueTy {
8faf50e0
XL
1382 generics: hir::Generics {
1383 params: lifetime_defs,
dfeec247 1384 where_clause: hir::WhereClause { predicates: &[], span },
8faf50e0
XL
1385 span,
1386 },
1387 bounds: hir_bounds,
0bf4aa26 1388 impl_trait_fn: fn_def_id,
74b04a01 1389 origin,
8faf50e0
XL
1390 };
1391
ba9703b0 1392 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id);
dfeec247
XL
1393 let opaque_ty_id =
1394 lctx.generate_opaque_type(opaque_ty_node_id, opaque_ty_item, span, opaque_ty_span);
8faf50e0 1395
0731742a 1396 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
416331ca 1397 hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, lifetimes)
a7813a04
XL
1398 })
1399 }
e9174d1e 1400
416331ca
XL
1401 /// Registers a new opaque type with the proper `NodeId`s and
1402 /// returns the lowered node-ID for the opaque type.
1403 fn generate_opaque_type(
532ac7d7 1404 &mut self,
416331ca 1405 opaque_ty_node_id: NodeId,
dfeec247 1406 opaque_ty_item: hir::OpaqueTy<'hir>,
532ac7d7 1407 span: Span,
416331ca 1408 opaque_ty_span: Span,
48663c56 1409 ) -> hir::HirId {
416331ca
XL
1410 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1411 let opaque_ty_id = self.lower_node_id(opaque_ty_node_id);
1412 // Generate an `type Foo = impl Trait;` declaration.
1413 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1414 let opaque_ty_item = hir::Item {
1415 hir_id: opaque_ty_id,
dc9dc135 1416 ident: Ident::invalid(),
532ac7d7 1417 attrs: Default::default(),
e74abb32 1418 kind: opaque_ty_item_kind,
532ac7d7 1419 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
416331ca 1420 span: opaque_ty_span,
532ac7d7
XL
1421 };
1422
1423 // Insert the item into the global item list. This usually happens
416331ca 1424 // automatically for all AST items. But this opaque type item
532ac7d7 1425 // does not actually exist in the AST.
416331ca
XL
1426 self.insert_item(opaque_ty_item);
1427 opaque_ty_id
532ac7d7
XL
1428 }
1429
ff7c6d11
XL
1430 fn lifetimes_from_impl_trait_bounds(
1431 &mut self,
416331ca 1432 opaque_ty_id: NodeId,
ba9703b0 1433 parent_def_id: LocalDefId,
dfeec247
XL
1434 bounds: hir::GenericBounds<'hir>,
1435 ) -> (&'hir [hir::GenericArg<'hir>], &'hir [hir::GenericParam<'hir>]) {
e1599b0c
XL
1436 debug!(
1437 "lifetimes_from_impl_trait_bounds(opaque_ty_id={:?}, \
ba9703b0 1438 parent_def_id={:?}, \
e1599b0c 1439 bounds={:#?})",
ba9703b0 1440 opaque_ty_id, parent_def_id, bounds,
e1599b0c
XL
1441 );
1442
dc9dc135 1443 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
ff7c6d11 1444 // appear in the bounds, excluding lifetimes that are created within the bounds.
0731742a 1445 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
dfeec247
XL
1446 struct ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1447 context: &'r mut LoweringContext<'a, 'hir>,
ba9703b0 1448 parent: LocalDefId,
416331ca 1449 opaque_ty_id: NodeId,
ff7c6d11
XL
1450 collect_elided_lifetimes: bool,
1451 currently_bound_lifetimes: Vec<hir::LifetimeName>,
b7449926 1452 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
dfeec247
XL
1453 output_lifetimes: Vec<hir::GenericArg<'hir>>,
1454 output_lifetime_params: Vec<hir::GenericParam<'hir>>,
ff7c6d11
XL
1455 }
1456
dfeec247 1457 impl<'r, 'a, 'v, 'hir> intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a, 'hir> {
ba9703b0 1458 type Map = intravisit::ErasedMap<'v>;
dfeec247 1459
ba9703b0 1460 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
dfeec247 1461 intravisit::NestedVisitorMap::None
ff7c6d11
XL
1462 }
1463
dfeec247 1464 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs<'v>) {
ff7c6d11
XL
1465 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1466 if parameters.parenthesized {
1467 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1468 self.collect_elided_lifetimes = false;
dfeec247 1469 intravisit::walk_generic_args(self, span, parameters);
ff7c6d11
XL
1470 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1471 } else {
dfeec247 1472 intravisit::walk_generic_args(self, span, parameters);
ff7c6d11
XL
1473 }
1474 }
1475
dfeec247 1476 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
0731742a 1477 // Don't collect elided lifetimes used inside of `fn()` syntax.
e74abb32 1478 if let hir::TyKind::BareFn(_) = t.kind {
ff7c6d11
XL
1479 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1480 self.collect_elided_lifetimes = false;
94b46f34
XL
1481
1482 // Record the "stack height" of `for<'a>` lifetime bindings
1483 // to be able to later fully undo their introduction.
1484 let old_len = self.currently_bound_lifetimes.len();
dfeec247 1485 intravisit::walk_ty(self, t);
94b46f34
XL
1486 self.currently_bound_lifetimes.truncate(old_len);
1487
ff7c6d11
XL
1488 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1489 } else {
dfeec247 1490 intravisit::walk_ty(self, t)
ff7c6d11
XL
1491 }
1492 }
1493
0531ce1d
XL
1494 fn visit_poly_trait_ref(
1495 &mut self,
dfeec247 1496 trait_ref: &'v hir::PolyTraitRef<'v>,
94b46f34 1497 modifier: hir::TraitBoundModifier,
0531ce1d 1498 ) {
94b46f34
XL
1499 // Record the "stack height" of `for<'a>` lifetime bindings
1500 // to be able to later fully undo their introduction.
ff7c6d11 1501 let old_len = self.currently_bound_lifetimes.len();
dfeec247 1502 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
94b46f34
XL
1503 self.currently_bound_lifetimes.truncate(old_len);
1504 }
ff7c6d11 1505
dfeec247 1506 fn visit_generic_param(&mut self, param: &'v hir::GenericParam<'v>) {
0731742a 1507 // Record the introduction of 'a in `for<'a> ...`.
8faf50e0 1508 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
94b46f34 1509 // Introduce lifetimes one at a time so that we can handle
0731742a 1510 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
8faf50e0
XL
1511 let lt_name = hir::LifetimeName::Param(param.name);
1512 self.currently_bound_lifetimes.push(lt_name);
ff7c6d11
XL
1513 }
1514
dfeec247 1515 intravisit::walk_generic_param(self, param);
ff7c6d11
XL
1516 }
1517
1518 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1519 let name = match lifetime.name {
0531ce1d 1520 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
ff7c6d11
XL
1521 if self.collect_elided_lifetimes {
1522 // Use `'_` for both implicit and underscore lifetimes in
416331ca 1523 // `type Foo<'_> = impl SomeTrait<'_>;`.
ff7c6d11
XL
1524 hir::LifetimeName::Underscore
1525 } else {
0531ce1d 1526 return;
ff7c6d11 1527 }
0531ce1d 1528 }
8faf50e0 1529 hir::LifetimeName::Param(_) => lifetime.name,
e1599b0c
XL
1530
1531 // Refers to some other lifetime that is "in
1532 // scope" within the type.
1533 hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
1534
0bf4aa26 1535 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
ff7c6d11
XL
1536 };
1537
0531ce1d 1538 if !self.currently_bound_lifetimes.contains(&name)
dfeec247
XL
1539 && !self.already_defined_lifetimes.contains(&name)
1540 {
ff7c6d11
XL
1541 self.already_defined_lifetimes.insert(name);
1542
8faf50e0 1543 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
48663c56 1544 hir_id: self.context.next_id(),
ff7c6d11
XL
1545 span: lifetime.span,
1546 name,
8faf50e0 1547 }));
ff7c6d11 1548
60c5eb7d 1549 let def_node_id = self.context.resolver.next_node_id();
48663c56 1550 let hir_id =
416331ca 1551 self.context.lower_node_id_with_owner(def_node_id, self.opaque_ty_id);
ff7c6d11
XL
1552 self.context.resolver.definitions().create_def_with_parent(
1553 self.parent,
1554 def_node_id,
e74abb32 1555 DefPathData::LifetimeNs(name.ident().name),
416331ca 1556 ExpnId::root(),
dfeec247
XL
1557 lifetime.span,
1558 );
8faf50e0 1559
0bf4aa26
XL
1560 let (name, kind) = match name {
1561 hir::LifetimeName::Underscore => (
e1599b0c 1562 hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
0bf4aa26
XL
1563 hir::LifetimeParamKind::Elided,
1564 ),
dfeec247
XL
1565 hir::LifetimeName::Param(param_name) => {
1566 (param_name, hir::LifetimeParamKind::Explicit)
1567 }
ba9703b0 1568 _ => panic!("expected `LifetimeName::Param` or `ParamName::Plain`"),
8faf50e0
XL
1569 };
1570
1571 self.output_lifetime_params.push(hir::GenericParam {
9fa01778 1572 hir_id,
94b46f34 1573 name,
8faf50e0
XL
1574 span: lifetime.span,
1575 pure_wrt_drop: false,
dfeec247
XL
1576 attrs: &[],
1577 bounds: &[],
1578 kind: hir::GenericParamKind::Lifetime { kind },
8faf50e0 1579 });
ff7c6d11
XL
1580 }
1581 }
1582 }
1583
1584 let mut lifetime_collector = ImplTraitLifetimeCollector {
1585 context: self,
ba9703b0 1586 parent: parent_def_id,
416331ca 1587 opaque_ty_id,
ff7c6d11
XL
1588 collect_elided_lifetimes: true,
1589 currently_bound_lifetimes: Vec::new(),
b7449926 1590 already_defined_lifetimes: FxHashSet::default(),
ff7c6d11
XL
1591 output_lifetimes: Vec::new(),
1592 output_lifetime_params: Vec::new(),
1593 };
1594
1595 for bound in bounds {
dfeec247 1596 intravisit::walk_param_bound(&mut lifetime_collector, &bound);
ff7c6d11
XL
1597 }
1598
dfeec247
XL
1599 let ImplTraitLifetimeCollector { output_lifetimes, output_lifetime_params, .. } =
1600 lifetime_collector;
32a655c1 1601
dc9dc135 1602 (
dfeec247
XL
1603 self.arena.alloc_from_iter(output_lifetimes),
1604 self.arena.alloc_from_iter(output_lifetime_params),
0531ce1d 1605 )
e9174d1e 1606 }
e9174d1e 1607
dfeec247 1608 fn lower_local(&mut self, l: &Local) -> (hir::Local<'hir>, SmallVec<[NodeId; 1]>) {
532ac7d7 1609 let mut ids = SmallVec::<[NodeId; 1]>::new();
0bf4aa26
XL
1610 if self.sess.features_untracked().impl_trait_in_bindings {
1611 if let Some(ref ty) = l.ty {
1612 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
1613 visitor.visit_ty(ty);
1614 }
1615 }
ba9703b0 1616 let parent_def_id = self.current_hir_id_owner.last().unwrap().0;
dfeec247
XL
1617 let ty = l.ty.as_ref().map(|t| {
1618 self.lower_ty(
1619 t,
1620 if self.sess.features_untracked().impl_trait_in_bindings {
ba9703b0
XL
1621 ImplTraitContext::OpaqueTy(
1622 Some(parent_def_id.to_def_id()),
1623 hir::OpaqueTyOrigin::Misc,
1624 )
dfeec247
XL
1625 } else {
1626 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
1627 },
1628 )
1629 });
1630 let init = l.init.as_ref().map(|e| self.lower_expr(e));
1631 (
1632 hir::Local {
1633 hir_id: self.lower_node_id(l.id),
1634 ty,
1635 pat: self.lower_pat(&l.pat),
1636 init,
1637 span: l.span,
1638 attrs: l.attrs.clone(),
1639 source: hir::LocalSource::Normal,
1640 },
1641 ids,
1642 )
a7813a04 1643 }
e9174d1e 1644
dfeec247 1645 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
e74abb32
XL
1646 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1647 // as they are not explicit in HIR/Ty function signatures.
1648 // (instead, the `c_variadic` flag is set to `true`)
1649 let mut inputs = &decl.inputs[..];
1650 if decl.c_variadic() {
1651 inputs = &inputs[..inputs.len() - 1];
1652 }
dfeec247
XL
1653 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1654 PatKind::Ident(_, ident, _) => ident,
1655 _ => Ident::new(kw::Invalid, param.pat.span),
1656 }))
32a655c1
SL
1657 }
1658
8faf50e0
XL
1659 // Lowers a function declaration.
1660 //
dc9dc135
XL
1661 // `decl`: the unlowered (AST) function declaration.
1662 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
8faf50e0 1663 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
dc9dc135
XL
1664 // `make_ret_async` is also `Some`.
1665 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1666 // This guards against trait declarations and implementations where `impl Trait` is
8faf50e0 1667 // disallowed.
dc9dc135
XL
1668 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1669 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1670 // return type `impl Trait` item.
0531ce1d
XL
1671 fn lower_fn_decl(
1672 &mut self,
1673 decl: &FnDecl,
dfeec247 1674 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam<'hir>>)>,
0531ce1d 1675 impl_trait_return_allow: bool,
8faf50e0 1676 make_ret_async: Option<NodeId>,
dfeec247
XL
1677 ) -> &'hir hir::FnDecl<'hir> {
1678 debug!(
1679 "lower_fn_decl(\
60c5eb7d
XL
1680 fn_decl: {:?}, \
1681 in_band_ty_params: {:?}, \
1682 impl_trait_return_allow: {}, \
1683 make_ret_async: {:?})",
dfeec247 1684 decl, in_band_ty_params, impl_trait_return_allow, make_ret_async,
60c5eb7d 1685 );
532ac7d7
XL
1686 let lt_mode = if make_ret_async.is_some() {
1687 // In `async fn`, argument-position elided lifetimes
1688 // must be transformed into fresh generic parameters so that
416331ca 1689 // they can be applied to the opaque `impl Trait` return type.
532ac7d7
XL
1690 AnonymousLifetimeMode::CreateParameter
1691 } else {
1692 self.anonymous_lifetime_mode
1693 };
1694
e74abb32
XL
1695 let c_variadic = decl.c_variadic();
1696
532ac7d7
XL
1697 // Remember how many lifetimes were already around so that we can
1698 // only look at the lifetime parameters introduced by the arguments.
532ac7d7 1699 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
e74abb32
XL
1700 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1701 // as they are not explicit in HIR/Ty function signatures.
1702 // (instead, the `c_variadic` flag is set to `true`)
1703 let mut inputs = &decl.inputs[..];
1704 if c_variadic {
1705 inputs = &inputs[..inputs.len() - 1];
1706 }
dfeec247
XL
1707 this.arena.alloc_from_iter(inputs.iter().map(|param| {
1708 if let Some((_, ibty)) = &mut in_band_ty_params {
1709 this.lower_ty_direct(&param.ty, ImplTraitContext::Universal(ibty))
1710 } else {
1711 this.lower_ty_direct(&param.ty, ImplTraitContext::disallowed())
1712 }
1713 }))
532ac7d7 1714 });
8faf50e0
XL
1715
1716 let output = if let Some(ret_id) = make_ret_async {
1717 self.lower_async_fn_ret_ty(
8faf50e0 1718 &decl.output,
dc9dc135 1719 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
8faf50e0
XL
1720 ret_id,
1721 )
1722 } else {
1723 match decl.output {
74b04a01
XL
1724 FnRetTy::Ty(ref ty) => {
1725 let context = match in_band_ty_params {
1726 Some((def_id, _)) if impl_trait_return_allow => {
1727 ImplTraitContext::OpaqueTy(Some(def_id), hir::OpaqueTyOrigin::FnReturn)
1728 }
1729 _ => ImplTraitContext::disallowed(),
1730 };
1731 hir::FnRetTy::Return(self.lower_ty(ty, context))
1732 }
1733 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(span),
8faf50e0
XL
1734 }
1735 };
1736
dfeec247 1737 self.arena.alloc(hir::FnDecl {
8faf50e0
XL
1738 inputs,
1739 output,
e74abb32 1740 c_variadic,
dfeec247
XL
1741 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1742 let is_mutable_pat = match arg.pat.kind {
ba9703b0
XL
1743 PatKind::Ident(BindingMode::ByValue(mt) | BindingMode::ByRef(mt), _, _) => {
1744 mt == Mutability::Mut
1745 }
dfeec247
XL
1746 _ => false,
1747 };
0bf4aa26 1748
dfeec247
XL
1749 match arg.ty.kind {
1750 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1751 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1752 // Given we are only considering `ImplicitSelf` types, we needn't consider
1753 // the case where we have a mutable pattern to a reference as that would
1754 // no longer be an `ImplicitSelf`.
1755 TyKind::Rptr(_, ref mt)
1756 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1757 {
1758 hir::ImplicitSelfKind::MutRef
0bf4aa26 1759 }
dfeec247
XL
1760 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1761 hir::ImplicitSelfKind::ImmRef
1762 }
1763 _ => hir::ImplicitSelfKind::None,
1764 }
1765 }),
a7813a04 1766 })
b039eaaf 1767 }
e9174d1e 1768
416331ca
XL
1769 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1770 // combined with the following definition of `OpaqueTy`:
532ac7d7 1771 //
416331ca 1772 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
8faf50e0 1773 //
e1599b0c 1774 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
dc9dc135
XL
1775 // `output`: unlowered output type (`T` in `-> T`)
1776 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
416331ca 1777 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
dc9dc135 1778 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
8faf50e0 1779 fn lower_async_fn_ret_ty(
0531ce1d 1780 &mut self,
74b04a01 1781 output: &FnRetTy,
8faf50e0 1782 fn_def_id: DefId,
416331ca 1783 opaque_ty_node_id: NodeId,
74b04a01 1784 ) -> hir::FnRetTy<'hir> {
e1599b0c
XL
1785 debug!(
1786 "lower_async_fn_ret_ty(\
1787 output={:?}, \
1788 fn_def_id={:?}, \
1789 opaque_ty_node_id={:?})",
1790 output, fn_def_id, opaque_ty_node_id,
1791 );
1792
532ac7d7 1793 let span = output.span();
8faf50e0 1794
dfeec247 1795 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
8faf50e0 1796
ba9703b0 1797 let opaque_ty_def_id = self.resolver.definitions().local_def_id(opaque_ty_node_id);
8faf50e0 1798
416331ca 1799 self.allocate_hir_id_counter(opaque_ty_node_id);
8faf50e0 1800
e1599b0c
XL
1801 // When we create the opaque type for this async fn, it is going to have
1802 // to capture all the lifetimes involved in the signature (including in the
1803 // return type). This is done by introducing lifetime parameters for:
1804 //
1805 // - all the explicitly declared lifetimes from the impl and function itself;
1806 // - all the elided lifetimes in the fn arguments;
1807 // - all the elided lifetimes in the return type.
1808 //
1809 // So for example in this snippet:
1810 //
1811 // ```rust
1812 // impl<'a> Foo<'a> {
1813 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1814 // // ^ '0 ^ '1 ^ '2
1815 // // elided lifetimes used below
1816 // }
1817 // }
1818 // ```
1819 //
1820 // we would create an opaque type like:
1821 //
1822 // ```
1823 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1824 // ```
1825 //
1826 // and we would then desugar `bar` to the equivalent of:
1827 //
1828 // ```rust
1829 // impl<'a> Foo<'a> {
1830 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1831 // }
1832 // ```
1833 //
1834 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1835 // this is because the elided lifetimes from the return type
1836 // should be figured out using the ordinary elision rules, and
1837 // this desugaring achieves that.
1838 //
1839 // The variable `input_lifetimes_count` tracks the number of
1840 // lifetime parameters to the opaque type *not counting* those
1841 // lifetimes elided in the return type. This includes those
1842 // that are explicitly declared (`in_scope_lifetimes`) and
1843 // those elided lifetimes we found in the arguments (current
1844 // content of `lifetimes_to_define`). Next, we will process
1845 // the return type, which will cause `lifetimes_to_define` to
1846 // grow.
1847 let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
1848
416331ca 1849 let (opaque_ty_id, lifetime_params) = self.with_hir_id_owner(opaque_ty_node_id, |this| {
e1599b0c
XL
1850 // We have to be careful to get elision right here. The
1851 // idea is that we create a lifetime parameter for each
1852 // lifetime in the return type. So, given a return type
1853 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1854 // Future<Output = &'1 [ &'2 u32 ]>`.
1855 //
1856 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1857 // hence the elision takes place at the fn site.
dfeec247
XL
1858 let future_bound = this
1859 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::CreateParameter, |this| {
1860 this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
1861 });
8faf50e0 1862
e1599b0c
XL
1863 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
1864
532ac7d7 1865 // Calculate all the lifetimes that should be captured
416331ca 1866 // by the opaque type. This should include all in-scope
532ac7d7
XL
1867 // lifetime parameters, including those defined in-band.
1868 //
1869 // Note: this must be done after lowering the output type,
1870 // as the output type may introduce new in-band lifetimes.
dfeec247
XL
1871 let lifetime_params: Vec<(Span, ParamName)> = this
1872 .in_scope_lifetimes
1873 .iter()
1874 .cloned()
1875 .map(|name| (name.ident().span, name))
1876 .chain(this.lifetimes_to_define.iter().cloned())
1877 .collect();
8faf50e0 1878
e1599b0c
XL
1879 debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes);
1880 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define);
1881 debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
1882
532ac7d7 1883 let generic_params =
dfeec247 1884 this.arena.alloc_from_iter(lifetime_params.iter().map(|(span, hir_name)| {
ba9703b0 1885 this.lifetime_to_generic_param(*span, *hir_name, opaque_ty_def_id)
dfeec247 1886 }));
8faf50e0 1887
416331ca 1888 let opaque_ty_item = hir::OpaqueTy {
532ac7d7
XL
1889 generics: hir::Generics {
1890 params: generic_params,
dfeec247 1891 where_clause: hir::WhereClause { predicates: &[], span },
532ac7d7
XL
1892 span,
1893 },
dfeec247 1894 bounds: arena_vec![this; future_bound],
532ac7d7 1895 impl_trait_fn: Some(fn_def_id),
416331ca 1896 origin: hir::OpaqueTyOrigin::AsyncFn,
8faf50e0
XL
1897 };
1898
ba9703b0 1899 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
dfeec247
XL
1900 let opaque_ty_id =
1901 this.generate_opaque_type(opaque_ty_node_id, opaque_ty_item, span, opaque_ty_span);
8faf50e0 1902
416331ca 1903 (opaque_ty_id, lifetime_params)
532ac7d7 1904 });
8faf50e0 1905
e1599b0c
XL
1906 // As documented above on the variable
1907 // `input_lifetimes_count`, we need to create the lifetime
1908 // arguments to our opaque type. Continuing with our example,
1909 // we're creating the type arguments for the return type:
1910 //
1911 // ```
1912 // Bar<'a, 'b, '0, '1, '_>
1913 // ```
1914 //
1915 // For the "input" lifetime parameters, we wish to create
1916 // references to the parameters themselves, including the
1917 // "implicit" ones created from parameter types (`'a`, `'b`,
1918 // '`0`, `'1`).
1919 //
1920 // For the "output" lifetime parameters, we just want to
1921 // generate `'_`.
dfeec247 1922 let mut generic_args: Vec<_> = lifetime_params[..input_lifetimes_count]
e1599b0c
XL
1923 .iter()
1924 .map(|&(span, hir_name)| {
1925 // Input lifetime like `'a` or `'1`:
1926 GenericArg::Lifetime(hir::Lifetime {
1927 hir_id: self.next_id(),
1928 span,
1929 name: hir::LifetimeName::Param(hir_name),
532ac7d7 1930 })
e1599b0c
XL
1931 })
1932 .collect();
dfeec247
XL
1933 generic_args.extend(lifetime_params[input_lifetimes_count..].iter().map(|&(span, _)|
1934 // Output lifetime like `'_`.
1935 GenericArg::Lifetime(hir::Lifetime {
1936 hir_id: self.next_id(),
1937 span,
1938 name: hir::LifetimeName::Implicit,
1939 })));
1940 let generic_args = self.arena.alloc_from_iter(generic_args);
8faf50e0 1941
dfeec247 1942 // Create the `Foo<...>` reference itself. Note that the `type
e1599b0c
XL
1943 // Foo = impl Trait` is, internally, created as a child of the
1944 // async fn, so the *type parameters* are inherited. It's
1945 // only the lifetime parameters that we must supply.
dfeec247
XL
1946 let opaque_ty_ref = hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, generic_args);
1947 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
74b04a01 1948 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
532ac7d7 1949 }
8faf50e0 1950
dc9dc135 1951 /// Transforms `-> T` into `Future<Output = T>`
532ac7d7
XL
1952 fn lower_async_fn_output_type_to_future_bound(
1953 &mut self,
74b04a01 1954 output: &FnRetTy,
532ac7d7
XL
1955 fn_def_id: DefId,
1956 span: Span,
dfeec247 1957 ) -> hir::GenericBound<'hir> {
532ac7d7
XL
1958 // Compute the `T` in `Future<Output = T>` from the return type.
1959 let output_ty = match output {
74b04a01
XL
1960 FnRetTy::Ty(ty) => {
1961 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
1962 // `impl Future` opaque type that `async fn` implicitly
1963 // generates.
1964 let context =
1965 ImplTraitContext::OpaqueTy(Some(fn_def_id), hir::OpaqueTyOrigin::FnReturn);
1966 self.lower_ty(ty, context)
1967 }
1968 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
532ac7d7 1969 };
8faf50e0 1970
532ac7d7 1971 // "<Output = T>"
dfeec247
XL
1972 let future_params = self.arena.alloc(hir::GenericArgs {
1973 args: &[],
1974 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
532ac7d7 1975 parenthesized: false,
8faf50e0
XL
1976 });
1977
532ac7d7
XL
1978 // ::std::future::Future<future_params>
1979 let future_path =
dfeec247 1980 self.std_path(span, &[sym::future, sym::Future], Some(future_params), false);
8faf50e0 1981
532ac7d7
XL
1982 hir::GenericBound::Trait(
1983 hir::PolyTraitRef {
dfeec247
XL
1984 trait_ref: hir::TraitRef { path: future_path, hir_ref_id: self.next_id() },
1985 bound_generic_params: &[],
532ac7d7
XL
1986 span,
1987 },
1988 hir::TraitBoundModifier::None,
1989 )
b039eaaf 1990 }
e9174d1e 1991
8faf50e0 1992 fn lower_param_bound(
0531ce1d 1993 &mut self,
8faf50e0 1994 tpb: &GenericBound,
dfeec247
XL
1995 itctx: ImplTraitContext<'_, 'hir>,
1996 ) -> hir::GenericBound<'hir> {
8faf50e0 1997 match *tpb {
dfeec247
XL
1998 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
1999 self.lower_poly_trait_ref(ty, itctx),
2000 self.lower_trait_bound_modifier(modifier),
2001 ),
8faf50e0
XL
2002 GenericBound::Outlives(ref lifetime) => {
2003 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2004 }
e9174d1e 2005 }
e9174d1e 2006 }
e9174d1e 2007
a7813a04 2008 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
83c7162d 2009 let span = l.ident.span;
8faf50e0 2010 match l.ident {
dfeec247
XL
2011 ident if ident.name == kw::StaticLifetime => {
2012 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static)
2013 }
2014 ident if ident.name == kw::UnderscoreLifetime => match self.anonymous_lifetime_mode {
2015 AnonymousLifetimeMode::CreateParameter => {
2016 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2017 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2018 }
ff7c6d11 2019
dfeec247
XL
2020 AnonymousLifetimeMode::PassThrough => {
2021 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2022 }
0bf4aa26 2023
dfeec247
XL
2024 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2025 },
8faf50e0
XL
2026 ident => {
2027 self.maybe_collect_in_band_lifetime(ident);
2028 let param_name = ParamName::Plain(ident);
2029 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
ff7c6d11 2030 }
0531ce1d
XL
2031 }
2032 }
ff7c6d11 2033
0531ce1d
XL
2034 fn new_named_lifetime(
2035 &mut self,
2036 id: NodeId,
2037 span: Span,
2038 name: hir::LifetimeName,
2039 ) -> hir::Lifetime {
dfeec247
XL
2040 hir::Lifetime { hir_id: self.lower_node_id(id), span, name }
2041 }
2042
2043 fn lower_generic_params_mut<'s>(
2044 &'s mut self,
2045 params: &'s [GenericParam],
2046 add_bounds: &'s NodeMap<Vec<GenericBound>>,
2047 mut itctx: ImplTraitContext<'s, 'hir>,
2048 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
2049 params
2050 .iter()
2051 .map(move |param| self.lower_generic_param(param, add_bounds, itctx.reborrow()))
b039eaaf 2052 }
e9174d1e 2053
8faf50e0
XL
2054 fn lower_generic_params(
2055 &mut self,
2056 params: &[GenericParam],
2057 add_bounds: &NodeMap<Vec<GenericBound>>,
dfeec247
XL
2058 itctx: ImplTraitContext<'_, 'hir>,
2059 ) -> &'hir [hir::GenericParam<'hir>] {
2060 self.arena.alloc_from_iter(self.lower_generic_params_mut(params, add_bounds, itctx))
2061 }
2062
2063 fn lower_generic_param(
2064 &mut self,
2065 param: &GenericParam,
2066 add_bounds: &NodeMap<Vec<GenericBound>>,
2067 mut itctx: ImplTraitContext<'_, 'hir>,
2068 ) -> hir::GenericParam<'hir> {
2069 let mut bounds: Vec<_> = self
2070 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2071 this.lower_param_bounds_mut(&param.bounds, itctx.reborrow()).collect()
2072 });
0bf4aa26 2073
9fa01778 2074 let (name, kind) = match param.kind {
8faf50e0
XL
2075 GenericParamKind::Lifetime => {
2076 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2077 self.is_collecting_in_band_lifetimes = false;
2078
dfeec247
XL
2079 let lt = self
2080 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2081 this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident })
2082 });
8faf50e0
XL
2083 let param_name = match lt.name {
2084 hir::LifetimeName::Param(param_name) => param_name,
0bf4aa26 2085 hir::LifetimeName::Implicit
dfeec247
XL
2086 | hir::LifetimeName::Underscore
2087 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
e1599b0c 2088 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
ba9703b0 2089 self.sess.diagnostic().span_bug(
e1599b0c
XL
2090 param.ident.span,
2091 "object-lifetime-default should not occur here",
2092 );
2093 }
0bf4aa26 2094 hir::LifetimeName::Error => ParamName::Error,
8faf50e0 2095 };
9fa01778 2096
dfeec247
XL
2097 let kind =
2098 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
ff7c6d11 2099
8faf50e0 2100 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
ff7c6d11 2101
9fa01778 2102 (param_name, kind)
8faf50e0
XL
2103 }
2104 GenericParamKind::Type { ref default, .. } => {
8faf50e0
XL
2105 let add_bounds = add_bounds.get(&param.id).map_or(&[][..], |x| &x);
2106 if !add_bounds.is_empty() {
dfeec247
XL
2107 let params = self.lower_param_bounds_mut(add_bounds, itctx.reborrow());
2108 bounds.extend(params);
8faf50e0 2109 }
e9174d1e 2110
9fa01778 2111 let kind = hir::GenericParamKind::Type {
74b04a01
XL
2112 default: default.as_ref().map(|x| {
2113 self.lower_ty(
2114 x,
2115 ImplTraitContext::OpaqueTy(None, hir::OpaqueTyOrigin::Misc),
2116 )
2117 }),
dfeec247
XL
2118 synthetic: param
2119 .attrs
2120 .iter()
2121 .filter(|attr| attr.check_name(sym::rustc_synthetic))
2122 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2123 .next(),
9fa01778
XL
2124 };
2125
e1599b0c 2126 (hir::ParamName::Plain(param.ident), kind)
8faf50e0 2127 }
9fa01778 2128 GenericParamKind::Const { ref ty } => {
dfeec247
XL
2129 let ty = self
2130 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2131 this.lower_ty(&ty, ImplTraitContext::disallowed())
2132 });
2133
2134 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const { ty })
9fa01778
XL
2135 }
2136 };
2137
9fa01778 2138 hir::GenericParam {
48663c56 2139 hir_id: self.lower_node_id(param.id),
9fa01778
XL
2140 name,
2141 span: param.ident.span,
48663c56 2142 pure_wrt_drop: attr::contains_name(&param.attrs, sym::may_dangle),
9fa01778 2143 attrs: self.lower_attrs(&param.attrs),
dfeec247 2144 bounds: self.arena.alloc_from_iter(bounds),
9fa01778 2145 kind,
8faf50e0 2146 }
e9174d1e 2147 }
e9174d1e 2148
dfeec247
XL
2149 fn lower_trait_ref(
2150 &mut self,
2151 p: &TraitRef,
2152 itctx: ImplTraitContext<'_, 'hir>,
2153 ) -> hir::TraitRef<'hir> {
abe05a73 2154 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
416331ca 2155 hir::QPath::Resolved(None, path) => path,
ba9703b0 2156 qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
32a655c1 2157 };
dfeec247 2158 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
e9174d1e 2159 }
e9174d1e 2160
0531ce1d
XL
2161 fn lower_poly_trait_ref(
2162 &mut self,
2163 p: &PolyTraitRef,
dfeec247
XL
2164 mut itctx: ImplTraitContext<'_, 'hir>,
2165 ) -> hir::PolyTraitRef<'hir> {
a1dfa0c6
XL
2166 let bound_generic_params = self.lower_generic_params(
2167 &p.bound_generic_params,
2168 &NodeMap::default(),
2169 itctx.reborrow(),
2170 );
dfeec247
XL
2171 let trait_ref = self.with_in_scope_lifetime_defs(&p.bound_generic_params, |this| {
2172 this.lower_trait_ref(&p.trait_ref, itctx)
2173 });
ff7c6d11 2174
dfeec247 2175 hir::PolyTraitRef { bound_generic_params, trait_ref, span: p.span }
b039eaaf 2176 }
e9174d1e 2177
dfeec247
XL
2178 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_, 'hir>) -> hir::MutTy<'hir> {
2179 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2180 }
2181
2182 fn lower_param_bounds(
2183 &mut self,
2184 bounds: &[GenericBound],
2185 itctx: ImplTraitContext<'_, 'hir>,
2186 ) -> hir::GenericBounds<'hir> {
2187 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
a7813a04 2188 }
e9174d1e 2189
dfeec247
XL
2190 fn lower_param_bounds_mut<'s>(
2191 &'s mut self,
2192 bounds: &'s [GenericBound],
2193 mut itctx: ImplTraitContext<'s, 'hir>,
2194 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2195 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx.reborrow()))
a7813a04 2196 }
e9174d1e 2197
dfeec247
XL
2198 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> &'hir hir::Block<'hir> {
2199 self.arena.alloc(self.lower_block_noalloc(b, targeted_by_break))
2200 }
2201
2202 fn lower_block_noalloc(&mut self, b: &Block, targeted_by_break: bool) -> hir::Block<'hir> {
e1599b0c 2203 let mut stmts = vec![];
dfeec247 2204 let mut expr: Option<&'hir _> = None;
3157f602 2205
cc61c64b
XL
2206 for (index, stmt) in b.stmts.iter().enumerate() {
2207 if index == b.stmts.len() - 1 {
e74abb32 2208 if let StmtKind::Expr(ref e) = stmt.kind {
dfeec247 2209 expr = Some(self.lower_expr(e));
cc61c64b
XL
2210 } else {
2211 stmts.extend(self.lower_stmt(stmt));
2212 }
3157f602 2213 } else {
cc61c64b 2214 stmts.extend(self.lower_stmt(stmt));
3157f602
XL
2215 }
2216 }
2217
dfeec247 2218 hir::Block {
48663c56 2219 hir_id: self.lower_node_id(b.id),
dfeec247 2220 stmts: self.arena.alloc_from_iter(stmts),
041b39d2 2221 expr,
a7813a04
XL
2222 rules: self.lower_block_check_mode(&b.rules),
2223 span: b.span,
041b39d2 2224 targeted_by_break,
dfeec247 2225 }
e9174d1e 2226 }
e9174d1e 2227
e1599b0c
XL
2228 /// Lowers a block directly to an expression, presuming that it
2229 /// has no attributes and is not targeted by a `break`.
dfeec247 2230 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
e1599b0c 2231 let block = self.lower_block(b, false);
dfeec247 2232 self.expr_block(block, AttrVec::new())
a7813a04 2233 }
b039eaaf 2234
416331ca 2235 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
dfeec247
XL
2236 self.with_new_scopes(|this| hir::AnonConst {
2237 hir_id: this.lower_node_id(c.id),
2238 body: this.lower_const_body(c.value.span, Some(&c.value)),
416331ca
XL
2239 })
2240 }
2241
dfeec247 2242 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt<'hir>; 1]> {
e74abb32 2243 let kind = match s.kind {
0bf4aa26
XL
2244 StmtKind::Local(ref l) => {
2245 let (l, item_ids) = self.lower_local(l);
dfeec247 2246 let mut ids: SmallVec<[hir::Stmt<'hir>; 1]> = item_ids
0bf4aa26 2247 .into_iter()
9fa01778 2248 .map(|item_id| {
48663c56
XL
2249 let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
2250 self.stmt(s.span, hir::StmtKind::Item(item_id))
0bf4aa26
XL
2251 })
2252 .collect();
9fa01778 2253 ids.push({
9fa01778 2254 hir::Stmt {
48663c56 2255 hir_id: self.lower_node_id(s.id),
dfeec247 2256 kind: hir::StmtKind::Local(self.arena.alloc(l)),
9fa01778
XL
2257 span: s.span,
2258 }
0bf4aa26
XL
2259 });
2260 return ids;
dfeec247 2261 }
476ff2be
SL
2262 StmtKind::Item(ref it) => {
2263 // Can only use the ID once.
2264 let mut id = Some(s.id);
dfeec247
XL
2265 return self
2266 .lower_item_id(it)
0531ce1d 2267 .into_iter()
9fa01778 2268 .map(|item_id| {
dfeec247
XL
2269 let hir_id = id
2270 .take()
2271 .map(|id| self.lower_node_id(id))
2272 .unwrap_or_else(|| self.next_id());
2273
2274 hir::Stmt { hir_id, kind: hir::StmtKind::Item(item_id), span: s.span }
0531ce1d
XL
2275 })
2276 .collect();
92a42be0 2277 }
dfeec247
XL
2278 StmtKind::Expr(ref e) => hir::StmtKind::Expr(self.lower_expr(e)),
2279 StmtKind::Semi(ref e) => hir::StmtKind::Semi(self.lower_expr(e)),
74b04a01 2280 StmtKind::Empty => return smallvec![],
ba9703b0 2281 StmtKind::MacCall(..) => panic!("shouldn't exist here"),
8faf50e0 2282 };
dfeec247 2283 smallvec![hir::Stmt { hir_id: self.lower_node_id(s.id), kind, span: s.span }]
e9174d1e 2284 }
e9174d1e 2285
a7813a04
XL
2286 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
2287 match *b {
dfeec247
XL
2288 BlockCheckMode::Default => hir::BlockCheckMode::DefaultBlock,
2289 BlockCheckMode::Unsafe(u) => {
2290 hir::BlockCheckMode::UnsafeBlock(self.lower_unsafe_source(u))
2291 }
a7813a04 2292 }
e9174d1e 2293 }
e9174d1e 2294
a7813a04
XL
2295 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2296 match u {
dfeec247
XL
2297 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2298 UserProvided => hir::UnsafeSource::UserProvided,
a7813a04 2299 }
e9174d1e 2300 }
e9174d1e 2301
a7813a04
XL
2302 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2303 match f {
2304 TraitBoundModifier::None => hir::TraitBoundModifier::None,
dfeec247
XL
2305 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2306
2307 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2308 // placeholder for compilation to proceed.
2309 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2310 hir::TraitBoundModifier::Maybe
2311 }
a7813a04 2312 }
e9174d1e 2313 }
e9174d1e 2314
a7813a04 2315 // Helper methods for building HIR.
b039eaaf 2316
dfeec247 2317 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
e74abb32 2318 hir::Stmt { span, kind, hir_id: self.next_id() }
48663c56
XL
2319 }
2320
dfeec247
XL
2321 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2322 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
416331ca
XL
2323 }
2324
0531ce1d
XL
2325 fn stmt_let_pat(
2326 &mut self,
dfeec247 2327 attrs: AttrVec,
48663c56 2328 span: Span,
dfeec247
XL
2329 init: Option<&'hir hir::Expr<'hir>>,
2330 pat: &'hir hir::Pat<'hir>,
0531ce1d 2331 source: hir::LocalSource,
dfeec247
XL
2332 ) -> hir::Stmt<'hir> {
2333 let local = hir::Local { attrs, hir_id: self.next_id(), init, pat, source, span, ty: None };
2334 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
7cac9316
XL
2335 }
2336
dfeec247
XL
2337 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2338 self.block_all(expr.span, &[], Some(expr))
a7813a04 2339 }
b039eaaf 2340
0531ce1d
XL
2341 fn block_all(
2342 &mut self,
2343 span: Span,
dfeec247
XL
2344 stmts: &'hir [hir::Stmt<'hir>],
2345 expr: Option<&'hir hir::Expr<'hir>>,
2346 ) -> &'hir hir::Block<'hir> {
2347 let blk = hir::Block {
041b39d2
XL
2348 stmts,
2349 expr,
48663c56 2350 hir_id: self.next_id(),
dfeec247 2351 rules: hir::BlockCheckMode::DefaultBlock,
041b39d2 2352 span,
cc61c64b 2353 targeted_by_break: false,
dfeec247
XL
2354 };
2355 self.arena.alloc(blk)
a7813a04 2356 }
b039eaaf 2357
48663c56 2358 /// Constructs a `true` or `false` literal pattern.
dfeec247 2359 fn pat_bool(&mut self, span: Span, val: bool) -> &'hir hir::Pat<'hir> {
dc9dc135 2360 let expr = self.expr_bool(span, val);
dfeec247 2361 self.pat(span, hir::PatKind::Lit(expr))
48663c56
XL
2362 }
2363
dfeec247
XL
2364 fn pat_ok(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2365 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], arena_vec![self; pat])
a7813a04 2366 }
b039eaaf 2367
dfeec247
XL
2368 fn pat_err(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2369 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], arena_vec![self; pat])
a7813a04 2370 }
b039eaaf 2371
dfeec247
XL
2372 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2373 self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], arena_vec![self; pat])
a7813a04 2374 }
b039eaaf 2375
dfeec247
XL
2376 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2377 self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], &[])
a7813a04 2378 }
b039eaaf 2379
0531ce1d
XL
2380 fn pat_std_enum(
2381 &mut self,
2382 span: Span,
48663c56 2383 components: &[Symbol],
dfeec247
XL
2384 subpats: &'hir [&'hir hir::Pat<'hir>],
2385 ) -> &'hir hir::Pat<'hir> {
8faf50e0 2386 let path = self.std_path(span, components, None, true);
dfeec247 2387 let qpath = hir::QPath::Resolved(None, path);
a7813a04 2388 let pt = if subpats.is_empty() {
476ff2be 2389 hir::PatKind::Path(qpath)
a7813a04 2390 } else {
476ff2be 2391 hir::PatKind::TupleStruct(qpath, subpats, None)
a7813a04 2392 };
476ff2be 2393 self.pat(span, pt)
e9174d1e 2394 }
e9174d1e 2395
dfeec247 2396 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
8faf50e0 2397 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
e9174d1e 2398 }
e9174d1e 2399
0531ce1d
XL
2400 fn pat_ident_binding_mode(
2401 &mut self,
2402 span: Span,
8faf50e0 2403 ident: Ident,
0531ce1d 2404 bm: hir::BindingAnnotation,
dfeec247 2405 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
48663c56 2406 let hir_id = self.next_id();
b039eaaf 2407
532ac7d7 2408 (
dfeec247 2409 self.arena.alloc(hir::Pat {
532ac7d7 2410 hir_id,
e74abb32 2411 kind: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
532ac7d7
XL
2412 span,
2413 }),
dfeec247 2414 hir_id,
532ac7d7 2415 )
a7813a04 2416 }
b039eaaf 2417
dfeec247 2418 fn pat_wild(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
a7813a04
XL
2419 self.pat(span, hir::PatKind::Wild)
2420 }
b039eaaf 2421
dfeec247
XL
2422 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2423 self.arena.alloc(hir::Pat { hir_id: self.next_id(), kind, span })
b039eaaf
SL
2424 }
2425
dc9dc135 2426 /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when
476ff2be
SL
2427 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
2428 /// The path is also resolved according to `is_value`.
8faf50e0
XL
2429 fn std_path(
2430 &mut self,
2431 span: Span,
48663c56 2432 components: &[Symbol],
dfeec247 2433 params: Option<&'hir hir::GenericArgs<'hir>>,
48663c56 2434 is_value: bool,
dfeec247 2435 ) -> &'hir hir::Path<'hir> {
416331ca
XL
2436 let ns = if is_value { Namespace::ValueNS } else { Namespace::TypeNS };
2437 let (path, res) = self.resolver.resolve_str_path(span, self.crate_root, components, ns);
13cf67c4 2438
dfeec247
XL
2439 let mut segments: Vec<_> = path
2440 .segments
2441 .iter()
2442 .map(|segment| {
2443 let res = self.expect_full_res(segment.id);
2444 hir::PathSegment {
2445 ident: segment.ident,
2446 hir_id: Some(self.lower_node_id(segment.id)),
2447 res: Some(self.lower_res(res)),
2448 infer_args: true,
2449 args: None,
2450 }
2451 })
2452 .collect();
dc9dc135
XL
2453 segments.last_mut().unwrap().args = params;
2454
dfeec247 2455 self.arena.alloc(hir::Path {
dc9dc135 2456 span,
e1599b0c 2457 res: res.map_id(|_| panic!("unexpected `NodeId`")),
dfeec247
XL
2458 segments: self.arena.alloc_from_iter(segments),
2459 })
a7813a04
XL
2460 }
2461
dfeec247
XL
2462 fn ty_path(
2463 &mut self,
2464 mut hir_id: hir::HirId,
2465 span: Span,
2466 qpath: hir::QPath<'hir>,
2467 ) -> hir::Ty<'hir> {
e74abb32 2468 let kind = match qpath {
32a655c1 2469 hir::QPath::Resolved(None, path) => {
8faf50e0 2470 // Turn trait object paths into `TyKind::TraitObject` instead.
48663c56 2471 match path.res {
ba9703b0 2472 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
a1dfa0c6 2473 let principal = hir::PolyTraitRef {
dfeec247
XL
2474 bound_generic_params: &[],
2475 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
a1dfa0c6
XL
2476 span,
2477 };
32a655c1 2478
a1dfa0c6
XL
2479 // The original ID is taken by the `PolyTraitRef`,
2480 // so the `Ty` itself needs a different one.
48663c56 2481 hir_id = self.next_id();
dfeec247
XL
2482 hir::TyKind::TraitObject(
2483 arena_vec![self; principal],
2484 self.elided_dyn_bound(span),
2485 )
a1dfa0c6
XL
2486 }
2487 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
32a655c1
SL
2488 }
2489 }
8faf50e0 2490 _ => hir::TyKind::Path(qpath),
32a655c1 2491 };
e74abb32 2492
dfeec247 2493 hir::Ty { hir_id, kind, span }
0531ce1d
XL
2494 }
2495
2496 /// Invoked to create the lifetime argument for a type `&T`
2497 /// with no explicit lifetime.
2498 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
2499 match self.anonymous_lifetime_mode {
532ac7d7
XL
2500 // Intercept when we are in an impl header or async fn and introduce an in-band
2501 // lifetime.
0531ce1d
XL
2502 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
2503 // `'f`.
2504 AnonymousLifetimeMode::CreateParameter => {
2505 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2506 hir::Lifetime {
48663c56 2507 hir_id: self.next_id(),
0531ce1d 2508 span,
8faf50e0 2509 name: hir::LifetimeName::Param(fresh_name),
0531ce1d
XL
2510 }
2511 }
2512
0bf4aa26
XL
2513 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
2514
0531ce1d
XL
2515 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
2516 }
2517 }
2518
0bf4aa26
XL
2519 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
2520 /// return a "error lifetime".
2521 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
2522 let (id, msg, label) = match id {
2523 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
2524
2525 None => (
60c5eb7d 2526 self.resolver.next_node_id(),
0bf4aa26
XL
2527 "`&` without an explicit lifetime name cannot be used here",
2528 "explicit lifetime name needed here",
2529 ),
2530 };
2531
dfeec247 2532 let mut err = struct_span_err!(self.sess, span, E0637, "{}", msg,);
0bf4aa26
XL
2533 err.span_label(span, label);
2534 err.emit();
2535
2536 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2537 }
2538
0531ce1d
XL
2539 /// Invoked to create the lifetime argument(s) for a path like
2540 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
2541 /// sorts of cases are deprecated. This may therefore report a warning or an
2542 /// error, depending on the mode.
dfeec247
XL
2543 fn elided_path_lifetimes<'s>(
2544 &'s mut self,
2545 span: Span,
2546 count: usize,
2547 ) -> impl Iterator<Item = hir::Lifetime> + Captures<'a> + Captures<'s> + Captures<'hir> {
2548 (0..count).map(move |_| self.elided_path_lifetime(span))
532ac7d7
XL
2549 }
2550
2551 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
0531ce1d 2552 match self.anonymous_lifetime_mode {
48663c56
XL
2553 AnonymousLifetimeMode::CreateParameter => {
2554 // We should have emitted E0726 when processing this path above
dfeec247
XL
2555 self.sess
2556 .delay_span_bug(span, "expected 'implicit elided lifetime not allowed' error");
60c5eb7d 2557 let id = self.resolver.next_node_id();
48663c56
XL
2558 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2559 }
e74abb32
XL
2560 // `PassThrough` is the normal case.
2561 // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
2562 // is unsuitable here, as these can occur from missing lifetime parameters in a
2563 // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
2564 // lifetime. Instead, we simply create an implicit lifetime, which will be checked
2565 // later, at which point a suitable error will be emitted.
dfeec247
XL
2566 AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
2567 self.new_implicit_lifetime(span)
2568 }
0531ce1d 2569 }
0531ce1d
XL
2570 }
2571
2572 /// Invoked to create the lifetime argument(s) for an elided trait object
2573 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2574 /// when the bound is written, even if it is written with `'_` like in
2575 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2576 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2577 match self.anonymous_lifetime_mode {
2578 // NB. We intentionally ignore the create-parameter mode here.
2579 // and instead "pass through" to resolve-lifetimes, which will apply
2580 // the object-lifetime-defaulting rules. Elided object lifetime defaults
2581 // do not act like other elided lifetimes. In other words, given this:
2582 //
2583 // impl Foo for Box<dyn Debug>
2584 //
2585 // we do not introduce a fresh `'_` to serve as the bound, but instead
2586 // ultimately translate to the equivalent of:
2587 //
2588 // impl Foo for Box<dyn Debug + 'static>
2589 //
2590 // `resolve_lifetime` has the code to make that happen.
2591 AnonymousLifetimeMode::CreateParameter => {}
2592
0bf4aa26
XL
2593 AnonymousLifetimeMode::ReportError => {
2594 // ReportError applies to explicit use of `'_`.
2595 }
2596
0531ce1d
XL
2597 // This is the normal case.
2598 AnonymousLifetimeMode::PassThrough => {}
2599 }
2600
e1599b0c
XL
2601 let r = hir::Lifetime {
2602 hir_id: self.next_id(),
2603 span,
2604 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2605 };
2606 debug!("elided_dyn_bound: r={:?}", r);
2607 r
532ac7d7
XL
2608 }
2609
0531ce1d 2610 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
dfeec247 2611 hir::Lifetime { hir_id: self.next_id(), span, name: hir::LifetimeName::Implicit }
9e0c209e 2612 }
0531ce1d 2613
e74abb32 2614 fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) {
416331ca
XL
2615 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
2616 // call site which do not have a macro backtrace. See #61963.
dfeec247
XL
2617 let is_macro_callsite = self
2618 .sess
2619 .source_map()
416331ca
XL
2620 .span_to_snippet(span)
2621 .map(|snippet| snippet.starts_with("#["))
2622 .unwrap_or(true);
2623 if !is_macro_callsite {
e74abb32 2624 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
74b04a01 2625 BARE_TRAIT_OBJECTS,
416331ca 2626 id,
48663c56 2627 span,
416331ca 2628 "trait objects without an explicit `dyn` are deprecated",
dfeec247 2629 BuiltinLintDiagnostics::BareTraitObject(span, is_global),
416331ca
XL
2630 )
2631 }
48663c56 2632 }
e9174d1e 2633}
8bb4bdeb 2634
dfeec247 2635fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body<'_>>) -> Vec<hir::BodyId> {
8bb4bdeb
XL
2636 // Sorting by span ensures that we get things in order within a
2637 // file, and also puts the files in a sensible order.
2638 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
2639 body_ids.sort_by_key(|b| bodies[b].value.span);
2640 body_ids
2641}
48663c56 2642
dfeec247
XL
2643/// Helper struct for delayed construction of GenericArgs.
2644struct GenericArgsCtor<'hir> {
2645 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2646 bindings: &'hir [hir::TypeBinding<'hir>],
2647 parenthesized: bool,
2648}
48663c56 2649
dfeec247
XL
2650impl<'hir> GenericArgsCtor<'hir> {
2651 fn is_empty(&self) -> bool {
2652 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2653 }
48663c56 2654
dfeec247
XL
2655 fn into_generic_args(self, arena: &'hir Arena<'hir>) -> hir::GenericArgs<'hir> {
2656 hir::GenericArgs {
2657 args: arena.alloc_from_iter(self.args),
2658 bindings: self.bindings,
2659 parenthesized: self.parenthesized,
48663c56 2660 }
48663c56 2661 }
48663c56 2662}