1 // ignore-tidy-filelength
3 //! Lowers the AST to the HIR.
5 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
6 //! much like a fold. Where lowering involves a bit more work things get more
7 //! interesting and there are some invariants you should know about. These mostly
8 //! concern spans and IDs.
10 //! Spans are assigned to AST nodes during parsing and then are modified during
11 //! expansion to indicate the origin of a node and the process it went through
12 //! being expanded. IDs are assigned to AST nodes just before lowering.
14 //! For the simpler lowering steps, IDs and spans should be preserved. Unlike
15 //! expansion we do not preserve the process of lowering in the spans, so spans
16 //! should not be modified here. When creating a new node (as opposed to
17 //! 'folding' an existing one), then you create a new ID using `next_id()`.
19 //! You must ensure that IDs are unique. That means that you should only use the
20 //! ID from an AST node in a single HIR node (you can assume that AST node-IDs
21 //! are unique). Every new node must have a unique ID. Avoid cloning HIR nodes.
22 //! If you do, you must then set the new node's ID to a fresh one.
24 //! Spans are used for error messages and for tools to map semantics back to
25 //! source code. It is therefore not as important with spans as IDs to be strict
26 //! about use (you can't break the compiler by screwing up a span). Obviously, a
27 //! HIR node can only have a single span. But multiple nodes can have the same
28 //! span and spans don't need to be kept in order, etc. Where code is preserved
29 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
30 //! new it is probably best to give a span for the whole AST node being lowered.
31 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
32 //! get confused if the spans from leaf AST nodes occur in multiple places
33 //! in the HIR, especially for multiple identifiers.
35 #![feature(array_value_iter)]
36 #![feature(crate_visibility_modifier)]
38 use rustc::arena::Arena;
39 use rustc::dep_graph::DepGraph;
40 use rustc::hir::map::definitions::{DefKey, DefPathData, Definitions};
41 use rustc::hir::map::Map;
43 use rustc::lint::builtin::{self, ELIDED_LIFETIMES_IN_PATHS};
44 use rustc::middle::cstore::CrateStore;
45 use rustc::util::captures::Captures;
46 use rustc::util::common::FN_OUTPUT_NAME;
47 use rustc::{bug, span_bug};
48 use rustc_data_structures::fx::FxHashSet;
49 use rustc_data_structures::sync::Lrc;
50 use rustc_error_codes::*;
51 use rustc_errors::{struct_span_err, Applicability};
53 use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res};
54 use rustc_hir::def_id::{DefId, DefIdMap, DefIndex, CRATE_DEF_INDEX};
55 use rustc_hir::intravisit;
56 use rustc_hir::{ConstArg, GenericArg, ParamName};
57 use rustc_index::vec::IndexVec;
58 use rustc_session::config::nightly_options;
59 use rustc_session::node_id::NodeMap;
60 use rustc_session::Session;
61 use rustc_span::hygiene::ExpnId;
62 use rustc_span::source_map::{respan, DesugaringKind, ExpnData, ExpnKind};
63 use rustc_span::symbol::{kw, sym, Symbol};
68 use syntax::print::pprust;
69 use syntax::sess::ParseSess;
70 use syntax::token::{self, Nonterminal, Token};
71 use syntax::tokenstream::{TokenStream, TokenTree};
72 use syntax::visit::{self, Visitor};
73 use syntax::walk_list;
75 use log::{debug, trace};
76 use smallvec::{smallvec, SmallVec};
77 use std::collections::BTreeMap;
80 macro_rules! arena_vec {
81 ($this:expr; $($x:expr),*) => ({
83 $this.arena.alloc_from_iter(std::array::IntoIter::new(a))
91 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
93 struct LoweringContext<'a, 'hir: 'a> {
94 crate_root: Option<Symbol>,
96 /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
99 resolver: &'a mut dyn Resolver,
101 /// HACK(Centril): there is a cyclic dependency between the parser and lowering
102 /// if we don't have this function pointer. To avoid that dependency so that
103 /// librustc is independent of the parser, we use dynamic dispatch here.
104 nt_to_tokenstream: NtToTokenstream,
106 /// Used to allocate HIR nodes
107 arena: &'hir Arena<'hir>,
109 /// The items being lowered are collected here.
110 items: BTreeMap<hir::HirId, hir::Item<'hir>>,
112 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem<'hir>>,
113 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem<'hir>>,
114 bodies: BTreeMap<hir::BodyId, hir::Body<'hir>>,
115 exported_macros: Vec<hir::MacroDef<'hir>>,
116 non_exported_macro_attrs: Vec<ast::Attribute>,
118 trait_impls: BTreeMap<DefId, Vec<hir::HirId>>,
120 modules: BTreeMap<hir::HirId, hir::ModuleItems>,
122 generator_kind: Option<hir::GeneratorKind>,
124 /// Used to get the current `fn`'s def span to point to when using `await`
125 /// outside of an `async fn`.
126 current_item: Option<Span>,
128 catch_scopes: Vec<NodeId>,
129 loop_scopes: Vec<NodeId>,
130 is_in_loop_condition: bool,
131 is_in_trait_impl: bool,
132 is_in_dyn_type: bool,
134 /// What to do when we encounter either an "anonymous lifetime
135 /// reference". The term "anonymous" is meant to encompass both
136 /// `'_` lifetimes as well as fully elided cases where nothing is
137 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
138 anonymous_lifetime_mode: AnonymousLifetimeMode,
140 /// Used to create lifetime definitions from in-band lifetime usages.
141 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
142 /// When a named lifetime is encountered in a function or impl header and
143 /// has not been defined
144 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
145 /// to this list. The results of this list are then added to the list of
146 /// lifetime definitions in the corresponding impl or function generics.
147 lifetimes_to_define: Vec<(Span, ParamName)>,
149 /// `true` if in-band lifetimes are being collected. This is used to
150 /// indicate whether or not we're in a place where new lifetimes will result
151 /// in in-band lifetime definitions, such a function or an impl header,
152 /// including implicit lifetimes from `impl_header_lifetime_elision`.
153 is_collecting_in_band_lifetimes: bool,
155 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
156 /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
157 /// against this list to see if it is already in-scope, or if a definition
158 /// needs to be created for it.
160 /// We always store a `modern()` version of the param-name in this
162 in_scope_lifetimes: Vec<ParamName>,
164 current_module: hir::HirId,
166 type_def_lifetime_params: DefIdMap<usize>,
168 current_hir_id_owner: Vec<(DefIndex, u32)>,
169 item_local_id_counters: NodeMap<u32>,
170 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
172 allow_try_trait: Option<Lrc<[Symbol]>>,
173 allow_gen_future: Option<Lrc<[Symbol]>>,
177 fn cstore(&self) -> &dyn CrateStore;
179 /// Obtains resolution for a `NodeId` with a single resolution.
180 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
182 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
183 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
185 /// Obtains resolution for a label with the given `NodeId`.
186 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
188 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
189 /// This should only return `None` during testing.
190 fn definitions(&mut self) -> &mut Definitions;
192 /// Given suffix `["b", "c", "d"]`, creates an AST path for `[::crate_root]::b::c::d` and
193 /// resolves it based on `is_value`.
197 crate_root: Option<Symbol>,
198 components: &[Symbol],
200 ) -> (ast::Path, Res<NodeId>);
202 fn lint_buffer(&mut self) -> &mut lint::LintBuffer;
204 fn next_node_id(&mut self) -> NodeId;
207 type NtToTokenstream = fn(&Nonterminal, &ParseSess, Span) -> TokenStream;
209 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
210 /// and if so, what meaning it has.
212 enum ImplTraitContext<'b, 'a> {
213 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
214 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
215 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
217 /// Newly generated parameters should be inserted into the given `Vec`.
218 Universal(&'b mut Vec<hir::GenericParam<'a>>),
220 /// Treat `impl Trait` as shorthand for a new opaque type.
221 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
222 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
224 /// We optionally store a `DefId` for the parent item here so we can look up necessary
225 /// information later. It is `None` when no information about the context should be stored
226 /// (e.g., for consts and statics).
227 OpaqueTy(Option<DefId> /* fn def-ID */),
229 /// `impl Trait` is not accepted in this position.
230 Disallowed(ImplTraitPosition),
233 /// Position in which `impl Trait` is disallowed.
234 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
235 enum ImplTraitPosition {
236 /// Disallowed in `let` / `const` / `static` bindings.
239 /// All other posiitons.
243 impl<'a> ImplTraitContext<'_, 'a> {
245 fn disallowed() -> Self {
246 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
249 fn reborrow<'this>(&'this mut self) -> ImplTraitContext<'this, 'a> {
250 use self::ImplTraitContext::*;
252 Universal(params) => Universal(params),
253 OpaqueTy(fn_def_id) => OpaqueTy(*fn_def_id),
254 Disallowed(pos) => Disallowed(*pos),
259 pub fn lower_crate<'a, 'hir>(
261 dep_graph: &'a DepGraph,
263 resolver: &'a mut dyn Resolver,
264 nt_to_tokenstream: NtToTokenstream,
265 arena: &'hir Arena<'hir>,
266 ) -> hir::Crate<'hir> {
267 // We're constructing the HIR here; we don't care what we will
268 // read, since we haven't even constructed the *input* to
270 dep_graph.assert_ignored();
272 let _prof_timer = sess.prof.generic_activity("hir_lowering");
275 crate_root: sess.parse_sess.injected_crate_name.try_get().copied(),
280 items: BTreeMap::new(),
281 trait_items: BTreeMap::new(),
282 impl_items: BTreeMap::new(),
283 bodies: BTreeMap::new(),
284 trait_impls: BTreeMap::new(),
285 modules: BTreeMap::new(),
286 exported_macros: Vec::new(),
287 non_exported_macro_attrs: Vec::new(),
288 catch_scopes: Vec::new(),
289 loop_scopes: Vec::new(),
290 is_in_loop_condition: false,
291 is_in_trait_impl: false,
292 is_in_dyn_type: false,
293 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
294 type_def_lifetime_params: Default::default(),
295 current_module: hir::CRATE_HIR_ID,
296 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
297 item_local_id_counters: Default::default(),
298 node_id_to_hir_id: IndexVec::new(),
299 generator_kind: None,
301 lifetimes_to_define: Vec::new(),
302 is_collecting_in_band_lifetimes: false,
303 in_scope_lifetimes: Vec::new(),
304 allow_try_trait: Some([sym::try_trait][..].into()),
305 allow_gen_future: Some([sym::gen_future][..].into()),
310 #[derive(Copy, Clone, PartialEq)]
312 /// Any path in a type context.
314 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
316 /// The `module::Type` in `module::Type::method` in an expression.
320 enum ParenthesizedGenericArgs {
325 /// What to do when we encounter an **anonymous** lifetime
326 /// reference. Anonymous lifetime references come in two flavors. You
327 /// have implicit, or fully elided, references to lifetimes, like the
328 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
329 /// or `Ref<'_, T>`. These often behave the same, but not always:
331 /// - certain usages of implicit references are deprecated, like
332 /// `Ref<T>`, and we sometimes just give hard errors in those cases
334 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
335 /// the same as `Box<dyn Foo + '_>`.
337 /// We describe the effects of the various modes in terms of three cases:
339 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
340 /// of a `&` (e.g., the missing lifetime in something like `&T`)
341 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
342 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
343 /// elided bounds follow special rules. Note that this only covers
344 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
345 /// '_>` is a case of "modern" elision.
346 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
347 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
348 /// non-deprecated equivalent.
350 /// Currently, the handling of lifetime elision is somewhat spread out
351 /// between HIR lowering and -- as described below -- the
352 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
353 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
354 /// everything into HIR lowering.
355 #[derive(Copy, Clone, Debug)]
356 enum AnonymousLifetimeMode {
357 /// For **Modern** cases, create a new anonymous region parameter
358 /// and reference that.
360 /// For **Dyn Bound** cases, pass responsibility to
361 /// `resolve_lifetime` code.
363 /// For **Deprecated** cases, report an error.
366 /// Give a hard error when either `&` or `'_` is written. Used to
367 /// rule out things like `where T: Foo<'_>`. Does not imply an
368 /// error on default object bounds (e.g., `Box<dyn Foo>`).
371 /// Pass responsibility to `resolve_lifetime` code for all cases.
375 struct ImplTraitTypeIdVisitor<'a> {
376 ids: &'a mut SmallVec<[NodeId; 1]>,
379 impl Visitor<'_> for ImplTraitTypeIdVisitor<'_> {
380 fn visit_ty(&mut self, ty: &Ty) {
382 TyKind::Typeof(_) | TyKind::BareFn(_) => return,
384 TyKind::ImplTrait(id, _) => self.ids.push(id),
387 visit::walk_ty(self, ty);
390 fn visit_path_segment(&mut self, path_span: Span, path_segment: &PathSegment) {
391 if let Some(ref p) = path_segment.args {
392 if let GenericArgs::Parenthesized(_) = **p {
396 visit::walk_path_segment(self, path_span, path_segment)
400 impl<'a, 'hir> LoweringContext<'a, 'hir> {
401 fn lower_crate(mut self, c: &Crate) -> hir::Crate<'hir> {
402 /// Full-crate AST visitor that inserts into a fresh
403 /// `LoweringContext` any information that may be
404 /// needed from arbitrary locations in the crate,
405 /// e.g., the number of lifetime generic parameters
406 /// declared for every type and trait definition.
407 struct MiscCollector<'tcx, 'lowering, 'hir> {
408 lctx: &'tcx mut LoweringContext<'lowering, 'hir>,
409 hir_id_owner: Option<NodeId>,
412 impl MiscCollector<'_, '_, '_> {
413 fn allocate_use_tree_hir_id_counters(&mut self, tree: &UseTree, owner: DefIndex) {
415 UseTreeKind::Simple(_, id1, id2) => {
416 for &id in &[id1, id2] {
417 self.lctx.resolver.definitions().create_def_with_parent(
424 self.lctx.allocate_hir_id_counter(id);
427 UseTreeKind::Glob => (),
428 UseTreeKind::Nested(ref trees) => {
429 for &(ref use_tree, id) in trees {
430 let hir_id = self.lctx.allocate_hir_id_counter(id);
431 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
437 fn with_hir_id_owner<T>(
439 owner: Option<NodeId>,
440 f: impl FnOnce(&mut Self) -> T,
442 let old = mem::replace(&mut self.hir_id_owner, owner);
444 self.hir_id_owner = old;
449 impl<'tcx> Visitor<'tcx> for MiscCollector<'tcx, '_, '_> {
450 fn visit_pat(&mut self, p: &'tcx Pat) {
451 if let PatKind::Paren(..) | PatKind::Rest = p.kind {
452 // Doesn't generate a HIR node
453 } else if let Some(owner) = self.hir_id_owner {
454 self.lctx.lower_node_id_with_owner(p.id, owner);
457 visit::walk_pat(self, p)
460 fn visit_item(&mut self, item: &'tcx Item) {
461 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
464 ItemKind::Struct(_, ref generics)
465 | ItemKind::Union(_, ref generics)
466 | ItemKind::Enum(_, ref generics)
467 | ItemKind::TyAlias(_, ref generics)
468 | ItemKind::Trait(_, _, ref generics, ..) => {
469 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
473 .filter(|param| match param.kind {
474 ast::GenericParamKind::Lifetime { .. } => true,
478 self.lctx.type_def_lifetime_params.insert(def_id, count);
480 ItemKind::Use(ref use_tree) => {
481 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
486 self.with_hir_id_owner(Some(item.id), |this| {
487 visit::walk_item(this, item);
491 fn visit_trait_item(&mut self, item: &'tcx AssocItem) {
492 self.lctx.allocate_hir_id_counter(item.id);
495 AssocItemKind::Fn(_, None) => {
496 // Ignore patterns in trait methods without bodies
497 self.with_hir_id_owner(None, |this| visit::walk_trait_item(this, item));
499 _ => self.with_hir_id_owner(Some(item.id), |this| {
500 visit::walk_trait_item(this, item);
505 fn visit_impl_item(&mut self, item: &'tcx AssocItem) {
506 self.lctx.allocate_hir_id_counter(item.id);
507 self.with_hir_id_owner(Some(item.id), |this| {
508 visit::walk_impl_item(this, item);
512 fn visit_foreign_item(&mut self, i: &'tcx ForeignItem) {
513 // Ignore patterns in foreign items
514 self.with_hir_id_owner(None, |this| visit::walk_foreign_item(this, i));
517 fn visit_ty(&mut self, t: &'tcx Ty) {
519 // Mirrors the case in visit::walk_ty
520 TyKind::BareFn(ref f) => {
521 walk_list!(self, visit_generic_param, &f.generic_params);
522 // Mirrors visit::walk_fn_decl
523 for parameter in &f.decl.inputs {
524 // We don't lower the ids of argument patterns
525 self.with_hir_id_owner(None, |this| {
526 this.visit_pat(¶meter.pat);
528 self.visit_ty(¶meter.ty)
530 self.visit_fn_ret_ty(&f.decl.output)
532 _ => visit::walk_ty(self, t),
537 self.lower_node_id(CRATE_NODE_ID);
538 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
540 visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
541 visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
543 let module = self.lower_mod(&c.module);
544 let attrs = self.lower_attrs(&c.attrs);
545 let body_ids = body_ids(&self.bodies);
547 self.resolver.definitions().init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
553 exported_macros: self.arena.alloc_from_iter(self.exported_macros),
554 non_exported_macro_attrs: self.arena.alloc_from_iter(self.non_exported_macro_attrs),
556 trait_items: self.trait_items,
557 impl_items: self.impl_items,
560 trait_impls: self.trait_impls,
561 modules: self.modules,
565 fn insert_item(&mut self, item: hir::Item<'hir>) {
566 let id = item.hir_id;
567 // FIXME: Use `debug_asset-rt`.
568 assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
569 self.items.insert(id, item);
570 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
573 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
574 // Set up the counter if needed.
575 self.item_local_id_counters.entry(owner).or_insert(0);
576 // Always allocate the first `HirId` for the owner itself.
577 let lowered = self.lower_node_id_with_owner(owner, owner);
578 debug_assert_eq!(lowered.local_id.as_u32(), 0);
582 fn lower_node_id_generic(
585 alloc_hir_id: impl FnOnce(&mut Self) -> hir::HirId,
587 if ast_node_id == DUMMY_NODE_ID {
588 return hir::DUMMY_HIR_ID;
591 let min_size = ast_node_id.as_usize() + 1;
593 if min_size > self.node_id_to_hir_id.len() {
594 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
597 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
599 if existing_hir_id == hir::DUMMY_HIR_ID {
600 // Generate a new `HirId`.
601 let hir_id = alloc_hir_id(self);
602 self.node_id_to_hir_id[ast_node_id] = hir_id;
610 fn with_hir_id_owner<T>(&mut self, owner: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
612 .item_local_id_counters
613 .insert(owner, HIR_ID_COUNTER_LOCKED)
614 .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
615 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
616 self.current_hir_id_owner.push((def_index, counter));
618 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
620 debug_assert!(def_index == new_def_index);
621 debug_assert!(new_counter >= counter);
623 let prev = self.item_local_id_counters.insert(owner, new_counter).unwrap();
624 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
628 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
629 /// the `LoweringContext`'s `NodeId => HirId` map.
630 /// Take care not to call this method if the resulting `HirId` is then not
631 /// actually used in the HIR, as that would trigger an assertion in the
632 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
633 /// properly. Calling the method twice with the same `NodeId` is fine though.
634 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
635 self.lower_node_id_generic(ast_node_id, |this| {
636 let &mut (def_index, ref mut local_id_counter) =
637 this.current_hir_id_owner.last_mut().unwrap();
638 let local_id = *local_id_counter;
639 *local_id_counter += 1;
640 hir::HirId { owner: def_index, local_id: hir::ItemLocalId::from_u32(local_id) }
644 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
645 self.lower_node_id_generic(ast_node_id, |this| {
646 let local_id_counter = this
647 .item_local_id_counters
649 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
650 let local_id = *local_id_counter;
652 // We want to be sure not to modify the counter in the map while it
653 // is also on the stack. Otherwise we'll get lost updates when writing
654 // back from the stack to the map.
655 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
657 *local_id_counter += 1;
658 let def_index = this.resolver.definitions().opt_def_index(owner).expect(
659 "you forgot to call `create_def_with_parent` or are lowering node-IDs \
660 that do not belong to the current owner",
663 hir::HirId { owner: def_index, local_id: hir::ItemLocalId::from_u32(local_id) }
667 fn next_id(&mut self) -> hir::HirId {
668 let node_id = self.resolver.next_node_id();
669 self.lower_node_id(node_id)
672 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
674 self.lower_node_id_generic(id, |_| {
675 panic!("expected `NodeId` to be lowered already for res {:#?}", res);
680 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
681 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
682 if pr.unresolved_segments() != 0 {
683 bug!("path not fully resolved: {:?}", pr);
689 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
690 self.resolver.get_import_res(id).present_items()
693 fn diagnostic(&self) -> &rustc_errors::Handler {
694 self.sess.diagnostic()
697 /// Reuses the span but adds information like the kind of the desugaring and features that are
698 /// allowed inside this span.
699 fn mark_span_with_reason(
701 reason: DesugaringKind,
703 allow_internal_unstable: Option<Lrc<[Symbol]>>,
705 span.fresh_expansion(ExpnData {
706 allow_internal_unstable,
707 ..ExpnData::default(ExpnKind::Desugaring(reason), span, self.sess.edition())
711 fn with_anonymous_lifetime_mode<R>(
713 anonymous_lifetime_mode: AnonymousLifetimeMode,
714 op: impl FnOnce(&mut Self) -> R,
717 "with_anonymous_lifetime_mode(anonymous_lifetime_mode={:?})",
718 anonymous_lifetime_mode,
720 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
721 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
722 let result = op(self);
723 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
725 "with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}",
726 old_anonymous_lifetime_mode
731 /// Creates a new `hir::GenericParam` for every new lifetime and
732 /// type parameter encountered while evaluating `f`. Definitions
733 /// are created with the parent provided. If no `parent_id` is
734 /// provided, no definitions will be returned.
736 /// Presuming that in-band lifetimes are enabled, then
737 /// `self.anonymous_lifetime_mode` will be updated to match the
738 /// parameter while `f` is running (and restored afterwards).
739 fn collect_in_band_defs<T>(
742 anonymous_lifetime_mode: AnonymousLifetimeMode,
743 f: impl FnOnce(&mut Self) -> (Vec<hir::GenericParam<'hir>>, T),
744 ) -> (Vec<hir::GenericParam<'hir>>, T) {
745 assert!(!self.is_collecting_in_band_lifetimes);
746 assert!(self.lifetimes_to_define.is_empty());
747 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
749 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
750 self.is_collecting_in_band_lifetimes = true;
752 let (in_band_ty_params, res) = f(self);
754 self.is_collecting_in_band_lifetimes = false;
755 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
757 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
759 let params = lifetimes_to_define
761 .map(|(span, hir_name)| self.lifetime_to_generic_param(span, hir_name, parent_id.index))
762 .chain(in_band_ty_params.into_iter())
768 /// Converts a lifetime into a new generic parameter.
769 fn lifetime_to_generic_param(
773 parent_index: DefIndex,
774 ) -> hir::GenericParam<'hir> {
775 let node_id = self.resolver.next_node_id();
777 // Get the name we'll use to make the def-path. Note
778 // that collisions are ok here and this shouldn't
779 // really show up for end-user.
780 let (str_name, kind) = match hir_name {
781 ParamName::Plain(ident) => (ident.name, hir::LifetimeParamKind::InBand),
782 ParamName::Fresh(_) => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Elided),
783 ParamName::Error => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Error),
786 // Add a definition for the in-band lifetime def.
787 self.resolver.definitions().create_def_with_parent(
790 DefPathData::LifetimeNs(str_name),
796 hir_id: self.lower_node_id(node_id),
801 pure_wrt_drop: false,
802 kind: hir::GenericParamKind::Lifetime { kind },
806 /// When there is a reference to some lifetime `'a`, and in-band
807 /// lifetimes are enabled, then we want to push that lifetime into
808 /// the vector of names to define later. In that case, it will get
809 /// added to the appropriate generics.
810 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
811 if !self.is_collecting_in_band_lifetimes {
815 if !self.sess.features_untracked().in_band_lifetimes {
819 if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.modern())) {
823 let hir_name = ParamName::Plain(ident);
825 if self.lifetimes_to_define.iter().any(|(_, lt_name)| lt_name.modern() == hir_name.modern())
830 self.lifetimes_to_define.push((ident.span, hir_name));
833 /// When we have either an elided or `'_` lifetime in an impl
834 /// header, we convert it to an in-band lifetime.
835 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
836 assert!(self.is_collecting_in_band_lifetimes);
837 let index = self.lifetimes_to_define.len() + self.in_scope_lifetimes.len();
838 let hir_name = ParamName::Fresh(index);
839 self.lifetimes_to_define.push((span, hir_name));
843 // Evaluates `f` with the lifetimes in `params` in-scope.
844 // This is used to track which lifetimes have already been defined, and
845 // which are new in-band lifetimes that need to have a definition created
847 fn with_in_scope_lifetime_defs<T>(
849 params: &[GenericParam],
850 f: impl FnOnce(&mut Self) -> T,
852 let old_len = self.in_scope_lifetimes.len();
853 let lt_def_names = params.iter().filter_map(|param| match param.kind {
854 GenericParamKind::Lifetime { .. } => Some(ParamName::Plain(param.ident.modern())),
857 self.in_scope_lifetimes.extend(lt_def_names);
861 self.in_scope_lifetimes.truncate(old_len);
865 /// Appends in-band lifetime defs and argument-position `impl
866 /// Trait` defs to the existing set of generics.
868 /// Presuming that in-band lifetimes are enabled, then
869 /// `self.anonymous_lifetime_mode` will be updated to match the
870 /// parameter while `f` is running (and restored afterwards).
871 fn add_in_band_defs<T>(
875 anonymous_lifetime_mode: AnonymousLifetimeMode,
876 f: impl FnOnce(&mut Self, &mut Vec<hir::GenericParam<'hir>>) -> T,
877 ) -> (hir::Generics<'hir>, T) {
878 let (in_band_defs, (mut lowered_generics, res)) =
879 self.with_in_scope_lifetime_defs(&generics.params, |this| {
880 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
881 let mut params = Vec::new();
882 // Note: it is necessary to lower generics *before* calling `f`.
883 // When lowering `async fn`, there's a final step when lowering
884 // the return type that assumes that all in-scope lifetimes have
885 // already been added to either `in_scope_lifetimes` or
886 // `lifetimes_to_define`. If we swapped the order of these two,
887 // in-band-lifetimes introduced by generics or where-clauses
888 // wouldn't have been added yet.
890 this.lower_generics_mut(generics, ImplTraitContext::Universal(&mut params));
891 let res = f(this, &mut params);
892 (params, (generics, res))
896 let mut lowered_params: Vec<_> =
897 lowered_generics.params.into_iter().chain(in_band_defs).collect();
899 // FIXME(const_generics): the compiler doesn't always cope with
900 // unsorted generic parameters at the moment, so we make sure
901 // that they're ordered correctly here for now. (When we chain
902 // the `in_band_defs`, we might make the order unsorted.)
903 lowered_params.sort_by_key(|param| match param.kind {
904 hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime,
905 hir::GenericParamKind::Type { .. } => ParamKindOrd::Type,
906 hir::GenericParamKind::Const { .. } => ParamKindOrd::Const,
909 lowered_generics.params = lowered_params.into();
911 let lowered_generics = lowered_generics.into_generics(self.arena);
912 (lowered_generics, res)
915 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
916 let was_in_dyn_type = self.is_in_dyn_type;
917 self.is_in_dyn_type = in_scope;
919 let result = f(self);
921 self.is_in_dyn_type = was_in_dyn_type;
926 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
927 let was_in_loop_condition = self.is_in_loop_condition;
928 self.is_in_loop_condition = false;
930 let catch_scopes = mem::take(&mut self.catch_scopes);
931 let loop_scopes = mem::take(&mut self.loop_scopes);
933 self.catch_scopes = catch_scopes;
934 self.loop_scopes = loop_scopes;
936 self.is_in_loop_condition = was_in_loop_condition;
941 fn def_key(&mut self, id: DefId) -> DefKey {
943 self.resolver.definitions().def_key(id.index)
945 self.resolver.cstore().def_key(id)
949 fn lower_attrs(&mut self, attrs: &[Attribute]) -> &'hir [Attribute] {
950 self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)))
953 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
954 // Note that we explicitly do not walk the path. Since we don't really
955 // lower attributes (we use the AST version) there is nowhere to keep
956 // the `HirId`s. We don't actually need HIR version of attributes anyway.
957 let kind = match attr.kind {
958 AttrKind::Normal(ref item) => AttrKind::Normal(AttrItem {
959 path: item.path.clone(),
960 args: self.lower_mac_args(&item.args),
962 AttrKind::DocComment(comment) => AttrKind::DocComment(comment),
965 Attribute { kind, id: attr.id, style: attr.style, span: attr.span }
968 fn lower_mac_args(&mut self, args: &MacArgs) -> MacArgs {
970 MacArgs::Empty => MacArgs::Empty,
971 MacArgs::Delimited(dspan, delim, ref tokens) => {
972 MacArgs::Delimited(dspan, delim, self.lower_token_stream(tokens.clone()))
974 MacArgs::Eq(eq_span, ref tokens) => {
975 MacArgs::Eq(eq_span, self.lower_token_stream(tokens.clone()))
980 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
981 tokens.into_trees().flat_map(|tree| self.lower_token_tree(tree).into_trees()).collect()
984 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
986 TokenTree::Token(token) => self.lower_token(token),
987 TokenTree::Delimited(span, delim, tts) => {
988 TokenTree::Delimited(span, delim, self.lower_token_stream(tts)).into()
993 fn lower_token(&mut self, token: Token) -> TokenStream {
995 token::Interpolated(nt) => {
996 let tts = (self.nt_to_tokenstream)(&nt, &self.sess.parse_sess, token.span);
997 self.lower_token_stream(tts)
999 _ => TokenTree::Token(token).into(),
1003 /// Given an associated type constraint like one of these:
1006 /// T: Iterator<Item: Debug>
1008 /// T: Iterator<Item = Debug>
1012 /// returns a `hir::TypeBinding` representing `Item`.
1013 fn lower_assoc_ty_constraint(
1015 constraint: &AssocTyConstraint,
1016 itctx: ImplTraitContext<'_, 'hir>,
1017 ) -> hir::TypeBinding<'hir> {
1018 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
1020 let kind = match constraint.kind {
1021 AssocTyConstraintKind::Equality { ref ty } => {
1022 hir::TypeBindingKind::Equality { ty: self.lower_ty(ty, itctx) }
1024 AssocTyConstraintKind::Bound { ref bounds } => {
1025 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1026 let (desugar_to_impl_trait, itctx) = match itctx {
1027 // We are in the return position:
1029 // fn foo() -> impl Iterator<Item: Debug>
1033 // fn foo() -> impl Iterator<Item = impl Debug>
1034 ImplTraitContext::OpaqueTy(_) => (true, itctx),
1036 // We are in the argument position, but within a dyn type:
1038 // fn foo(x: dyn Iterator<Item: Debug>)
1042 // fn foo(x: dyn Iterator<Item = impl Debug>)
1043 ImplTraitContext::Universal(_) if self.is_in_dyn_type => (true, itctx),
1045 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1046 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1047 // "impl trait context" to permit `impl Debug` in this position (it desugars
1048 // then to an opaque type).
1050 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1051 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => {
1052 (true, ImplTraitContext::OpaqueTy(None))
1055 // We are in the parameter position, but not within a dyn type:
1057 // fn foo(x: impl Iterator<Item: Debug>)
1059 // so we leave it as is and this gets expanded in astconv to a bound like
1060 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1062 _ => (false, itctx),
1065 if desugar_to_impl_trait {
1066 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1067 // constructing the HIR for `impl bounds...` and then lowering that.
1069 let impl_trait_node_id = self.resolver.next_node_id();
1070 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
1071 self.resolver.definitions().create_def_with_parent(
1074 DefPathData::ImplTrait,
1079 self.with_dyn_type_scope(false, |this| {
1080 let node_id = this.resolver.next_node_id();
1081 let ty = this.lower_ty(
1084 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1085 span: constraint.span,
1090 hir::TypeBindingKind::Equality { ty }
1093 // Desugar `AssocTy: Bounds` into a type binding where the
1094 // later desugars into a trait predicate.
1095 let bounds = self.lower_param_bounds(bounds, itctx);
1097 hir::TypeBindingKind::Constraint { bounds }
1103 hir_id: self.lower_node_id(constraint.id),
1104 ident: constraint.ident,
1106 span: constraint.span,
1110 fn lower_generic_arg(
1112 arg: &ast::GenericArg,
1113 itctx: ImplTraitContext<'_, 'hir>,
1114 ) -> hir::GenericArg<'hir> {
1116 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1117 ast::GenericArg::Type(ty) => {
1118 // We parse const arguments as path types as we cannot distiguish them durring
1119 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1120 // type and value namespaces. If we resolved the path in the value namespace, we
1121 // transform it into a generic const argument.
1122 if let TyKind::Path(ref qself, ref path) = ty.kind {
1123 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1124 let res = partial_res.base_res();
1125 if !res.matches_ns(Namespace::TypeNS) {
1127 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1131 // Construct a AnonConst where the expr is the "ty"'s path.
1133 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
1134 let node_id = self.resolver.next_node_id();
1136 // Add a definition for the in-band const def.
1137 self.resolver.definitions().create_def_with_parent(
1140 DefPathData::AnonConst,
1145 let path_expr = Expr {
1147 kind: ExprKind::Path(qself.clone(), path.clone()),
1149 attrs: AttrVec::new(),
1152 let ct = self.with_new_scopes(|this| hir::AnonConst {
1153 hir_id: this.lower_node_id(node_id),
1154 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1156 return GenericArg::Const(ConstArg { value: ct, span: ty.span });
1160 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1162 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1163 value: self.lower_anon_const(&ct),
1164 span: ct.value.span,
1169 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_, 'hir>) -> &'hir hir::Ty<'hir> {
1170 self.arena.alloc(self.lower_ty_direct(t, itctx))
1176 qself: &Option<QSelf>,
1178 param_mode: ParamMode,
1179 itctx: ImplTraitContext<'_, 'hir>,
1180 ) -> hir::Ty<'hir> {
1181 let id = self.lower_node_id(t.id);
1182 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1183 let ty = self.ty_path(id, t.span, qpath);
1184 if let hir::TyKind::TraitObject(..) = ty.kind {
1185 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1190 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1191 hir::Ty { hir_id: self.next_id(), kind, span }
1194 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1195 self.ty(span, hir::TyKind::Tup(tys))
1198 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_, 'hir>) -> hir::Ty<'hir> {
1199 let kind = match t.kind {
1200 TyKind::Infer => hir::TyKind::Infer,
1201 TyKind::Err => hir::TyKind::Err,
1202 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1203 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1204 TyKind::Rptr(ref region, ref mt) => {
1205 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1206 let lifetime = match *region {
1207 Some(ref lt) => self.lower_lifetime(lt),
1208 None => self.elided_ref_lifetime(span),
1210 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1212 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(&f.generic_params, |this| {
1213 this.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
1214 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1215 generic_params: this.lower_generic_params(
1217 &NodeMap::default(),
1218 ImplTraitContext::disallowed(),
1220 unsafety: f.unsafety,
1221 abi: this.lower_extern(f.ext),
1222 decl: this.lower_fn_decl(&f.decl, None, false, None),
1223 param_names: this.lower_fn_params_to_names(&f.decl),
1227 TyKind::Never => hir::TyKind::Never,
1228 TyKind::Tup(ref tys) => {
1229 hir::TyKind::Tup(self.arena.alloc_from_iter(
1230 tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())),
1233 TyKind::Paren(ref ty) => {
1234 return self.lower_ty_direct(ty, itctx);
1236 TyKind::Path(ref qself, ref path) => {
1237 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1239 TyKind::ImplicitSelf => {
1240 let res = self.expect_full_res(t.id);
1241 let res = self.lower_res(res);
1242 hir::TyKind::Path(hir::QPath::Resolved(
1244 self.arena.alloc(hir::Path {
1246 segments: arena_vec![self; hir::PathSegment::from_ident(
1247 Ident::with_dummy_span(kw::SelfUpper)
1253 TyKind::Array(ref ty, ref length) => {
1254 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1256 TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1257 TyKind::TraitObject(ref bounds, kind) => {
1258 let mut lifetime_bound = None;
1259 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1261 this.arena.alloc_from_iter(bounds.iter().filter_map(
1262 |bound| match *bound {
1263 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1264 Some(this.lower_poly_trait_ref(ty, itctx.reborrow()))
1266 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1267 GenericBound::Outlives(ref lifetime) => {
1268 if lifetime_bound.is_none() {
1269 lifetime_bound = Some(this.lower_lifetime(lifetime));
1275 let lifetime_bound =
1276 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1277 (bounds, lifetime_bound)
1279 if kind != TraitObjectSyntax::Dyn {
1280 self.maybe_lint_bare_trait(t.span, t.id, false);
1282 hir::TyKind::TraitObject(bounds, lifetime_bound)
1284 TyKind::ImplTrait(def_node_id, ref bounds) => {
1287 ImplTraitContext::OpaqueTy(fn_def_id) => {
1288 self.lower_opaque_impl_trait(span, fn_def_id, def_node_id, |this| {
1289 this.lower_param_bounds(bounds, itctx)
1292 ImplTraitContext::Universal(in_band_ty_params) => {
1293 // Add a definition for the in-band `Param`.
1295 self.resolver.definitions().opt_def_index(def_node_id).unwrap();
1297 let hir_bounds = self.lower_param_bounds(
1299 ImplTraitContext::Universal(in_band_ty_params),
1301 // Set the name to `impl Bound1 + Bound2`.
1302 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1303 in_band_ty_params.push(hir::GenericParam {
1304 hir_id: self.lower_node_id(def_node_id),
1305 name: ParamName::Plain(ident),
1306 pure_wrt_drop: false,
1310 kind: hir::GenericParamKind::Type {
1312 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1316 hir::TyKind::Path(hir::QPath::Resolved(
1318 self.arena.alloc(hir::Path {
1320 res: Res::Def(DefKind::TyParam, DefId::local(def_index)),
1321 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1325 ImplTraitContext::Disallowed(pos) => {
1326 let allowed_in = if self.sess.features_untracked().impl_trait_in_bindings {
1327 "bindings or function and inherent method return types"
1329 "function and inherent method return types"
1331 let mut err = struct_span_err!(
1335 "`impl Trait` not allowed outside of {}",
1338 if pos == ImplTraitPosition::Binding && nightly_options::is_nightly_build()
1341 "add `#![feature(impl_trait_in_bindings)]` to the crate \
1342 attributes to enable",
1350 TyKind::Mac(_) => bug!("`TyKind::Mac` should have been expanded by now"),
1351 TyKind::CVarArgs => {
1352 self.sess.delay_span_bug(
1354 "`TyKind::CVarArgs` should have been handled elsewhere",
1360 hir::Ty { kind, span: t.span, hir_id: self.lower_node_id(t.id) }
1363 fn lower_opaque_impl_trait(
1366 fn_def_id: Option<DefId>,
1367 opaque_ty_node_id: NodeId,
1368 lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1369 ) -> hir::TyKind<'hir> {
1371 "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
1372 fn_def_id, opaque_ty_node_id, span,
1375 // Make sure we know that some funky desugaring has been going on here.
1376 // This is a first: there is code in other places like for loop
1377 // desugaring that explicitly states that we don't want to track that.
1378 // Not tracking it makes lints in rustc and clippy very fragile, as
1379 // frequently opened issues show.
1380 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1382 let opaque_ty_def_index =
1383 self.resolver.definitions().opt_def_index(opaque_ty_node_id).unwrap();
1385 self.allocate_hir_id_counter(opaque_ty_node_id);
1387 let hir_bounds = self.with_hir_id_owner(opaque_ty_node_id, lower_bounds);
1389 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1391 opaque_ty_def_index,
1395 debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes,);
1397 debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs,);
1399 self.with_hir_id_owner(opaque_ty_node_id, move |lctx| {
1400 let opaque_ty_item = hir::OpaqueTy {
1401 generics: hir::Generics {
1402 params: lifetime_defs,
1403 where_clause: hir::WhereClause { predicates: &[], span },
1407 impl_trait_fn: fn_def_id,
1408 origin: hir::OpaqueTyOrigin::FnReturn,
1411 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_index);
1413 lctx.generate_opaque_type(opaque_ty_node_id, opaque_ty_item, span, opaque_ty_span);
1415 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1416 hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, lifetimes)
1420 /// Registers a new opaque type with the proper `NodeId`s and
1421 /// returns the lowered node-ID for the opaque type.
1422 fn generate_opaque_type(
1424 opaque_ty_node_id: NodeId,
1425 opaque_ty_item: hir::OpaqueTy<'hir>,
1427 opaque_ty_span: Span,
1429 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1430 let opaque_ty_id = self.lower_node_id(opaque_ty_node_id);
1431 // Generate an `type Foo = impl Trait;` declaration.
1432 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1433 let opaque_ty_item = hir::Item {
1434 hir_id: opaque_ty_id,
1435 ident: Ident::invalid(),
1436 attrs: Default::default(),
1437 kind: opaque_ty_item_kind,
1438 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1439 span: opaque_ty_span,
1442 // Insert the item into the global item list. This usually happens
1443 // automatically for all AST items. But this opaque type item
1444 // does not actually exist in the AST.
1445 self.insert_item(opaque_ty_item);
1449 fn lifetimes_from_impl_trait_bounds(
1451 opaque_ty_id: NodeId,
1452 parent_index: DefIndex,
1453 bounds: hir::GenericBounds<'hir>,
1454 ) -> (&'hir [hir::GenericArg<'hir>], &'hir [hir::GenericParam<'hir>]) {
1456 "lifetimes_from_impl_trait_bounds(opaque_ty_id={:?}, \
1457 parent_index={:?}, \
1459 opaque_ty_id, parent_index, bounds,
1462 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1463 // appear in the bounds, excluding lifetimes that are created within the bounds.
1464 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1465 struct ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1466 context: &'r mut LoweringContext<'a, 'hir>,
1468 opaque_ty_id: NodeId,
1469 collect_elided_lifetimes: bool,
1470 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1471 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1472 output_lifetimes: Vec<hir::GenericArg<'hir>>,
1473 output_lifetime_params: Vec<hir::GenericParam<'hir>>,
1476 impl<'r, 'a, 'v, 'hir> intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1479 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<'_, Self::Map> {
1480 intravisit::NestedVisitorMap::None
1483 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs<'v>) {
1484 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1485 if parameters.parenthesized {
1486 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1487 self.collect_elided_lifetimes = false;
1488 intravisit::walk_generic_args(self, span, parameters);
1489 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1491 intravisit::walk_generic_args(self, span, parameters);
1495 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
1496 // Don't collect elided lifetimes used inside of `fn()` syntax.
1497 if let hir::TyKind::BareFn(_) = t.kind {
1498 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1499 self.collect_elided_lifetimes = false;
1501 // Record the "stack height" of `for<'a>` lifetime bindings
1502 // to be able to later fully undo their introduction.
1503 let old_len = self.currently_bound_lifetimes.len();
1504 intravisit::walk_ty(self, t);
1505 self.currently_bound_lifetimes.truncate(old_len);
1507 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1509 intravisit::walk_ty(self, t)
1513 fn visit_poly_trait_ref(
1515 trait_ref: &'v hir::PolyTraitRef<'v>,
1516 modifier: hir::TraitBoundModifier,
1518 // Record the "stack height" of `for<'a>` lifetime bindings
1519 // to be able to later fully undo their introduction.
1520 let old_len = self.currently_bound_lifetimes.len();
1521 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1522 self.currently_bound_lifetimes.truncate(old_len);
1525 fn visit_generic_param(&mut self, param: &'v hir::GenericParam<'v>) {
1526 // Record the introduction of 'a in `for<'a> ...`.
1527 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1528 // Introduce lifetimes one at a time so that we can handle
1529 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1530 let lt_name = hir::LifetimeName::Param(param.name);
1531 self.currently_bound_lifetimes.push(lt_name);
1534 intravisit::walk_generic_param(self, param);
1537 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1538 let name = match lifetime.name {
1539 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1540 if self.collect_elided_lifetimes {
1541 // Use `'_` for both implicit and underscore lifetimes in
1542 // `type Foo<'_> = impl SomeTrait<'_>;`.
1543 hir::LifetimeName::Underscore
1548 hir::LifetimeName::Param(_) => lifetime.name,
1550 // Refers to some other lifetime that is "in
1551 // scope" within the type.
1552 hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
1554 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1557 if !self.currently_bound_lifetimes.contains(&name)
1558 && !self.already_defined_lifetimes.contains(&name)
1560 self.already_defined_lifetimes.insert(name);
1562 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1563 hir_id: self.context.next_id(),
1564 span: lifetime.span,
1568 let def_node_id = self.context.resolver.next_node_id();
1570 self.context.lower_node_id_with_owner(def_node_id, self.opaque_ty_id);
1571 self.context.resolver.definitions().create_def_with_parent(
1574 DefPathData::LifetimeNs(name.ident().name),
1579 let (name, kind) = match name {
1580 hir::LifetimeName::Underscore => (
1581 hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1582 hir::LifetimeParamKind::Elided,
1584 hir::LifetimeName::Param(param_name) => {
1585 (param_name, hir::LifetimeParamKind::Explicit)
1587 _ => bug!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1590 self.output_lifetime_params.push(hir::GenericParam {
1593 span: lifetime.span,
1594 pure_wrt_drop: false,
1597 kind: hir::GenericParamKind::Lifetime { kind },
1603 let mut lifetime_collector = ImplTraitLifetimeCollector {
1605 parent: parent_index,
1607 collect_elided_lifetimes: true,
1608 currently_bound_lifetimes: Vec::new(),
1609 already_defined_lifetimes: FxHashSet::default(),
1610 output_lifetimes: Vec::new(),
1611 output_lifetime_params: Vec::new(),
1614 for bound in bounds {
1615 intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1618 let ImplTraitLifetimeCollector { output_lifetimes, output_lifetime_params, .. } =
1622 self.arena.alloc_from_iter(output_lifetimes),
1623 self.arena.alloc_from_iter(output_lifetime_params),
1630 qself: &Option<QSelf>,
1632 param_mode: ParamMode,
1633 mut itctx: ImplTraitContext<'_, 'hir>,
1634 ) -> hir::QPath<'hir> {
1635 let qself_position = qself.as_ref().map(|q| q.position);
1636 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1639 self.resolver.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err));
1641 let proj_start = p.segments.len() - partial_res.unresolved_segments();
1642 let path = self.arena.alloc(hir::Path {
1643 res: self.lower_res(partial_res.base_res()),
1644 segments: self.arena.alloc_from_iter(p.segments[..proj_start].iter().enumerate().map(
1646 let param_mode = match (qself_position, param_mode) {
1647 (Some(j), ParamMode::Optional) if i < j => {
1648 // This segment is part of the trait path in a
1649 // qualified path - one of `a`, `b` or `Trait`
1650 // in `<X as a::b::Trait>::T::U::method`.
1656 // Figure out if this is a type/trait segment,
1657 // which may need lifetime elision performed.
1658 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1659 krate: def_id.krate,
1660 index: this.def_key(def_id).parent.expect("missing parent"),
1662 let type_def_id = match partial_res.base_res() {
1663 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
1664 Some(parent_def_id(self, def_id))
1666 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
1667 Some(parent_def_id(self, def_id))
1669 Res::Def(DefKind::Struct, def_id)
1670 | Res::Def(DefKind::Union, def_id)
1671 | Res::Def(DefKind::Enum, def_id)
1672 | Res::Def(DefKind::TyAlias, def_id)
1673 | Res::Def(DefKind::Trait, def_id)
1674 if i + 1 == proj_start =>
1680 let parenthesized_generic_args = match partial_res.base_res() {
1681 // `a::b::Trait(Args)`
1682 Res::Def(DefKind::Trait, _) if i + 1 == proj_start => {
1683 ParenthesizedGenericArgs::Ok
1685 // `a::b::Trait(Args)::TraitItem`
1686 Res::Def(DefKind::Method, _)
1687 | Res::Def(DefKind::AssocConst, _)
1688 | Res::Def(DefKind::AssocTy, _)
1689 if i + 2 == proj_start =>
1691 ParenthesizedGenericArgs::Ok
1693 // Avoid duplicated errors.
1694 Res::Err => ParenthesizedGenericArgs::Ok,
1696 _ => ParenthesizedGenericArgs::Err,
1699 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1700 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1703 assert!(!def_id.is_local());
1704 let item_generics = self
1707 .item_generics_cloned_untracked(def_id, self.sess);
1708 let n = item_generics.own_counts().lifetimes;
1709 self.type_def_lifetime_params.insert(def_id, n);
1712 self.lower_path_segment(
1717 parenthesized_generic_args,
1726 // Simple case, either no projections, or only fully-qualified.
1727 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
1728 if partial_res.unresolved_segments() == 0 {
1729 return hir::QPath::Resolved(qself, path);
1732 // Create the innermost type that we're projecting from.
1733 let mut ty = if path.segments.is_empty() {
1734 // If the base path is empty that means there exists a
1735 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
1736 qself.expect("missing QSelf for <T>::...")
1738 // Otherwise, the base path is an implicit `Self` type path,
1739 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1740 // `<I as Iterator>::Item::default`.
1741 let new_id = self.next_id();
1742 self.arena.alloc(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1745 // Anything after the base path are associated "extensions",
1746 // out of which all but the last one are associated types,
1747 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1748 // * base path is `std::vec::Vec<T>`
1749 // * "extensions" are `IntoIter`, `Item` and `clone`
1750 // * type nodes are:
1751 // 1. `std::vec::Vec<T>` (created above)
1752 // 2. `<std::vec::Vec<T>>::IntoIter`
1753 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1754 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1755 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1756 let segment = self.arena.alloc(self.lower_path_segment(
1761 ParenthesizedGenericArgs::Err,
1765 let qpath = hir::QPath::TypeRelative(ty, segment);
1767 // It's finished, return the extension of the right node type.
1768 if i == p.segments.len() - 1 {
1772 // Wrap the associated extension in another type node.
1773 let new_id = self.next_id();
1774 ty = self.arena.alloc(self.ty_path(new_id, p.span, qpath));
1777 // We should've returned in the for loop above.
1780 "lower_qpath: no final extension segment in {}..{}",
1786 fn lower_path_extra(
1790 param_mode: ParamMode,
1791 explicit_owner: Option<NodeId>,
1792 ) -> &'hir hir::Path<'hir> {
1793 self.arena.alloc(hir::Path {
1795 segments: self.arena.alloc_from_iter(p.segments.iter().map(|segment| {
1796 self.lower_path_segment(
1801 ParenthesizedGenericArgs::Err,
1802 ImplTraitContext::disallowed(),
1810 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> &'hir hir::Path<'hir> {
1811 let res = self.expect_full_res(id);
1812 let res = self.lower_res(res);
1813 self.lower_path_extra(res, p, param_mode, None)
1816 fn lower_path_segment(
1819 segment: &PathSegment,
1820 param_mode: ParamMode,
1821 expected_lifetimes: usize,
1822 parenthesized_generic_args: ParenthesizedGenericArgs,
1823 itctx: ImplTraitContext<'_, 'hir>,
1824 explicit_owner: Option<NodeId>,
1825 ) -> hir::PathSegment<'hir> {
1826 let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
1827 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
1828 match **generic_args {
1829 GenericArgs::AngleBracketed(ref data) => {
1830 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1832 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1833 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1834 ParenthesizedGenericArgs::Err => {
1835 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
1836 err.span_label(data.span, "only `Fn` traits may use parentheses");
1837 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
1838 // Do not suggest going from `Trait()` to `Trait<>`
1839 if data.inputs.len() > 0 {
1840 if let Some(split) = snippet.find('(') {
1841 let trait_name = &snippet[0..split];
1842 let args = &snippet[split + 1..snippet.len() - 1];
1843 err.span_suggestion(
1845 "use angle brackets instead",
1846 format!("{}<{}>", trait_name, args),
1847 Applicability::MaybeIncorrect,
1854 self.lower_angle_bracketed_parameter_data(
1855 &data.as_angle_bracketed_args(),
1866 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1869 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1870 GenericArg::Lifetime(_) => true,
1873 let first_generic_span = generic_args
1877 .chain(generic_args.bindings.iter().map(|b| b.span))
1879 if !generic_args.parenthesized && !has_lifetimes {
1880 generic_args.args = self
1881 .elided_path_lifetimes(path_span, expected_lifetimes)
1882 .map(|lt| GenericArg::Lifetime(lt))
1883 .chain(generic_args.args.into_iter())
1885 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1886 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1887 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
1888 let no_bindings = generic_args.bindings.is_empty();
1889 let (incl_angl_brckt, insertion_sp, suggestion) = if no_non_lt_args && no_bindings {
1890 // If there are no (non-implicit) generic args or associated type
1891 // bindings, our suggestion includes the angle brackets.
1892 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1894 // Otherwise (sorry, this is kind of gross) we need to infer the
1895 // place to splice in the `'_, ` from the generics that do exist.
1896 let first_generic_span = first_generic_span
1897 .expect("already checked that non-lifetime args or bindings exist");
1898 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1900 match self.anonymous_lifetime_mode {
1901 // In create-parameter mode we error here because we don't want to support
1902 // deprecated impl elision in new features like impl elision and `async fn`,
1903 // both of which work using the `CreateParameter` mode:
1905 // impl Foo for std::cell::Ref<u32> // note lack of '_
1906 // async fn foo(_: std::cell::Ref<u32>) { ... }
1907 AnonymousLifetimeMode::CreateParameter => {
1908 let mut err = struct_span_err!(
1912 "implicit elided lifetime not allowed here"
1914 crate::lint::builtin::add_elided_lifetime_in_path_suggestion(
1925 AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
1926 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
1927 ELIDED_LIFETIMES_IN_PATHS,
1930 "hidden lifetime parameters in types are deprecated",
1931 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1944 let res = self.expect_full_res(segment.id);
1945 let id = if let Some(owner) = explicit_owner {
1946 self.lower_node_id_with_owner(segment.id, owner)
1948 self.lower_node_id(segment.id)
1951 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
1952 segment.ident, segment.id, id,
1956 ident: segment.ident,
1958 res: Some(self.lower_res(res)),
1960 args: if generic_args.is_empty() {
1963 Some(self.arena.alloc(generic_args.into_generic_args(self.arena)))
1968 fn lower_angle_bracketed_parameter_data(
1970 data: &AngleBracketedArgs,
1971 param_mode: ParamMode,
1972 mut itctx: ImplTraitContext<'_, 'hir>,
1973 ) -> (GenericArgsCtor<'hir>, bool) {
1974 let &AngleBracketedArgs { ref args, ref constraints, .. } = data;
1975 let has_non_lt_args = args.iter().any(|arg| match arg {
1976 ast::GenericArg::Lifetime(_) => false,
1977 ast::GenericArg::Type(_) => true,
1978 ast::GenericArg::Const(_) => true,
1982 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1983 bindings: self.arena.alloc_from_iter(
1984 constraints.iter().map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow())),
1986 parenthesized: false,
1988 !has_non_lt_args && param_mode == ParamMode::Optional,
1992 fn lower_parenthesized_parameter_data(
1994 data: &ParenthesizedArgs,
1995 ) -> (GenericArgsCtor<'hir>, bool) {
1996 // Switch to `PassThrough` mode for anonymous lifetimes; this
1997 // means that we permit things like `&Ref<T>`, where `Ref` has
1998 // a hidden lifetime parameter. This is needed for backwards
1999 // compatibility, even in contexts like an impl header where
2000 // we generally don't permit such things (see #51008).
2001 self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
2002 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2003 let inputs = this.arena.alloc_from_iter(
2004 inputs.iter().map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed())),
2006 let output_ty = match output {
2007 FunctionRetTy::Ty(ty) => this.lower_ty(&ty, ImplTraitContext::disallowed()),
2008 FunctionRetTy::Default(_) => this.arena.alloc(this.ty_tup(span, &[])),
2010 let args = smallvec![GenericArg::Type(this.ty_tup(span, inputs))];
2011 let binding = hir::TypeBinding {
2012 hir_id: this.next_id(),
2013 ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
2014 span: output_ty.span,
2015 kind: hir::TypeBindingKind::Equality { ty: output_ty },
2018 GenericArgsCtor { args, bindings: arena_vec![this; binding], parenthesized: true },
2024 fn lower_local(&mut self, l: &Local) -> (hir::Local<'hir>, SmallVec<[NodeId; 1]>) {
2025 let mut ids = SmallVec::<[NodeId; 1]>::new();
2026 if self.sess.features_untracked().impl_trait_in_bindings {
2027 if let Some(ref ty) = l.ty {
2028 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2029 visitor.visit_ty(ty);
2032 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2033 let ty = l.ty.as_ref().map(|t| {
2036 if self.sess.features_untracked().impl_trait_in_bindings {
2037 ImplTraitContext::OpaqueTy(Some(parent_def_id))
2039 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2043 let init = l.init.as_ref().map(|e| self.lower_expr(e));
2046 hir_id: self.lower_node_id(l.id),
2048 pat: self.lower_pat(&l.pat),
2051 attrs: l.attrs.clone(),
2052 source: hir::LocalSource::Normal,
2058 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
2059 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
2060 // as they are not explicit in HIR/Ty function signatures.
2061 // (instead, the `c_variadic` flag is set to `true`)
2062 let mut inputs = &decl.inputs[..];
2063 if decl.c_variadic() {
2064 inputs = &inputs[..inputs.len() - 1];
2066 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
2067 PatKind::Ident(_, ident, _) => ident,
2068 _ => Ident::new(kw::Invalid, param.pat.span),
2072 // Lowers a function declaration.
2074 // `decl`: the unlowered (AST) function declaration.
2075 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
2076 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2077 // `make_ret_async` is also `Some`.
2078 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
2079 // This guards against trait declarations and implementations where `impl Trait` is
2081 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2082 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
2083 // return type `impl Trait` item.
2087 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam<'hir>>)>,
2088 impl_trait_return_allow: bool,
2089 make_ret_async: Option<NodeId>,
2090 ) -> &'hir hir::FnDecl<'hir> {
2094 in_band_ty_params: {:?}, \
2095 impl_trait_return_allow: {}, \
2096 make_ret_async: {:?})",
2097 decl, in_band_ty_params, impl_trait_return_allow, make_ret_async,
2099 let lt_mode = if make_ret_async.is_some() {
2100 // In `async fn`, argument-position elided lifetimes
2101 // must be transformed into fresh generic parameters so that
2102 // they can be applied to the opaque `impl Trait` return type.
2103 AnonymousLifetimeMode::CreateParameter
2105 self.anonymous_lifetime_mode
2108 let c_variadic = decl.c_variadic();
2110 // Remember how many lifetimes were already around so that we can
2111 // only look at the lifetime parameters introduced by the arguments.
2112 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2113 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
2114 // as they are not explicit in HIR/Ty function signatures.
2115 // (instead, the `c_variadic` flag is set to `true`)
2116 let mut inputs = &decl.inputs[..];
2118 inputs = &inputs[..inputs.len() - 1];
2120 this.arena.alloc_from_iter(inputs.iter().map(|param| {
2121 if let Some((_, ibty)) = &mut in_band_ty_params {
2122 this.lower_ty_direct(¶m.ty, ImplTraitContext::Universal(ibty))
2124 this.lower_ty_direct(¶m.ty, ImplTraitContext::disallowed())
2129 let output = if let Some(ret_id) = make_ret_async {
2130 self.lower_async_fn_ret_ty(
2132 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
2137 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2138 Some((def_id, _)) if impl_trait_return_allow => hir::FunctionRetTy::Return(
2139 self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(def_id))),
2141 _ => hir::FunctionRetTy::Return(
2142 self.lower_ty(ty, ImplTraitContext::disallowed()),
2145 FunctionRetTy::Default(span) => hir::FunctionRetTy::DefaultReturn(span),
2149 self.arena.alloc(hir::FnDecl {
2153 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
2154 let is_mutable_pat = match arg.pat.kind {
2155 PatKind::Ident(BindingMode::ByValue(mt), _, _)
2156 | PatKind::Ident(BindingMode::ByRef(mt), _, _) => mt == Mutability::Mut,
2161 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2162 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2163 // Given we are only considering `ImplicitSelf` types, we needn't consider
2164 // the case where we have a mutable pattern to a reference as that would
2165 // no longer be an `ImplicitSelf`.
2166 TyKind::Rptr(_, ref mt)
2167 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
2169 hir::ImplicitSelfKind::MutRef
2171 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
2172 hir::ImplicitSelfKind::ImmRef
2174 _ => hir::ImplicitSelfKind::None,
2180 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
2181 // combined with the following definition of `OpaqueTy`:
2183 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
2185 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
2186 // `output`: unlowered output type (`T` in `-> T`)
2187 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
2188 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
2189 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
2190 fn lower_async_fn_ret_ty(
2192 output: &FunctionRetTy,
2194 opaque_ty_node_id: NodeId,
2195 ) -> hir::FunctionRetTy<'hir> {
2197 "lower_async_fn_ret_ty(\
2200 opaque_ty_node_id={:?})",
2201 output, fn_def_id, opaque_ty_node_id,
2204 let span = output.span();
2206 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
2208 let opaque_ty_def_index =
2209 self.resolver.definitions().opt_def_index(opaque_ty_node_id).unwrap();
2211 self.allocate_hir_id_counter(opaque_ty_node_id);
2213 // When we create the opaque type for this async fn, it is going to have
2214 // to capture all the lifetimes involved in the signature (including in the
2215 // return type). This is done by introducing lifetime parameters for:
2217 // - all the explicitly declared lifetimes from the impl and function itself;
2218 // - all the elided lifetimes in the fn arguments;
2219 // - all the elided lifetimes in the return type.
2221 // So for example in this snippet:
2224 // impl<'a> Foo<'a> {
2225 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
2226 // // ^ '0 ^ '1 ^ '2
2227 // // elided lifetimes used below
2232 // we would create an opaque type like:
2235 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
2238 // and we would then desugar `bar` to the equivalent of:
2241 // impl<'a> Foo<'a> {
2242 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
2246 // Note that the final parameter to `Bar` is `'_`, not `'2` --
2247 // this is because the elided lifetimes from the return type
2248 // should be figured out using the ordinary elision rules, and
2249 // this desugaring achieves that.
2251 // The variable `input_lifetimes_count` tracks the number of
2252 // lifetime parameters to the opaque type *not counting* those
2253 // lifetimes elided in the return type. This includes those
2254 // that are explicitly declared (`in_scope_lifetimes`) and
2255 // those elided lifetimes we found in the arguments (current
2256 // content of `lifetimes_to_define`). Next, we will process
2257 // the return type, which will cause `lifetimes_to_define` to
2259 let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
2261 let (opaque_ty_id, lifetime_params) = self.with_hir_id_owner(opaque_ty_node_id, |this| {
2262 // We have to be careful to get elision right here. The
2263 // idea is that we create a lifetime parameter for each
2264 // lifetime in the return type. So, given a return type
2265 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
2266 // Future<Output = &'1 [ &'2 u32 ]>`.
2268 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
2269 // hence the elision takes place at the fn site.
2270 let future_bound = this
2271 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::CreateParameter, |this| {
2272 this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
2275 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
2277 // Calculate all the lifetimes that should be captured
2278 // by the opaque type. This should include all in-scope
2279 // lifetime parameters, including those defined in-band.
2281 // Note: this must be done after lowering the output type,
2282 // as the output type may introduce new in-band lifetimes.
2283 let lifetime_params: Vec<(Span, ParamName)> = this
2287 .map(|name| (name.ident().span, name))
2288 .chain(this.lifetimes_to_define.iter().cloned())
2291 debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes);
2292 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define);
2293 debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
2295 let generic_params =
2296 this.arena.alloc_from_iter(lifetime_params.iter().map(|(span, hir_name)| {
2297 this.lifetime_to_generic_param(*span, *hir_name, opaque_ty_def_index)
2300 let opaque_ty_item = hir::OpaqueTy {
2301 generics: hir::Generics {
2302 params: generic_params,
2303 where_clause: hir::WhereClause { predicates: &[], span },
2306 bounds: arena_vec![this; future_bound],
2307 impl_trait_fn: Some(fn_def_id),
2308 origin: hir::OpaqueTyOrigin::AsyncFn,
2311 trace!("exist ty from async fn def index: {:#?}", opaque_ty_def_index);
2313 this.generate_opaque_type(opaque_ty_node_id, opaque_ty_item, span, opaque_ty_span);
2315 (opaque_ty_id, lifetime_params)
2318 // As documented above on the variable
2319 // `input_lifetimes_count`, we need to create the lifetime
2320 // arguments to our opaque type. Continuing with our example,
2321 // we're creating the type arguments for the return type:
2324 // Bar<'a, 'b, '0, '1, '_>
2327 // For the "input" lifetime parameters, we wish to create
2328 // references to the parameters themselves, including the
2329 // "implicit" ones created from parameter types (`'a`, `'b`,
2332 // For the "output" lifetime parameters, we just want to
2334 let mut generic_args: Vec<_> = lifetime_params[..input_lifetimes_count]
2336 .map(|&(span, hir_name)| {
2337 // Input lifetime like `'a` or `'1`:
2338 GenericArg::Lifetime(hir::Lifetime {
2339 hir_id: self.next_id(),
2341 name: hir::LifetimeName::Param(hir_name),
2345 generic_args.extend(lifetime_params[input_lifetimes_count..].iter().map(|&(span, _)|
2346 // Output lifetime like `'_`.
2347 GenericArg::Lifetime(hir::Lifetime {
2348 hir_id: self.next_id(),
2350 name: hir::LifetimeName::Implicit,
2352 let generic_args = self.arena.alloc_from_iter(generic_args);
2354 // Create the `Foo<...>` reference itself. Note that the `type
2355 // Foo = impl Trait` is, internally, created as a child of the
2356 // async fn, so the *type parameters* are inherited. It's
2357 // only the lifetime parameters that we must supply.
2358 let opaque_ty_ref = hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, generic_args);
2359 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2360 hir::FunctionRetTy::Return(self.arena.alloc(opaque_ty))
2363 /// Transforms `-> T` into `Future<Output = T>`
2364 fn lower_async_fn_output_type_to_future_bound(
2366 output: &FunctionRetTy,
2369 ) -> hir::GenericBound<'hir> {
2370 // Compute the `T` in `Future<Output = T>` from the return type.
2371 let output_ty = match output {
2372 FunctionRetTy::Ty(ty) => self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(fn_def_id))),
2373 FunctionRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
2377 let future_params = self.arena.alloc(hir::GenericArgs {
2379 bindings: arena_vec![self; hir::TypeBinding {
2380 ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
2381 kind: hir::TypeBindingKind::Equality { ty: output_ty },
2382 hir_id: self.next_id(),
2385 parenthesized: false,
2388 // ::std::future::Future<future_params>
2390 self.std_path(span, &[sym::future, sym::Future], Some(future_params), false);
2392 hir::GenericBound::Trait(
2394 trait_ref: hir::TraitRef { path: future_path, hir_ref_id: self.next_id() },
2395 bound_generic_params: &[],
2398 hir::TraitBoundModifier::None,
2402 fn lower_param_bound(
2405 itctx: ImplTraitContext<'_, 'hir>,
2406 ) -> hir::GenericBound<'hir> {
2408 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2409 self.lower_poly_trait_ref(ty, itctx),
2410 self.lower_trait_bound_modifier(modifier),
2412 GenericBound::Outlives(ref lifetime) => {
2413 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2418 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2419 let span = l.ident.span;
2421 ident if ident.name == kw::StaticLifetime => {
2422 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static)
2424 ident if ident.name == kw::UnderscoreLifetime => match self.anonymous_lifetime_mode {
2425 AnonymousLifetimeMode::CreateParameter => {
2426 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2427 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2430 AnonymousLifetimeMode::PassThrough => {
2431 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2434 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2437 self.maybe_collect_in_band_lifetime(ident);
2438 let param_name = ParamName::Plain(ident);
2439 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2444 fn new_named_lifetime(
2448 name: hir::LifetimeName,
2449 ) -> hir::Lifetime {
2450 hir::Lifetime { hir_id: self.lower_node_id(id), span, name }
2453 fn lower_generic_params_mut<'s>(
2455 params: &'s [GenericParam],
2456 add_bounds: &'s NodeMap<Vec<GenericBound>>,
2457 mut itctx: ImplTraitContext<'s, 'hir>,
2458 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
2461 .map(move |param| self.lower_generic_param(param, add_bounds, itctx.reborrow()))
2464 fn lower_generic_params(
2466 params: &[GenericParam],
2467 add_bounds: &NodeMap<Vec<GenericBound>>,
2468 itctx: ImplTraitContext<'_, 'hir>,
2469 ) -> &'hir [hir::GenericParam<'hir>] {
2470 self.arena.alloc_from_iter(self.lower_generic_params_mut(params, add_bounds, itctx))
2473 fn lower_generic_param(
2475 param: &GenericParam,
2476 add_bounds: &NodeMap<Vec<GenericBound>>,
2477 mut itctx: ImplTraitContext<'_, 'hir>,
2478 ) -> hir::GenericParam<'hir> {
2479 let mut bounds: Vec<_> = self
2480 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2481 this.lower_param_bounds_mut(¶m.bounds, itctx.reborrow()).collect()
2484 let (name, kind) = match param.kind {
2485 GenericParamKind::Lifetime => {
2486 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2487 self.is_collecting_in_band_lifetimes = false;
2490 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2491 this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident })
2493 let param_name = match lt.name {
2494 hir::LifetimeName::Param(param_name) => param_name,
2495 hir::LifetimeName::Implicit
2496 | hir::LifetimeName::Underscore
2497 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2498 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2501 "object-lifetime-default should not occur here",
2504 hir::LifetimeName::Error => ParamName::Error,
2508 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2510 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2514 GenericParamKind::Type { ref default, .. } => {
2515 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2516 if !add_bounds.is_empty() {
2517 let params = self.lower_param_bounds_mut(add_bounds, itctx.reborrow());
2518 bounds.extend(params);
2521 let kind = hir::GenericParamKind::Type {
2524 .map(|x| self.lower_ty(x, ImplTraitContext::OpaqueTy(None))),
2528 .filter(|attr| attr.check_name(sym::rustc_synthetic))
2529 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2533 (hir::ParamName::Plain(param.ident), kind)
2535 GenericParamKind::Const { ref ty } => (
2536 hir::ParamName::Plain(param.ident),
2537 hir::GenericParamKind::Const {
2538 ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2544 hir_id: self.lower_node_id(param.id),
2546 span: param.ident.span,
2547 pure_wrt_drop: attr::contains_name(¶m.attrs, sym::may_dangle),
2548 attrs: self.lower_attrs(¶m.attrs),
2549 bounds: self.arena.alloc_from_iter(bounds),
2557 itctx: ImplTraitContext<'_, 'hir>,
2558 ) -> hir::TraitRef<'hir> {
2559 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2560 hir::QPath::Resolved(None, path) => path,
2561 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2563 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2566 fn lower_poly_trait_ref(
2569 mut itctx: ImplTraitContext<'_, 'hir>,
2570 ) -> hir::PolyTraitRef<'hir> {
2571 let bound_generic_params = self.lower_generic_params(
2572 &p.bound_generic_params,
2573 &NodeMap::default(),
2576 let trait_ref = self.with_in_scope_lifetime_defs(&p.bound_generic_params, |this| {
2577 this.lower_trait_ref(&p.trait_ref, itctx)
2580 hir::PolyTraitRef { bound_generic_params, trait_ref, span: p.span }
2583 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_, 'hir>) -> hir::MutTy<'hir> {
2584 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2587 fn lower_param_bounds(
2589 bounds: &[GenericBound],
2590 itctx: ImplTraitContext<'_, 'hir>,
2591 ) -> hir::GenericBounds<'hir> {
2592 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2595 fn lower_param_bounds_mut<'s>(
2597 bounds: &'s [GenericBound],
2598 mut itctx: ImplTraitContext<'s, 'hir>,
2599 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2600 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx.reborrow()))
2603 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> &'hir hir::Block<'hir> {
2604 self.arena.alloc(self.lower_block_noalloc(b, targeted_by_break))
2607 fn lower_block_noalloc(&mut self, b: &Block, targeted_by_break: bool) -> hir::Block<'hir> {
2608 let mut stmts = vec![];
2609 let mut expr: Option<&'hir _> = None;
2611 for (index, stmt) in b.stmts.iter().enumerate() {
2612 if index == b.stmts.len() - 1 {
2613 if let StmtKind::Expr(ref e) = stmt.kind {
2614 expr = Some(self.lower_expr(e));
2616 stmts.extend(self.lower_stmt(stmt));
2619 stmts.extend(self.lower_stmt(stmt));
2624 hir_id: self.lower_node_id(b.id),
2625 stmts: self.arena.alloc_from_iter(stmts),
2627 rules: self.lower_block_check_mode(&b.rules),
2633 /// Lowers a block directly to an expression, presuming that it
2634 /// has no attributes and is not targeted by a `break`.
2635 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2636 let block = self.lower_block(b, false);
2637 self.expr_block(block, AttrVec::new())
2640 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2641 self.with_new_scopes(|this| hir::AnonConst {
2642 hir_id: this.lower_node_id(c.id),
2643 body: this.lower_const_body(c.value.span, Some(&c.value)),
2647 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt<'hir>; 1]> {
2648 let kind = match s.kind {
2649 StmtKind::Local(ref l) => {
2650 let (l, item_ids) = self.lower_local(l);
2651 let mut ids: SmallVec<[hir::Stmt<'hir>; 1]> = item_ids
2654 let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
2655 self.stmt(s.span, hir::StmtKind::Item(item_id))
2660 hir_id: self.lower_node_id(s.id),
2661 kind: hir::StmtKind::Local(self.arena.alloc(l)),
2667 StmtKind::Item(ref it) => {
2668 // Can only use the ID once.
2669 let mut id = Some(s.id);
2676 .map(|id| self.lower_node_id(id))
2677 .unwrap_or_else(|| self.next_id());
2679 hir::Stmt { hir_id, kind: hir::StmtKind::Item(item_id), span: s.span }
2683 StmtKind::Expr(ref e) => hir::StmtKind::Expr(self.lower_expr(e)),
2684 StmtKind::Semi(ref e) => hir::StmtKind::Semi(self.lower_expr(e)),
2685 StmtKind::Mac(..) => panic!("shouldn't exist here"),
2687 smallvec![hir::Stmt { hir_id: self.lower_node_id(s.id), kind, span: s.span }]
2690 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
2692 BlockCheckMode::Default => hir::BlockCheckMode::DefaultBlock,
2693 BlockCheckMode::Unsafe(u) => {
2694 hir::BlockCheckMode::UnsafeBlock(self.lower_unsafe_source(u))
2699 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2701 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2702 UserProvided => hir::UnsafeSource::UserProvided,
2706 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2708 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2709 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
2713 // Helper methods for building HIR.
2715 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2716 hir::Stmt { span, kind, hir_id: self.next_id() }
2719 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2720 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2727 init: Option<&'hir hir::Expr<'hir>>,
2728 pat: &'hir hir::Pat<'hir>,
2729 source: hir::LocalSource,
2730 ) -> hir::Stmt<'hir> {
2731 let local = hir::Local { attrs, hir_id: self.next_id(), init, pat, source, span, ty: None };
2732 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2735 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2736 self.block_all(expr.span, &[], Some(expr))
2742 stmts: &'hir [hir::Stmt<'hir>],
2743 expr: Option<&'hir hir::Expr<'hir>>,
2744 ) -> &'hir hir::Block<'hir> {
2745 let blk = hir::Block {
2748 hir_id: self.next_id(),
2749 rules: hir::BlockCheckMode::DefaultBlock,
2751 targeted_by_break: false,
2753 self.arena.alloc(blk)
2756 /// Constructs a `true` or `false` literal pattern.
2757 fn pat_bool(&mut self, span: Span, val: bool) -> &'hir hir::Pat<'hir> {
2758 let expr = self.expr_bool(span, val);
2759 self.pat(span, hir::PatKind::Lit(expr))
2762 fn pat_ok(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2763 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], arena_vec![self; pat])
2766 fn pat_err(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2767 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], arena_vec![self; pat])
2770 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2771 self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], arena_vec![self; pat])
2774 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2775 self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], &[])
2781 components: &[Symbol],
2782 subpats: &'hir [&'hir hir::Pat<'hir>],
2783 ) -> &'hir hir::Pat<'hir> {
2784 let path = self.std_path(span, components, None, true);
2785 let qpath = hir::QPath::Resolved(None, path);
2786 let pt = if subpats.is_empty() {
2787 hir::PatKind::Path(qpath)
2789 hir::PatKind::TupleStruct(qpath, subpats, None)
2794 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2795 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
2798 fn pat_ident_binding_mode(
2802 bm: hir::BindingAnnotation,
2803 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2804 let hir_id = self.next_id();
2807 self.arena.alloc(hir::Pat {
2809 kind: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
2816 fn pat_wild(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2817 self.pat(span, hir::PatKind::Wild)
2820 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2821 self.arena.alloc(hir::Pat { hir_id: self.next_id(), kind, span })
2824 /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when
2825 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
2826 /// The path is also resolved according to `is_value`.
2830 components: &[Symbol],
2831 params: Option<&'hir hir::GenericArgs<'hir>>,
2833 ) -> &'hir hir::Path<'hir> {
2834 let ns = if is_value { Namespace::ValueNS } else { Namespace::TypeNS };
2835 let (path, res) = self.resolver.resolve_str_path(span, self.crate_root, components, ns);
2837 let mut segments: Vec<_> = path
2841 let res = self.expect_full_res(segment.id);
2843 ident: segment.ident,
2844 hir_id: Some(self.lower_node_id(segment.id)),
2845 res: Some(self.lower_res(res)),
2851 segments.last_mut().unwrap().args = params;
2853 self.arena.alloc(hir::Path {
2855 res: res.map_id(|_| panic!("unexpected `NodeId`")),
2856 segments: self.arena.alloc_from_iter(segments),
2862 mut hir_id: hir::HirId,
2864 qpath: hir::QPath<'hir>,
2865 ) -> hir::Ty<'hir> {
2866 let kind = match qpath {
2867 hir::QPath::Resolved(None, path) => {
2868 // Turn trait object paths into `TyKind::TraitObject` instead.
2870 Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
2871 let principal = hir::PolyTraitRef {
2872 bound_generic_params: &[],
2873 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2877 // The original ID is taken by the `PolyTraitRef`,
2878 // so the `Ty` itself needs a different one.
2879 hir_id = self.next_id();
2880 hir::TyKind::TraitObject(
2881 arena_vec![self; principal],
2882 self.elided_dyn_bound(span),
2885 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2888 _ => hir::TyKind::Path(qpath),
2891 hir::Ty { hir_id, kind, span }
2894 /// Invoked to create the lifetime argument for a type `&T`
2895 /// with no explicit lifetime.
2896 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
2897 match self.anonymous_lifetime_mode {
2898 // Intercept when we are in an impl header or async fn and introduce an in-band
2900 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
2902 AnonymousLifetimeMode::CreateParameter => {
2903 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2905 hir_id: self.next_id(),
2907 name: hir::LifetimeName::Param(fresh_name),
2911 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
2913 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
2917 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
2918 /// return a "error lifetime".
2919 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
2920 let (id, msg, label) = match id {
2921 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
2924 self.resolver.next_node_id(),
2925 "`&` without an explicit lifetime name cannot be used here",
2926 "explicit lifetime name needed here",
2930 let mut err = struct_span_err!(self.sess, span, E0637, "{}", msg,);
2931 err.span_label(span, label);
2934 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2937 /// Invoked to create the lifetime argument(s) for a path like
2938 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
2939 /// sorts of cases are deprecated. This may therefore report a warning or an
2940 /// error, depending on the mode.
2941 fn elided_path_lifetimes<'s>(
2945 ) -> impl Iterator<Item = hir::Lifetime> + Captures<'a> + Captures<'s> + Captures<'hir> {
2946 (0..count).map(move |_| self.elided_path_lifetime(span))
2949 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
2950 match self.anonymous_lifetime_mode {
2951 AnonymousLifetimeMode::CreateParameter => {
2952 // We should have emitted E0726 when processing this path above
2954 .delay_span_bug(span, "expected 'implicit elided lifetime not allowed' error");
2955 let id = self.resolver.next_node_id();
2956 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2958 // `PassThrough` is the normal case.
2959 // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
2960 // is unsuitable here, as these can occur from missing lifetime parameters in a
2961 // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
2962 // lifetime. Instead, we simply create an implicit lifetime, which will be checked
2963 // later, at which point a suitable error will be emitted.
2964 AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
2965 self.new_implicit_lifetime(span)
2970 /// Invoked to create the lifetime argument(s) for an elided trait object
2971 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2972 /// when the bound is written, even if it is written with `'_` like in
2973 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2974 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2975 match self.anonymous_lifetime_mode {
2976 // NB. We intentionally ignore the create-parameter mode here.
2977 // and instead "pass through" to resolve-lifetimes, which will apply
2978 // the object-lifetime-defaulting rules. Elided object lifetime defaults
2979 // do not act like other elided lifetimes. In other words, given this:
2981 // impl Foo for Box<dyn Debug>
2983 // we do not introduce a fresh `'_` to serve as the bound, but instead
2984 // ultimately translate to the equivalent of:
2986 // impl Foo for Box<dyn Debug + 'static>
2988 // `resolve_lifetime` has the code to make that happen.
2989 AnonymousLifetimeMode::CreateParameter => {}
2991 AnonymousLifetimeMode::ReportError => {
2992 // ReportError applies to explicit use of `'_`.
2995 // This is the normal case.
2996 AnonymousLifetimeMode::PassThrough => {}
2999 let r = hir::Lifetime {
3000 hir_id: self.next_id(),
3002 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
3004 debug!("elided_dyn_bound: r={:?}", r);
3008 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
3009 hir::Lifetime { hir_id: self.next_id(), span, name: hir::LifetimeName::Implicit }
3012 fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) {
3013 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
3014 // call site which do not have a macro backtrace. See #61963.
3015 let is_macro_callsite = self
3018 .span_to_snippet(span)
3019 .map(|snippet| snippet.starts_with("#["))
3021 if !is_macro_callsite {
3022 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
3023 builtin::BARE_TRAIT_OBJECTS,
3026 "trait objects without an explicit `dyn` are deprecated",
3027 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
3033 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body<'_>>) -> Vec<hir::BodyId> {
3034 // Sorting by span ensures that we get things in order within a
3035 // file, and also puts the files in a sensible order.
3036 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
3037 body_ids.sort_by_key(|b| bodies[b].value.span);
3041 /// Helper struct for delayed construction of GenericArgs.
3042 struct GenericArgsCtor<'hir> {
3043 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
3044 bindings: &'hir [hir::TypeBinding<'hir>],
3045 parenthesized: bool,
3048 impl<'hir> GenericArgsCtor<'hir> {
3049 fn is_empty(&self) -> bool {
3050 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
3053 fn into_generic_args(self, arena: &'hir Arena<'hir>) -> hir::GenericArgs<'hir> {
3055 args: arena.alloc_from_iter(self.args),
3056 bindings: self.bindings,
3057 parenthesized: self.parenthesized,