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 use crate::dep_graph::DepGraph;
36 use crate::hir::{self, ParamName};
37 use crate::hir::HirVec;
38 use crate::hir::map::{DefKey, DefPathData, Definitions};
39 use crate::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
40 use crate::hir::def::{Res, DefKind, PartialRes, PerNS};
41 use crate::hir::{GenericArg, ConstArg};
42 use crate::lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
43 ELIDED_LIFETIMES_IN_PATHS};
44 use crate::middle::cstore::CrateStore;
45 use crate::session::Session;
46 use crate::session::config::nightly_options;
47 use crate::util::common::FN_OUTPUT_NAME;
48 use crate::util::nodemap::{DefIdMap, NodeMap};
49 use errors::Applicability;
50 use rustc_data_structures::fx::FxHashSet;
51 use rustc_data_structures::indexed_vec::IndexVec;
52 use rustc_data_structures::thin_vec::ThinVec;
53 use rustc_data_structures::sync::Lrc;
55 use std::collections::{BTreeSet, BTreeMap};
57 use smallvec::SmallVec;
62 use syntax::ext::hygiene::{Mark, SyntaxContext};
63 use syntax::print::pprust;
65 use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned};
66 use syntax::source_map::CompilerDesugaringKind::IfTemporary;
67 use syntax::std_inject;
68 use syntax::symbol::{kw, sym, Symbol};
69 use syntax::tokenstream::{TokenStream, TokenTree};
70 use syntax::parse::token::Token;
71 use syntax::visit::{self, Visitor};
72 use syntax_pos::{DUMMY_SP, edition, Span};
74 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
76 pub struct LoweringContext<'a> {
77 crate_root: Option<Symbol>,
79 /// Used to assign ids to HIR nodes that do not directly correspond to an AST node.
82 cstore: &'a dyn CrateStore,
84 resolver: &'a mut dyn Resolver,
86 /// The items being lowered are collected here.
87 items: BTreeMap<hir::HirId, hir::Item>,
89 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
90 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
91 bodies: BTreeMap<hir::BodyId, hir::Body>,
92 exported_macros: Vec<hir::MacroDef>,
94 trait_impls: BTreeMap<DefId, Vec<hir::HirId>>,
96 modules: BTreeMap<NodeId, hir::ModuleItems>,
101 /// Used to get the current `fn`'s def span to point to when using `await`
102 /// outside of an `async fn`.
103 current_item: Option<Span>,
105 catch_scopes: Vec<NodeId>,
106 loop_scopes: Vec<NodeId>,
107 is_in_loop_condition: bool,
108 is_in_trait_impl: bool,
110 /// What to do when we encounter either an "anonymous lifetime
111 /// reference". The term "anonymous" is meant to encompass both
112 /// `'_` lifetimes as well as fully elided cases where nothing is
113 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
114 anonymous_lifetime_mode: AnonymousLifetimeMode,
116 /// Used to create lifetime definitions from in-band lifetime usages.
117 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
118 /// When a named lifetime is encountered in a function or impl header and
119 /// has not been defined
120 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
121 /// to this list. The results of this list are then added to the list of
122 /// lifetime definitions in the corresponding impl or function generics.
123 lifetimes_to_define: Vec<(Span, ParamName)>,
125 /// Whether or not in-band lifetimes are being collected. This is used to
126 /// indicate whether or not we're in a place where new lifetimes will result
127 /// in in-band lifetime definitions, such a function or an impl header,
128 /// including implicit lifetimes from `impl_header_lifetime_elision`.
129 is_collecting_in_band_lifetimes: bool,
131 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
132 /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
133 /// against this list to see if it is already in-scope, or if a definition
134 /// needs to be created for it.
135 in_scope_lifetimes: Vec<Ident>,
137 current_module: NodeId,
139 type_def_lifetime_params: DefIdMap<usize>,
141 current_hir_id_owner: Vec<(DefIndex, u32)>,
142 item_local_id_counters: NodeMap<u32>,
143 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
147 /// Resolve a path generated by the lowerer when expanding `for`, `if let`, etc.
154 /// Obtain resolution for a `NodeId` with a single resolution.
155 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
157 /// Obtain per-namespace resolutions for `use` statement with the given `NoedId`.
158 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
160 /// Obtain resolution for a label with the given `NodeId`.
161 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
163 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
164 /// This should only return `None` during testing.
165 fn definitions(&mut self) -> &mut Definitions;
167 /// Given suffix `["b", "c", "d"]`, creates a HIR path for `[::crate_root]::b::c::d` and
168 /// resolves it based on `is_value`.
172 crate_root: Option<Symbol>,
173 components: &[Symbol],
178 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
179 /// and if so, what meaning it has.
181 enum ImplTraitContext<'a> {
182 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
183 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
184 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
186 /// Newly generated parameters should be inserted into the given `Vec`.
187 Universal(&'a mut Vec<hir::GenericParam>),
189 /// Treat `impl Trait` as shorthand for a new existential parameter.
190 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
191 /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
193 /// We optionally store a `DefId` for the parent item here so we can look up necessary
194 /// information later. It is `None` when no information about the context should be stored
195 /// (e.g., for consts and statics).
196 Existential(Option<DefId> /* fn def-ID */),
198 /// Treat `impl Trait` as a bound on the associated type applied to the trait.
199 /// Example: `trait Foo { type Bar: Iterator<Item = impl Debug>; }` is conceptually
200 /// equivalent to `trait Foo where <Self::Bar as Iterator>::Item: Debug
201 /// { type Bar: Iterator; }`.
204 /// `impl Trait` is not accepted in this position.
205 Disallowed(ImplTraitPosition),
208 /// Position in which `impl Trait` is disallowed. Used for error reporting.
209 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
210 enum ImplTraitPosition {
215 impl<'a> ImplTraitContext<'a> {
217 fn disallowed() -> Self {
218 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
221 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
222 use self::ImplTraitContext::*;
224 Universal(params) => Universal(params),
225 Existential(fn_def_id) => Existential(*fn_def_id),
226 AssociatedTy => AssociatedTy,
227 Disallowed(pos) => Disallowed(*pos),
234 cstore: &dyn CrateStore,
235 dep_graph: &DepGraph,
237 resolver: &mut dyn Resolver,
239 // We're constructing the HIR here; we don't care what we will
240 // read, since we haven't even constructed the *input* to
242 dep_graph.assert_ignored();
245 crate_root: std_inject::injected_crate_name().map(Symbol::intern),
249 items: BTreeMap::new(),
250 trait_items: BTreeMap::new(),
251 impl_items: BTreeMap::new(),
252 bodies: BTreeMap::new(),
253 trait_impls: BTreeMap::new(),
254 modules: BTreeMap::new(),
255 exported_macros: Vec::new(),
256 catch_scopes: Vec::new(),
257 loop_scopes: Vec::new(),
258 is_in_loop_condition: false,
259 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
260 type_def_lifetime_params: Default::default(),
261 current_module: CRATE_NODE_ID,
262 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
263 item_local_id_counters: Default::default(),
264 node_id_to_hir_id: IndexVec::new(),
266 is_async_body: false,
268 is_in_trait_impl: false,
269 lifetimes_to_define: Vec::new(),
270 is_collecting_in_band_lifetimes: false,
271 in_scope_lifetimes: Vec::new(),
275 #[derive(Copy, Clone, PartialEq)]
277 /// Any path in a type context.
279 /// The `module::Type` in `module::Type::method` in an expression.
283 enum ParenthesizedGenericArgs {
289 /// What to do when we encounter an **anonymous** lifetime
290 /// reference. Anonymous lifetime references come in two flavors. You
291 /// have implicit, or fully elided, references to lifetimes, like the
292 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
293 /// or `Ref<'_, T>`. These often behave the same, but not always:
295 /// - certain usages of implicit references are deprecated, like
296 /// `Ref<T>`, and we sometimes just give hard errors in those cases
298 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
299 /// the same as `Box<dyn Foo + '_>`.
301 /// We describe the effects of the various modes in terms of three cases:
303 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
304 /// of a `&` (e.g., the missing lifetime in something like `&T`)
305 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
306 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
307 /// elided bounds follow special rules. Note that this only covers
308 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
309 /// '_>` is a case of "modern" elision.
310 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
311 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
312 /// non-deprecated equivalent.
314 /// Currently, the handling of lifetime elision is somewhat spread out
315 /// between HIR lowering and -- as described below -- the
316 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
317 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
318 /// everything into HIR lowering.
319 #[derive(Copy, Clone)]
320 enum AnonymousLifetimeMode {
321 /// For **Modern** cases, create a new anonymous region parameter
322 /// and reference that.
324 /// For **Dyn Bound** cases, pass responsibility to
325 /// `resolve_lifetime` code.
327 /// For **Deprecated** cases, report an error.
330 /// Give a hard error when either `&` or `'_` is written. Used to
331 /// rule out things like `where T: Foo<'_>`. Does not imply an
332 /// error on default object bounds (e.g., `Box<dyn Foo>`).
335 /// Pass responsibility to `resolve_lifetime` code for all cases.
338 /// Used in the return types of `async fn` where there exists
339 /// exactly one argument-position elided lifetime.
341 /// In `async fn`, we lower the arguments types using the `CreateParameter`
342 /// mode, meaning that non-`dyn` elided lifetimes are assigned a fresh name.
343 /// If any corresponding elided lifetimes appear in the output, we need to
344 /// replace them with references to the fresh name assigned to the corresponding
345 /// elided lifetime in the arguments.
347 /// For **Modern cases**, replace the anonymous parameter with a
348 /// reference to a specific freshly-named lifetime that was
349 /// introduced in argument
351 /// For **Dyn Bound** cases, pass responsibility to
352 /// `resole_lifetime` code.
353 Replace(LtReplacement),
356 /// The type of elided lifetime replacement to perform on `async fn` return types.
357 #[derive(Copy, Clone)]
359 /// Fresh name introduced by the single non-dyn elided lifetime
360 /// in the arguments of the async fn.
363 /// There is no single non-dyn elided lifetime because no lifetimes
364 /// appeared in the arguments.
367 /// There is no single non-dyn elided lifetime because multiple
368 /// lifetimes appeared in the arguments.
372 /// Calculates the `LtReplacement` to use for elided lifetimes in the return
373 /// type based on the fresh elided lifetimes introduced in argument position.
374 fn get_elided_lt_replacement(arg_position_lifetimes: &[(Span, ParamName)]) -> LtReplacement {
375 match arg_position_lifetimes {
376 [] => LtReplacement::NoLifetimes,
377 [(_span, param)] => LtReplacement::Some(*param),
378 _ => LtReplacement::MultipleLifetimes,
382 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[NodeId; 1]> }
384 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
385 fn visit_ty(&mut self, ty: &'a Ty) {
391 TyKind::ImplTrait(id, _) => self.ids.push(id),
394 visit::walk_ty(self, ty);
397 fn visit_path_segment(
400 path_segment: &'v PathSegment,
402 if let Some(ref p) = path_segment.args {
403 if let GenericArgs::Parenthesized(_) = **p {
407 visit::walk_path_segment(self, path_span, path_segment)
411 impl<'a> LoweringContext<'a> {
412 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
413 /// Full-crate AST visitor that inserts into a fresh
414 /// `LoweringContext` any information that may be
415 /// needed from arbitrary locations in the crate,
416 /// e.g., the number of lifetime generic parameters
417 /// declared for every type and trait definition.
418 struct MiscCollector<'lcx, 'interner: 'lcx> {
419 lctx: &'lcx mut LoweringContext<'interner>,
420 hir_id_owner: Option<NodeId>,
423 impl MiscCollector<'_, '_> {
424 fn allocate_use_tree_hir_id_counters(
430 UseTreeKind::Simple(_, id1, id2) => {
431 for &id in &[id1, id2] {
432 self.lctx.resolver.definitions().create_def_with_parent(
439 self.lctx.allocate_hir_id_counter(id);
442 UseTreeKind::Glob => (),
443 UseTreeKind::Nested(ref trees) => {
444 for &(ref use_tree, id) in trees {
445 let hir_id = self.lctx.allocate_hir_id_counter(id);
446 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
452 fn with_hir_id_owner<F, T>(&mut self, owner: Option<NodeId>, f: F) -> T
454 F: FnOnce(&mut Self) -> T,
456 let old = mem::replace(&mut self.hir_id_owner, owner);
458 self.hir_id_owner = old;
463 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
464 fn visit_pat(&mut self, p: &'lcx Pat) {
466 // Doesn't generate a HIR node
467 PatKind::Paren(..) => {},
469 if let Some(owner) = self.hir_id_owner {
470 self.lctx.lower_node_id_with_owner(p.id, owner);
475 visit::walk_pat(self, p)
478 fn visit_item(&mut self, item: &'lcx Item) {
479 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
482 ItemKind::Struct(_, ref generics)
483 | ItemKind::Union(_, ref generics)
484 | ItemKind::Enum(_, ref generics)
485 | ItemKind::Ty(_, ref generics)
486 | ItemKind::Existential(_, ref generics)
487 | ItemKind::Trait(_, _, ref generics, ..) => {
488 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
492 .filter(|param| match param.kind {
493 ast::GenericParamKind::Lifetime { .. } => true,
497 self.lctx.type_def_lifetime_params.insert(def_id, count);
499 ItemKind::Use(ref use_tree) => {
500 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
505 self.with_hir_id_owner(Some(item.id), |this| {
506 visit::walk_item(this, item);
510 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
511 self.lctx.allocate_hir_id_counter(item.id);
514 TraitItemKind::Method(_, None) => {
515 // Ignore patterns in trait methods without bodies
516 self.with_hir_id_owner(None, |this| {
517 visit::walk_trait_item(this, item)
520 _ => self.with_hir_id_owner(Some(item.id), |this| {
521 visit::walk_trait_item(this, item);
526 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
527 self.lctx.allocate_hir_id_counter(item.id);
528 self.with_hir_id_owner(Some(item.id), |this| {
529 visit::walk_impl_item(this, item);
533 fn visit_foreign_item(&mut self, i: &'lcx ForeignItem) {
534 // Ignore patterns in foreign items
535 self.with_hir_id_owner(None, |this| {
536 visit::walk_foreign_item(this, i)
540 fn visit_ty(&mut self, t: &'lcx Ty) {
542 // Mirrors the case in visit::walk_ty
543 TyKind::BareFn(ref f) => {
549 // Mirrors visit::walk_fn_decl
550 for argument in &f.decl.inputs {
551 // We don't lower the ids of argument patterns
552 self.with_hir_id_owner(None, |this| {
553 this.visit_pat(&argument.pat);
555 self.visit_ty(&argument.ty)
557 self.visit_fn_ret_ty(&f.decl.output)
559 _ => visit::walk_ty(self, t),
564 struct ItemLowerer<'lcx, 'interner: 'lcx> {
565 lctx: &'lcx mut LoweringContext<'interner>,
568 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
569 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
571 F: FnOnce(&mut Self),
573 let old = self.lctx.is_in_trait_impl;
574 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
580 self.lctx.is_in_trait_impl = old;
584 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
585 fn visit_mod(&mut self, m: &'lcx Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
586 self.lctx.modules.insert(n, hir::ModuleItems {
587 items: BTreeSet::new(),
588 trait_items: BTreeSet::new(),
589 impl_items: BTreeSet::new(),
592 let old = self.lctx.current_module;
593 self.lctx.current_module = n;
594 visit::walk_mod(self, m);
595 self.lctx.current_module = old;
598 fn visit_item(&mut self, item: &'lcx Item) {
599 let mut item_hir_id = None;
600 self.lctx.with_hir_id_owner(item.id, |lctx| {
601 if let Some(hir_item) = lctx.lower_item(item) {
602 item_hir_id = Some(hir_item.hir_id);
603 lctx.insert_item(hir_item);
607 if let Some(hir_id) = item_hir_id {
608 let item_generics = match self.lctx.items.get(&hir_id).unwrap().node {
609 hir::ItemKind::Impl(_, _, _, ref generics, ..)
610 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
611 generics.params.clone()
616 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
617 let this = &mut ItemLowerer { lctx: this };
618 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
619 this.with_trait_impl_ref(opt_trait_ref, |this| {
620 visit::walk_item(this, item)
623 visit::walk_item(this, item);
629 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
630 self.lctx.with_hir_id_owner(item.id, |lctx| {
631 let hir_item = lctx.lower_trait_item(item);
632 let id = hir::TraitItemId { hir_id: hir_item.hir_id };
633 lctx.trait_items.insert(id, hir_item);
634 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
637 visit::walk_trait_item(self, item);
640 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
641 self.lctx.with_hir_id_owner(item.id, |lctx| {
642 let hir_item = lctx.lower_impl_item(item);
643 let id = hir::ImplItemId { hir_id: hir_item.hir_id };
644 lctx.impl_items.insert(id, hir_item);
645 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
647 visit::walk_impl_item(self, item);
651 self.lower_node_id(CRATE_NODE_ID);
652 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
654 visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
655 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
657 let module = self.lower_mod(&c.module);
658 let attrs = self.lower_attrs(&c.attrs);
659 let body_ids = body_ids(&self.bodies);
663 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
669 exported_macros: hir::HirVec::from(self.exported_macros),
671 trait_items: self.trait_items,
672 impl_items: self.impl_items,
675 trait_impls: self.trait_impls,
676 modules: self.modules,
680 fn insert_item(&mut self, item: hir::Item) {
681 let id = item.hir_id;
682 // FIXME: Use `debug_asset-rt`.
683 assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
684 self.items.insert(id, item);
685 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
688 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
689 // Set up the counter if needed.
690 self.item_local_id_counters.entry(owner).or_insert(0);
691 // Always allocate the first `HirId` for the owner itself.
692 let lowered = self.lower_node_id_with_owner(owner, owner);
693 debug_assert_eq!(lowered.local_id.as_u32(), 0);
697 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> hir::HirId
699 F: FnOnce(&mut Self) -> hir::HirId,
701 if ast_node_id == DUMMY_NODE_ID {
702 return hir::DUMMY_HIR_ID;
705 let min_size = ast_node_id.as_usize() + 1;
707 if min_size > self.node_id_to_hir_id.len() {
708 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
711 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
713 if existing_hir_id == hir::DUMMY_HIR_ID {
714 // Generate a new `HirId`.
715 let hir_id = alloc_hir_id(self);
716 self.node_id_to_hir_id[ast_node_id] = hir_id;
724 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
726 F: FnOnce(&mut Self) -> T,
728 let counter = self.item_local_id_counters
729 .insert(owner, HIR_ID_COUNTER_LOCKED)
730 .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
731 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
732 self.current_hir_id_owner.push((def_index, counter));
734 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
736 debug_assert!(def_index == new_def_index);
737 debug_assert!(new_counter >= counter);
739 let prev = self.item_local_id_counters
740 .insert(owner, new_counter)
742 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
746 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
747 /// the `LoweringContext`'s `NodeId => HirId` map.
748 /// Take care not to call this method if the resulting `HirId` is then not
749 /// actually used in the HIR, as that would trigger an assertion in the
750 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
751 /// properly. Calling the method twice with the same `NodeId` is fine though.
752 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
753 self.lower_node_id_generic(ast_node_id, |this| {
754 let &mut (def_index, ref mut local_id_counter) =
755 this.current_hir_id_owner.last_mut().unwrap();
756 let local_id = *local_id_counter;
757 *local_id_counter += 1;
760 local_id: hir::ItemLocalId::from_u32(local_id),
765 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
766 self.lower_node_id_generic(ast_node_id, |this| {
767 let local_id_counter = this
768 .item_local_id_counters
770 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
771 let local_id = *local_id_counter;
773 // We want to be sure not to modify the counter in the map while it
774 // is also on the stack. Otherwise we'll get lost updates when writing
775 // back from the stack to the map.
776 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
778 *local_id_counter += 1;
782 .opt_def_index(owner)
783 .expect("you forgot to call `create_def_with_parent` or are lowering node-IDs \
784 that do not belong to the current owner");
788 local_id: hir::ItemLocalId::from_u32(local_id),
793 fn record_body(&mut self, arguments: HirVec<hir::Arg>, value: hir::Expr) -> hir::BodyId {
794 if self.is_generator && self.is_async_body {
799 "`async` generators are not yet supported",
801 self.sess.abort_if_errors();
803 let body = hir::Body {
804 is_generator: self.is_generator || self.is_async_body,
809 self.bodies.insert(id, body);
813 fn next_id(&mut self) -> hir::HirId {
814 self.lower_node_id(self.sess.next_node_id())
817 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
819 self.lower_node_id_generic(id, |_| {
820 panic!("expected node_id to be lowered already for res {:#?}", res)
825 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
826 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
827 if pr.unresolved_segments() != 0 {
828 bug!("path not fully resolved: {:?}", pr);
834 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
835 self.resolver.get_import_res(id).present_items()
838 fn diagnostic(&self) -> &errors::Handler {
839 self.sess.diagnostic()
842 /// Reuses the span but adds information like the kind of the desugaring and features that are
843 /// allowed inside this span.
844 fn mark_span_with_reason(
846 reason: CompilerDesugaringKind,
848 allow_internal_unstable: Option<Lrc<[Symbol]>>,
850 let mark = Mark::fresh(Mark::root());
851 mark.set_expn_info(source_map::ExpnInfo {
853 def_site: Some(span),
854 format: source_map::CompilerDesugaring(reason),
855 allow_internal_unstable,
856 allow_internal_unsafe: false,
857 local_inner_macros: false,
858 edition: edition::Edition::from_session(),
860 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
863 fn with_anonymous_lifetime_mode<R>(
865 anonymous_lifetime_mode: AnonymousLifetimeMode,
866 op: impl FnOnce(&mut Self) -> R,
868 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
869 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
870 let result = op(self);
871 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
875 /// Creates a new `hir::GenericParam` for every new lifetime and
876 /// type parameter encountered while evaluating `f`. Definitions
877 /// are created with the parent provided. If no `parent_id` is
878 /// provided, no definitions will be returned.
880 /// Presuming that in-band lifetimes are enabled, then
881 /// `self.anonymous_lifetime_mode` will be updated to match the
882 /// argument while `f` is running (and restored afterwards).
883 fn collect_in_band_defs<T, F>(
886 anonymous_lifetime_mode: AnonymousLifetimeMode,
888 ) -> (Vec<hir::GenericParam>, T)
890 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
892 assert!(!self.is_collecting_in_band_lifetimes);
893 assert!(self.lifetimes_to_define.is_empty());
894 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
896 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
897 self.is_collecting_in_band_lifetimes = true;
899 let (in_band_ty_params, res) = f(self);
901 self.is_collecting_in_band_lifetimes = false;
902 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
904 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
906 let params = lifetimes_to_define
908 .map(|(span, hir_name)| self.lifetime_to_generic_param(
909 span, hir_name, parent_id.index,
911 .chain(in_band_ty_params.into_iter())
917 /// Converts a lifetime into a new generic parameter.
918 fn lifetime_to_generic_param(
922 parent_index: DefIndex,
923 ) -> hir::GenericParam {
924 let node_id = self.sess.next_node_id();
926 // Get the name we'll use to make the def-path. Note
927 // that collisions are ok here and this shouldn't
928 // really show up for end-user.
929 let (str_name, kind) = match hir_name {
930 ParamName::Plain(ident) => (
931 ident.as_interned_str(),
932 hir::LifetimeParamKind::InBand,
934 ParamName::Fresh(_) => (
935 kw::UnderscoreLifetime.as_interned_str(),
936 hir::LifetimeParamKind::Elided,
938 ParamName::Error => (
939 kw::UnderscoreLifetime.as_interned_str(),
940 hir::LifetimeParamKind::Error,
944 // Add a definition for the in-band lifetime def.
945 self.resolver.definitions().create_def_with_parent(
948 DefPathData::LifetimeNs(str_name),
954 hir_id: self.lower_node_id(node_id),
959 pure_wrt_drop: false,
960 kind: hir::GenericParamKind::Lifetime { kind }
964 /// When there is a reference to some lifetime `'a`, and in-band
965 /// lifetimes are enabled, then we want to push that lifetime into
966 /// the vector of names to define later. In that case, it will get
967 /// added to the appropriate generics.
968 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
969 if !self.is_collecting_in_band_lifetimes {
973 if !self.sess.features_untracked().in_band_lifetimes {
977 if self.in_scope_lifetimes.contains(&ident.modern()) {
981 let hir_name = ParamName::Plain(ident);
983 if self.lifetimes_to_define.iter()
984 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
988 self.lifetimes_to_define.push((ident.span, hir_name));
991 /// When we have either an elided or `'_` lifetime in an impl
992 /// header, we convert it to an in-band lifetime.
993 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
994 assert!(self.is_collecting_in_band_lifetimes);
995 let index = self.lifetimes_to_define.len();
996 let hir_name = ParamName::Fresh(index);
997 self.lifetimes_to_define.push((span, hir_name));
1001 // Evaluates `f` with the lifetimes in `params` in-scope.
1002 // This is used to track which lifetimes have already been defined, and
1003 // which are new in-band lifetimes that need to have a definition created
1005 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
1007 F: FnOnce(&mut LoweringContext<'_>) -> T,
1009 let old_len = self.in_scope_lifetimes.len();
1010 let lt_def_names = params.iter().filter_map(|param| match param.kind {
1011 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
1014 self.in_scope_lifetimes.extend(lt_def_names);
1018 self.in_scope_lifetimes.truncate(old_len);
1022 // Same as the method above, but accepts `hir::GenericParam`s
1023 // instead of `ast::GenericParam`s.
1024 // This should only be used with generics that have already had their
1025 // in-band lifetimes added. In practice, this means that this function is
1026 // only used when lowering a child item of a trait or impl.
1027 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
1028 params: &HirVec<hir::GenericParam>,
1031 F: FnOnce(&mut LoweringContext<'_>) -> T,
1033 let old_len = self.in_scope_lifetimes.len();
1034 let lt_def_names = params.iter().filter_map(|param| match param.kind {
1035 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
1038 self.in_scope_lifetimes.extend(lt_def_names);
1042 self.in_scope_lifetimes.truncate(old_len);
1046 /// Appends in-band lifetime defs and argument-position `impl
1047 /// Trait` defs to the existing set of generics.
1049 /// Presuming that in-band lifetimes are enabled, then
1050 /// `self.anonymous_lifetime_mode` will be updated to match the
1051 /// argument while `f` is running (and restored afterwards).
1052 fn add_in_band_defs<F, T>(
1054 generics: &Generics,
1056 anonymous_lifetime_mode: AnonymousLifetimeMode,
1058 ) -> (hir::Generics, T)
1060 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
1062 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
1065 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
1066 let mut params = Vec::new();
1067 // Note: it is necessary to lower generics *before* calling `f`.
1068 // When lowering `async fn`, there's a final step when lowering
1069 // the return type that assumes that all in-scope lifetimes have
1070 // already been added to either `in_scope_lifetimes` or
1071 // `lifetimes_to_define`. If we swapped the order of these two,
1072 // in-band-lifetimes introduced by generics or where-clauses
1073 // wouldn't have been added yet.
1074 let generics = this.lower_generics(
1076 ImplTraitContext::Universal(&mut params),
1078 let res = f(this, &mut params);
1079 (params, (generics, res))
1084 lowered_generics.params = lowered_generics
1088 .chain(in_band_defs)
1091 // FIXME(const_generics): the compiler doesn't always cope with
1092 // unsorted generic parameters at the moment, so we make sure
1093 // that they're ordered correctly here for now. (When we chain
1094 // the `in_band_defs`, we might make the order unsorted.)
1095 lowered_generics.params.sort_by_key(|param| {
1097 hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime,
1098 hir::GenericParamKind::Type { .. } => ParamKindOrd::Type,
1099 hir::GenericParamKind::Const { .. } => ParamKindOrd::Const,
1103 (lowered_generics, res)
1106 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
1108 F: FnOnce(&mut LoweringContext<'_>) -> T,
1110 let len = self.catch_scopes.len();
1111 self.catch_scopes.push(catch_id);
1113 let result = f(self);
1116 self.catch_scopes.len(),
1117 "catch scopes should be added and removed in stack order"
1120 self.catch_scopes.pop().unwrap();
1127 capture_clause: CaptureBy,
1128 closure_node_id: NodeId,
1129 ret_ty: Option<&Ty>,
1131 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1132 ) -> hir::ExprKind {
1133 let capture_clause = self.lower_capture_clause(capture_clause);
1134 let output = match ret_ty {
1135 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
1136 None => FunctionRetTy::Default(span),
1138 let ast_decl = FnDecl {
1143 let decl = self.lower_fn_decl(&ast_decl, None, /* impl trait allowed */ false, None);
1144 let body_id = self.lower_fn_body(&ast_decl, |this| {
1145 this.is_async_body = true;
1148 let generator = hir::Expr {
1149 hir_id: self.lower_node_id(closure_node_id),
1150 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
1151 Some(hir::GeneratorMovability::Static)),
1153 attrs: ThinVec::new(),
1156 let unstable_span = self.mark_span_with_reason(
1157 CompilerDesugaringKind::Async,
1159 Some(vec![sym::gen_future].into()),
1161 let gen_future = self.expr_std_path(
1162 unstable_span, &[sym::future, sym::from_generator], None, ThinVec::new());
1163 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
1168 f: impl FnOnce(&mut LoweringContext<'_>) -> (HirVec<hir::Arg>, hir::Expr),
1170 let prev_is_generator = mem::replace(&mut self.is_generator, false);
1171 let prev_is_async_body = mem::replace(&mut self.is_async_body, false);
1172 let (arguments, result) = f(self);
1173 let body_id = self.record_body(arguments, result);
1174 self.is_generator = prev_is_generator;
1175 self.is_async_body = prev_is_async_body;
1182 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1184 self.lower_body(|this| (
1185 decl.inputs.iter().map(|x| this.lower_arg(x)).collect(),
1190 fn lower_const_body(&mut self, expr: &Expr) -> hir::BodyId {
1191 self.lower_body(|this| (hir_vec![], this.lower_expr(expr)))
1194 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
1196 F: FnOnce(&mut LoweringContext<'_>) -> T,
1198 // We're no longer in the base loop's condition; we're in another loop.
1199 let was_in_loop_condition = self.is_in_loop_condition;
1200 self.is_in_loop_condition = false;
1202 let len = self.loop_scopes.len();
1203 self.loop_scopes.push(loop_id);
1205 let result = f(self);
1208 self.loop_scopes.len(),
1209 "loop scopes should be added and removed in stack order"
1212 self.loop_scopes.pop().unwrap();
1214 self.is_in_loop_condition = was_in_loop_condition;
1219 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
1221 F: FnOnce(&mut LoweringContext<'_>) -> T,
1223 let was_in_loop_condition = self.is_in_loop_condition;
1224 self.is_in_loop_condition = true;
1226 let result = f(self);
1228 self.is_in_loop_condition = was_in_loop_condition;
1233 fn with_new_scopes<T, F>(&mut self, f: F) -> T
1235 F: FnOnce(&mut LoweringContext<'_>) -> T,
1237 let was_in_loop_condition = self.is_in_loop_condition;
1238 self.is_in_loop_condition = false;
1240 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
1241 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
1243 self.catch_scopes = catch_scopes;
1244 self.loop_scopes = loop_scopes;
1246 self.is_in_loop_condition = was_in_loop_condition;
1251 fn def_key(&mut self, id: DefId) -> DefKey {
1253 self.resolver.definitions().def_key(id.index)
1255 self.cstore.def_key(id)
1259 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1260 label.map(|label| hir::Label {
1265 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1266 let target_id = match destination {
1268 if let Some(loop_id) = self.resolver.get_label_res(id) {
1269 Ok(self.lower_node_id(loop_id))
1271 Err(hir::LoopIdError::UnresolvedLabel)
1278 .map(|id| Ok(self.lower_node_id(id)))
1279 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1284 label: self.lower_label(destination.map(|(_, label)| label)),
1289 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1292 .map(|a| self.lower_attr(a))
1296 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1297 // Note that we explicitly do not walk the path. Since we don't really
1298 // lower attributes (we use the AST version) there is nowhere to keep
1299 // the `HirId`s. We don't actually need HIR version of attributes anyway.
1303 path: attr.path.clone(),
1304 tokens: self.lower_token_stream(attr.tokens.clone()),
1305 is_sugared_doc: attr.is_sugared_doc,
1310 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1313 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1317 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1319 TokenTree::Token(span, token) => self.lower_token(token, span),
1320 TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1323 self.lower_token_stream(tts),
1328 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1330 Token::Interpolated(nt) => {
1331 let tts = nt.to_tokenstream(&self.sess.parse_sess, span);
1332 self.lower_token_stream(tts)
1334 other => TokenTree::Token(span, other).into(),
1338 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1340 hir_id: self.next_id(),
1341 attrs: self.lower_attrs(&arm.attrs),
1342 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1343 guard: match arm.guard {
1344 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1347 body: P(self.lower_expr(&arm.body)),
1352 fn lower_assoc_ty_constraint(&mut self,
1353 c: &AssocTyConstraint,
1354 itctx: ImplTraitContext<'_>)
1355 -> hir::TypeBinding {
1356 let ty = match c.kind {
1357 AssocTyConstraintKind::Equality { ref ty } => self.lower_ty(ty, itctx),
1358 AssocTyConstraintKind::Bound { ref bounds } => {
1359 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`.
1360 let impl_ty_node_id = self.sess.next_node_id();
1361 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
1362 self.resolver.definitions().create_def_with_parent(
1366 DefIndexAddressSpace::High,
1370 id: self.sess.next_node_id(),
1371 node: TyKind::ImplTrait(impl_ty_node_id, bounds.clone()),
1378 hir_id: self.lower_node_id(c.id),
1385 fn lower_generic_arg(&mut self,
1386 arg: &ast::GenericArg,
1387 itctx: ImplTraitContext<'_>)
1388 -> hir::GenericArg {
1390 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1391 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1392 ast::GenericArg::Const(ct) => {
1393 GenericArg::Const(ConstArg {
1394 value: self.lower_anon_const(&ct),
1395 span: ct.value.span,
1401 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1402 P(self.lower_ty_direct(t, itctx))
1405 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1406 let kind = match t.node {
1407 TyKind::Infer => hir::TyKind::Infer,
1408 TyKind::Err => hir::TyKind::Err,
1409 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1410 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1411 TyKind::Rptr(ref region, ref mt) => {
1412 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1413 let lifetime = match *region {
1414 Some(ref lt) => self.lower_lifetime(lt),
1415 None => self.elided_ref_lifetime(span),
1417 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1419 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1422 this.with_anonymous_lifetime_mode(
1423 AnonymousLifetimeMode::PassThrough,
1425 hir::TyKind::BareFn(P(hir::BareFnTy {
1426 generic_params: this.lower_generic_params(
1428 &NodeMap::default(),
1429 ImplTraitContext::disallowed(),
1431 unsafety: this.lower_unsafety(f.unsafety),
1433 decl: this.lower_fn_decl(&f.decl, None, false, None),
1434 arg_names: this.lower_fn_args_to_names(&f.decl),
1440 TyKind::Never => hir::TyKind::Never,
1441 TyKind::Tup(ref tys) => {
1442 hir::TyKind::Tup(tys.iter().map(|ty| {
1443 self.lower_ty_direct(ty, itctx.reborrow())
1446 TyKind::Paren(ref ty) => {
1447 return self.lower_ty_direct(ty, itctx);
1449 TyKind::Path(ref qself, ref path) => {
1450 let id = self.lower_node_id(t.id);
1451 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1452 let ty = self.ty_path(id, t.span, qpath);
1453 if let hir::TyKind::TraitObject(..) = ty.node {
1454 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1458 TyKind::ImplicitSelf => {
1459 let res = self.expect_full_res(t.id);
1460 let res = self.lower_res(res);
1461 hir::TyKind::Path(hir::QPath::Resolved(
1465 segments: hir_vec![hir::PathSegment::from_ident(
1466 Ident::with_empty_ctxt(kw::SelfUpper)
1472 TyKind::Array(ref ty, ref length) => {
1473 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1475 TyKind::Typeof(ref expr) => {
1476 hir::TyKind::Typeof(self.lower_anon_const(expr))
1478 TyKind::TraitObject(ref bounds, kind) => {
1479 let mut lifetime_bound = None;
1482 .filter_map(|bound| match *bound {
1483 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1484 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1486 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1487 GenericBound::Outlives(ref lifetime) => {
1488 if lifetime_bound.is_none() {
1489 lifetime_bound = Some(self.lower_lifetime(lifetime));
1495 let lifetime_bound =
1496 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1497 if kind != TraitObjectSyntax::Dyn {
1498 self.maybe_lint_bare_trait(t.span, t.id, false);
1500 hir::TyKind::TraitObject(bounds, lifetime_bound)
1502 TyKind::ImplTrait(def_node_id, ref bounds) => {
1505 ImplTraitContext::Existential(fn_def_id) => {
1506 self.lower_existential_impl_trait(
1507 span, fn_def_id, def_node_id,
1508 |this| this.lower_param_bounds(bounds, itctx),
1511 ImplTraitContext::Universal(in_band_ty_params) => {
1512 // Add a definition for the in-band `Param`.
1513 let def_index = self
1516 .opt_def_index(def_node_id)
1519 let hir_bounds = self.lower_param_bounds(
1521 ImplTraitContext::Universal(in_band_ty_params),
1523 // Set the name to `impl Bound1 + Bound2`.
1524 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1525 in_band_ty_params.push(hir::GenericParam {
1526 hir_id: self.lower_node_id(def_node_id),
1527 name: ParamName::Plain(ident),
1528 pure_wrt_drop: false,
1532 kind: hir::GenericParamKind::Type {
1534 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1538 hir::TyKind::Path(hir::QPath::Resolved(
1542 res: Res::Def(DefKind::TyParam, DefId::local(def_index)),
1543 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1547 ImplTraitContext::AssociatedTy => {
1548 let hir_bounds = self.lower_param_bounds(
1550 ImplTraitContext::AssociatedTy,
1553 hir::TyKind::AssocTyExistential(
1557 ImplTraitContext::Disallowed(pos) => {
1558 let allowed_in = if self.sess.features_untracked()
1559 .impl_trait_in_bindings {
1560 "bindings or function and inherent method return types"
1562 "function and inherent method return types"
1564 let mut err = struct_span_err!(
1568 "`impl Trait` not allowed outside of {}",
1571 if pos == ImplTraitPosition::Binding &&
1572 nightly_options::is_nightly_build() {
1574 "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1582 TyKind::Mac(_) => bug!("`TyMac` should have been expanded by now."),
1583 TyKind::CVarArgs => {
1584 // Create the implicit lifetime of the "spoofed" `VaList`.
1585 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1586 let lt = self.new_implicit_lifetime(span);
1587 hir::TyKind::CVarArgs(lt)
1594 hir_id: self.lower_node_id(t.id),
1598 fn lower_existential_impl_trait(
1601 fn_def_id: Option<DefId>,
1602 exist_ty_node_id: NodeId,
1603 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1605 // Make sure we know that some funky desugaring has been going on here.
1606 // This is a first: there is code in other places like for loop
1607 // desugaring that explicitly states that we don't want to track that.
1608 // Not tracking it makes lints in rustc and clippy very fragile, as
1609 // frequently opened issues show.
1610 let exist_ty_span = self.mark_span_with_reason(
1611 CompilerDesugaringKind::ExistentialReturnType,
1616 let exist_ty_def_index = self
1619 .opt_def_index(exist_ty_node_id)
1622 self.allocate_hir_id_counter(exist_ty_node_id);
1624 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1626 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1632 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1633 let exist_ty_item = hir::ExistTy {
1634 generics: hir::Generics {
1635 params: lifetime_defs,
1636 where_clause: hir::WhereClause {
1637 hir_id: lctx.next_id(),
1638 predicates: hir_vec![],
1643 impl_trait_fn: fn_def_id,
1644 origin: hir::ExistTyOrigin::ReturnImplTrait,
1647 trace!("exist ty from impl trait def-index: {:#?}", exist_ty_def_index);
1648 let exist_ty_id = lctx.generate_existential_type(
1655 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1656 hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, lifetimes)
1660 /// Registers a new existential type with the proper `NodeId`s and
1661 /// returns the lowered node-ID for the existential type.
1662 fn generate_existential_type(
1664 exist_ty_node_id: NodeId,
1665 exist_ty_item: hir::ExistTy,
1667 exist_ty_span: Span,
1669 let exist_ty_item_kind = hir::ItemKind::Existential(exist_ty_item);
1670 let exist_ty_id = self.lower_node_id(exist_ty_node_id);
1671 // Generate an `existential type Foo: Trait;` declaration.
1672 trace!("registering existential type with id {:#?}", exist_ty_id);
1673 let exist_ty_item = hir::Item {
1674 hir_id: exist_ty_id,
1675 ident: Ident::invalid(),
1676 attrs: Default::default(),
1677 node: exist_ty_item_kind,
1678 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1679 span: exist_ty_span,
1682 // Insert the item into the global item list. This usually happens
1683 // automatically for all AST items. But this existential type item
1684 // does not actually exist in the AST.
1685 self.insert_item(exist_ty_item);
1689 fn lifetimes_from_impl_trait_bounds(
1691 exist_ty_id: NodeId,
1692 parent_index: DefIndex,
1693 bounds: &hir::GenericBounds,
1694 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1695 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1696 // appear in the bounds, excluding lifetimes that are created within the bounds.
1697 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1698 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1699 context: &'r mut LoweringContext<'a>,
1701 exist_ty_id: NodeId,
1702 collect_elided_lifetimes: bool,
1703 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1704 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1705 output_lifetimes: Vec<hir::GenericArg>,
1706 output_lifetime_params: Vec<hir::GenericParam>,
1709 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1710 fn nested_visit_map<'this>(
1712 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1713 hir::intravisit::NestedVisitorMap::None
1716 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1717 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1718 if parameters.parenthesized {
1719 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1720 self.collect_elided_lifetimes = false;
1721 hir::intravisit::walk_generic_args(self, span, parameters);
1722 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1724 hir::intravisit::walk_generic_args(self, span, parameters);
1728 fn visit_ty(&mut self, t: &'v hir::Ty) {
1729 // Don't collect elided lifetimes used inside of `fn()` syntax.
1730 if let hir::TyKind::BareFn(_) = t.node {
1731 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1732 self.collect_elided_lifetimes = false;
1734 // Record the "stack height" of `for<'a>` lifetime bindings
1735 // to be able to later fully undo their introduction.
1736 let old_len = self.currently_bound_lifetimes.len();
1737 hir::intravisit::walk_ty(self, t);
1738 self.currently_bound_lifetimes.truncate(old_len);
1740 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1742 hir::intravisit::walk_ty(self, t)
1746 fn visit_poly_trait_ref(
1748 trait_ref: &'v hir::PolyTraitRef,
1749 modifier: hir::TraitBoundModifier,
1751 // Record the "stack height" of `for<'a>` lifetime bindings
1752 // to be able to later fully undo their introduction.
1753 let old_len = self.currently_bound_lifetimes.len();
1754 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1755 self.currently_bound_lifetimes.truncate(old_len);
1758 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1759 // Record the introduction of 'a in `for<'a> ...`.
1760 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1761 // Introduce lifetimes one at a time so that we can handle
1762 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1763 let lt_name = hir::LifetimeName::Param(param.name);
1764 self.currently_bound_lifetimes.push(lt_name);
1767 hir::intravisit::walk_generic_param(self, param);
1770 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1771 let name = match lifetime.name {
1772 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1773 if self.collect_elided_lifetimes {
1774 // Use `'_` for both implicit and underscore lifetimes in
1775 // `abstract type Foo<'_>: SomeTrait<'_>;`.
1776 hir::LifetimeName::Underscore
1781 hir::LifetimeName::Param(_) => lifetime.name,
1782 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1785 if !self.currently_bound_lifetimes.contains(&name)
1786 && !self.already_defined_lifetimes.contains(&name) {
1787 self.already_defined_lifetimes.insert(name);
1789 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1790 hir_id: self.context.next_id(),
1791 span: lifetime.span,
1795 let def_node_id = self.context.sess.next_node_id();
1797 self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1798 self.context.resolver.definitions().create_def_with_parent(
1801 DefPathData::LifetimeNs(name.ident().as_interned_str()),
1805 let (name, kind) = match name {
1806 hir::LifetimeName::Underscore => (
1807 hir::ParamName::Plain(Ident::with_empty_ctxt(kw::UnderscoreLifetime)),
1808 hir::LifetimeParamKind::Elided,
1810 hir::LifetimeName::Param(param_name) => (
1812 hir::LifetimeParamKind::Explicit,
1814 _ => bug!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1817 self.output_lifetime_params.push(hir::GenericParam {
1820 span: lifetime.span,
1821 pure_wrt_drop: false,
1824 kind: hir::GenericParamKind::Lifetime { kind }
1830 let mut lifetime_collector = ImplTraitLifetimeCollector {
1832 parent: parent_index,
1834 collect_elided_lifetimes: true,
1835 currently_bound_lifetimes: Vec::new(),
1836 already_defined_lifetimes: FxHashSet::default(),
1837 output_lifetimes: Vec::new(),
1838 output_lifetime_params: Vec::new(),
1841 for bound in bounds {
1842 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1846 lifetime_collector.output_lifetimes.into(),
1847 lifetime_collector.output_lifetime_params.into(),
1851 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1856 .map(|x| self.lower_foreign_item(x))
1861 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1868 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1870 node: hir::VariantKind {
1871 ident: v.node.ident,
1872 id: self.lower_node_id(v.node.id),
1873 attrs: self.lower_attrs(&v.node.attrs),
1874 data: self.lower_variant_data(&v.node.data),
1875 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1884 qself: &Option<QSelf>,
1886 param_mode: ParamMode,
1887 mut itctx: ImplTraitContext<'_>,
1889 let qself_position = qself.as_ref().map(|q| q.position);
1890 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1892 let partial_res = self.resolver
1893 .get_partial_res(id)
1894 .unwrap_or_else(|| PartialRes::new(Res::Err));
1896 let proj_start = p.segments.len() - partial_res.unresolved_segments();
1897 let path = P(hir::Path {
1898 res: self.lower_res(partial_res.base_res()),
1899 segments: p.segments[..proj_start]
1902 .map(|(i, segment)| {
1903 let param_mode = match (qself_position, param_mode) {
1904 (Some(j), ParamMode::Optional) if i < j => {
1905 // This segment is part of the trait path in a
1906 // qualified path - one of `a`, `b` or `Trait`
1907 // in `<X as a::b::Trait>::T::U::method`.
1913 // Figure out if this is a type/trait segment,
1914 // which may need lifetime elision performed.
1915 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1916 krate: def_id.krate,
1917 index: this.def_key(def_id).parent.expect("missing parent"),
1919 let type_def_id = match partial_res.base_res() {
1920 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
1921 Some(parent_def_id(self, def_id))
1923 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
1924 Some(parent_def_id(self, def_id))
1926 Res::Def(DefKind::Struct, def_id)
1927 | Res::Def(DefKind::Union, def_id)
1928 | Res::Def(DefKind::Enum, def_id)
1929 | Res::Def(DefKind::TyAlias, def_id)
1930 | Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start =>
1936 let parenthesized_generic_args = match partial_res.base_res() {
1937 // `a::b::Trait(Args)`
1938 Res::Def(DefKind::Trait, _)
1939 if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1940 // `a::b::Trait(Args)::TraitItem`
1941 Res::Def(DefKind::Method, _)
1942 | Res::Def(DefKind::AssocConst, _)
1943 | Res::Def(DefKind::AssocTy, _)
1944 if i + 2 == proj_start =>
1946 ParenthesizedGenericArgs::Ok
1948 // Avoid duplicated errors.
1949 Res::Err => ParenthesizedGenericArgs::Ok,
1951 Res::Def(DefKind::Struct, _)
1952 | Res::Def(DefKind::Enum, _)
1953 | Res::Def(DefKind::Union, _)
1954 | Res::Def(DefKind::TyAlias, _)
1955 | Res::Def(DefKind::Variant, _) if i + 1 == proj_start =>
1957 ParenthesizedGenericArgs::Err
1959 // A warning for now, for compatibility reasons.
1960 _ => ParenthesizedGenericArgs::Warn,
1963 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1964 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1967 assert!(!def_id.is_local());
1969 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1970 let n = item_generics.own_counts().lifetimes;
1971 self.type_def_lifetime_params.insert(def_id, n);
1974 self.lower_path_segment(
1979 parenthesized_generic_args,
1988 // Simple case, either no projections, or only fully-qualified.
1989 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
1990 if partial_res.unresolved_segments() == 0 {
1991 return hir::QPath::Resolved(qself, path);
1994 // Create the innermost type that we're projecting from.
1995 let mut ty = if path.segments.is_empty() {
1996 // If the base path is empty that means there exists a
1997 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
1998 qself.expect("missing QSelf for <T>::...")
2000 // Otherwise, the base path is an implicit `Self` type path,
2001 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
2002 // `<I as Iterator>::Item::default`.
2003 let new_id = self.next_id();
2004 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
2007 // Anything after the base path are associated "extensions",
2008 // out of which all but the last one are associated types,
2009 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
2010 // * base path is `std::vec::Vec<T>`
2011 // * "extensions" are `IntoIter`, `Item` and `clone`
2012 // * type nodes are:
2013 // 1. `std::vec::Vec<T>` (created above)
2014 // 2. `<std::vec::Vec<T>>::IntoIter`
2015 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
2016 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
2017 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
2018 let segment = P(self.lower_path_segment(
2023 ParenthesizedGenericArgs::Warn,
2027 let qpath = hir::QPath::TypeRelative(ty, segment);
2029 // It's finished, return the extension of the right node type.
2030 if i == p.segments.len() - 1 {
2034 // Wrap the associated extension in another type node.
2035 let new_id = self.next_id();
2036 ty = P(self.ty_path(new_id, p.span, qpath));
2039 // We should've returned in the for loop above.
2042 "lower_qpath: no final extension segment in {}..{}",
2048 fn lower_path_extra(
2052 param_mode: ParamMode,
2053 explicit_owner: Option<NodeId>,
2057 segments: p.segments
2060 self.lower_path_segment(
2065 ParenthesizedGenericArgs::Err,
2066 ImplTraitContext::disallowed(),
2075 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
2076 let res = self.expect_full_res(id);
2077 let res = self.lower_res(res);
2078 self.lower_path_extra(res, p, param_mode, None)
2081 fn lower_path_segment(
2084 segment: &PathSegment,
2085 param_mode: ParamMode,
2086 expected_lifetimes: usize,
2087 parenthesized_generic_args: ParenthesizedGenericArgs,
2088 itctx: ImplTraitContext<'_>,
2089 explicit_owner: Option<NodeId>,
2090 ) -> hir::PathSegment {
2091 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
2092 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
2093 match **generic_args {
2094 GenericArgs::AngleBracketed(ref data) => {
2095 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
2097 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
2098 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
2099 ParenthesizedGenericArgs::Warn => {
2100 self.sess.buffer_lint(
2101 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
2106 (hir::GenericArgs::none(), true)
2108 ParenthesizedGenericArgs::Err => {
2109 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
2110 err.span_label(data.span, "only `Fn` traits may use parentheses");
2111 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
2112 // Do not suggest going from `Trait()` to `Trait<>`
2113 if data.inputs.len() > 0 {
2114 err.span_suggestion(
2116 "use angle brackets instead",
2117 format!("<{}>", &snippet[1..snippet.len() - 1]),
2118 Applicability::MaybeIncorrect,
2124 self.lower_angle_bracketed_parameter_data(
2125 &data.as_angle_bracketed_args(),
2135 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
2138 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
2139 GenericArg::Lifetime(_) => true,
2142 let first_generic_span = generic_args.args.iter().map(|a| a.span())
2143 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
2144 if !generic_args.parenthesized && !has_lifetimes {
2146 self.elided_path_lifetimes(path_span, expected_lifetimes)
2148 .map(|lt| GenericArg::Lifetime(lt))
2149 .chain(generic_args.args.into_iter())
2151 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
2152 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
2153 let no_ty_args = generic_args.args.len() == expected_lifetimes;
2154 let no_bindings = generic_args.bindings.is_empty();
2155 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
2156 // If there are no (non-implicit) generic args or associated type
2157 // bindings, our suggestion includes the angle brackets.
2158 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
2160 // Otherwise (sorry, this is kind of gross) we need to infer the
2161 // place to splice in the `'_, ` from the generics that do exist.
2162 let first_generic_span = first_generic_span
2163 .expect("already checked that type args or bindings exist");
2164 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
2166 match self.anonymous_lifetime_mode {
2167 // In create-parameter mode we error here because we don't want to support
2168 // deprecated impl elision in new features like impl elision and `async fn`,
2169 // both of which work using the `CreateParameter` mode:
2171 // impl Foo for std::cell::Ref<u32> // note lack of '_
2172 // async fn foo(_: std::cell::Ref<u32>) { ... }
2173 AnonymousLifetimeMode::CreateParameter => {
2174 let mut err = struct_span_err!(
2178 "implicit elided lifetime not allowed here"
2180 crate::lint::builtin::add_elided_lifetime_in_path_suggestion(
2191 AnonymousLifetimeMode::PassThrough |
2192 AnonymousLifetimeMode::ReportError |
2193 AnonymousLifetimeMode::Replace(_) => {
2194 self.sess.buffer_lint_with_diagnostic(
2195 ELIDED_LIFETIMES_IN_PATHS,
2198 "hidden lifetime parameters in types are deprecated",
2199 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
2212 let res = self.expect_full_res(segment.id);
2213 let id = if let Some(owner) = explicit_owner {
2214 self.lower_node_id_with_owner(segment.id, owner)
2216 self.lower_node_id(segment.id)
2219 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
2220 segment.ident, segment.id, id,
2223 hir::PathSegment::new(
2226 Some(self.lower_res(res)),
2232 fn lower_angle_bracketed_parameter_data(
2234 data: &AngleBracketedArgs,
2235 param_mode: ParamMode,
2236 mut itctx: ImplTraitContext<'_>,
2237 ) -> (hir::GenericArgs, bool) {
2238 let &AngleBracketedArgs { ref args, ref constraints, .. } = data;
2239 let has_types = args.iter().any(|arg| match arg {
2240 ast::GenericArg::Type(_) => true,
2245 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
2246 bindings: constraints.iter()
2247 .map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow()))
2249 parenthesized: false,
2251 !has_types && param_mode == ParamMode::Optional
2255 fn lower_parenthesized_parameter_data(
2257 data: &ParenthesizedArgs,
2258 ) -> (hir::GenericArgs, bool) {
2259 // Switch to `PassThrough` mode for anonymous lifetimes; this
2260 // means that we permit things like `&Ref<T>`, where `Ref` has
2261 // a hidden lifetime parameter. This is needed for backwards
2262 // compatibility, even in contexts like an impl header where
2263 // we generally don't permit such things (see #51008).
2264 self.with_anonymous_lifetime_mode(
2265 AnonymousLifetimeMode::PassThrough,
2267 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2270 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
2272 let mk_tup = |this: &mut Self, tys, span| {
2273 hir::Ty { node: hir::TyKind::Tup(tys), hir_id: this.next_id(), span }
2277 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
2280 hir_id: this.next_id(),
2281 ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
2284 .map(|ty| this.lower_ty(&ty, ImplTraitContext::disallowed()))
2285 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
2286 span: output.as_ref().map_or(span, |ty| ty.span),
2289 parenthesized: true,
2297 fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) {
2298 let mut ids = SmallVec::<[NodeId; 1]>::new();
2299 if self.sess.features_untracked().impl_trait_in_bindings {
2300 if let Some(ref ty) = l.ty {
2301 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2302 visitor.visit_ty(ty);
2305 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2307 hir_id: self.lower_node_id(l.id),
2310 .map(|t| self.lower_ty(t,
2311 if self.sess.features_untracked().impl_trait_in_bindings {
2312 ImplTraitContext::Existential(Some(parent_def_id))
2314 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2317 pat: self.lower_pat(&l.pat),
2318 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2320 attrs: l.attrs.clone(),
2321 source: hir::LocalSource::Normal,
2325 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
2327 Mutability::Mutable => hir::MutMutable,
2328 Mutability::Immutable => hir::MutImmutable,
2332 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
2334 hir_id: self.lower_node_id(arg.id),
2335 pat: self.lower_pat(&arg.pat),
2339 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2342 .map(|arg| match arg.pat.node {
2343 PatKind::Ident(_, ident, _) => ident,
2344 _ => Ident::new(kw::Invalid, arg.pat.span),
2349 // Lowers a function declaration.
2351 // `decl`: the unlowered (AST) function declaration.
2352 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
2353 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2354 // `make_ret_async` is also `Some`.
2355 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
2356 // This guards against trait declarations and implementations where `impl Trait` is
2358 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2359 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
2360 // return type `impl Trait` item.
2364 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2365 impl_trait_return_allow: bool,
2366 make_ret_async: Option<NodeId>,
2367 ) -> P<hir::FnDecl> {
2368 let lt_mode = if make_ret_async.is_some() {
2369 // In `async fn`, argument-position elided lifetimes
2370 // must be transformed into fresh generic parameters so that
2371 // they can be applied to the existential return type.
2372 AnonymousLifetimeMode::CreateParameter
2374 self.anonymous_lifetime_mode
2377 // Remember how many lifetimes were already around so that we can
2378 // only look at the lifetime parameters introduced by the arguments.
2379 let lifetime_count_before_args = self.lifetimes_to_define.len();
2380 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2384 if let Some((_, ibty)) = &mut in_band_ty_params {
2385 this.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2387 this.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2390 .collect::<HirVec<_>>()
2393 let output = if let Some(ret_id) = make_ret_async {
2394 // Calculate the `LtReplacement` to use for any return-position elided
2395 // lifetimes based on the elided lifetime parameters introduced in the args.
2396 let lt_replacement = get_elided_lt_replacement(
2397 &self.lifetimes_to_define[lifetime_count_before_args..]
2399 self.lower_async_fn_ret_ty(
2401 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
2407 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2408 Some((def_id, _)) if impl_trait_return_allow => {
2409 hir::Return(self.lower_ty(ty,
2410 ImplTraitContext::Existential(Some(def_id))))
2413 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2416 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2423 c_variadic: decl.c_variadic,
2424 implicit_self: decl.inputs.get(0).map_or(
2425 hir::ImplicitSelfKind::None,
2427 let is_mutable_pat = match arg.pat.node {
2428 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2429 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2430 mt == Mutability::Mutable,
2435 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2436 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2437 // Given we are only considering `ImplicitSelf` types, we needn't consider
2438 // the case where we have a mutable pattern to a reference as that would
2439 // no longer be an `ImplicitSelf`.
2440 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2441 mt.mutbl == ast::Mutability::Mutable =>
2442 hir::ImplicitSelfKind::MutRef,
2443 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2444 hir::ImplicitSelfKind::ImmRef,
2445 _ => hir::ImplicitSelfKind::None,
2452 // Transforms `-> T` for `async fn` into `-> ExistTy { .. }`
2453 // combined with the following definition of `ExistTy`:
2455 // existential type ExistTy<generics_from_parent_fn>: Future<Output = T>;
2457 // `inputs`: lowered types of arguments to the function (used to collect lifetimes)
2458 // `output`: unlowered output type (`T` in `-> T`)
2459 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
2460 // `exist_ty_node_id`: `NodeId` of the existential type that should be created
2461 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
2462 fn lower_async_fn_ret_ty(
2464 output: &FunctionRetTy,
2466 exist_ty_node_id: NodeId,
2467 elided_lt_replacement: LtReplacement,
2468 ) -> hir::FunctionRetTy {
2469 let span = output.span();
2471 let exist_ty_span = self.mark_span_with_reason(
2472 CompilerDesugaringKind::Async,
2477 let exist_ty_def_index = self
2480 .opt_def_index(exist_ty_node_id)
2483 self.allocate_hir_id_counter(exist_ty_node_id);
2485 let (exist_ty_id, lifetime_params) = self.with_hir_id_owner(exist_ty_node_id, |this| {
2486 let future_bound = this.with_anonymous_lifetime_mode(
2487 AnonymousLifetimeMode::Replace(elided_lt_replacement),
2488 |this| this.lower_async_fn_output_type_to_future_bound(
2495 // Calculate all the lifetimes that should be captured
2496 // by the existential type. This should include all in-scope
2497 // lifetime parameters, including those defined in-band.
2499 // Note: this must be done after lowering the output type,
2500 // as the output type may introduce new in-band lifetimes.
2501 let lifetime_params: Vec<(Span, ParamName)> =
2502 this.in_scope_lifetimes
2504 .map(|ident| (ident.span, ParamName::Plain(ident)))
2505 .chain(this.lifetimes_to_define.iter().cloned())
2508 let generic_params =
2511 .map(|(span, hir_name)| {
2512 this.lifetime_to_generic_param(span, hir_name, exist_ty_def_index)
2516 let exist_ty_item = hir::ExistTy {
2517 generics: hir::Generics {
2518 params: generic_params,
2519 where_clause: hir::WhereClause {
2520 hir_id: this.next_id(),
2521 predicates: hir_vec![],
2525 bounds: hir_vec![future_bound],
2526 impl_trait_fn: Some(fn_def_id),
2527 origin: hir::ExistTyOrigin::AsyncFn,
2530 trace!("exist ty from async fn def index: {:#?}", exist_ty_def_index);
2531 let exist_ty_id = this.generate_existential_type(
2538 (exist_ty_id, lifetime_params)
2544 .map(|(span, hir_name)| {
2545 GenericArg::Lifetime(hir::Lifetime {
2546 hir_id: self.next_id(),
2548 name: hir::LifetimeName::Param(hir_name),
2553 let exist_ty_ref = hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, generic_args);
2555 hir::FunctionRetTy::Return(P(hir::Ty {
2558 hir_id: self.next_id(),
2562 /// Transforms `-> T` into `Future<Output = T>`
2563 fn lower_async_fn_output_type_to_future_bound(
2565 output: &FunctionRetTy,
2568 ) -> hir::GenericBound {
2569 // Compute the `T` in `Future<Output = T>` from the return type.
2570 let output_ty = match output {
2571 FunctionRetTy::Ty(ty) => {
2572 self.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2574 FunctionRetTy::Default(ret_ty_span) => {
2576 hir_id: self.next_id(),
2577 node: hir::TyKind::Tup(hir_vec![]),
2584 let future_params = P(hir::GenericArgs {
2586 bindings: hir_vec![hir::TypeBinding {
2587 ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
2589 hir_id: self.next_id(),
2592 parenthesized: false,
2595 // ::std::future::Future<future_params>
2597 self.std_path(span, &[sym::future, sym::Future], Some(future_params), false);
2599 hir::GenericBound::Trait(
2601 trait_ref: hir::TraitRef {
2603 hir_ref_id: self.next_id(),
2605 bound_generic_params: hir_vec![],
2608 hir::TraitBoundModifier::None,
2612 fn lower_param_bound(
2615 itctx: ImplTraitContext<'_>,
2616 ) -> hir::GenericBound {
2618 GenericBound::Trait(ref ty, modifier) => {
2619 hir::GenericBound::Trait(
2620 self.lower_poly_trait_ref(ty, itctx),
2621 self.lower_trait_bound_modifier(modifier),
2624 GenericBound::Outlives(ref lifetime) => {
2625 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2630 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2631 let span = l.ident.span;
2633 ident if ident.name == kw::StaticLifetime =>
2634 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2635 ident if ident.name == kw::UnderscoreLifetime =>
2636 match self.anonymous_lifetime_mode {
2637 AnonymousLifetimeMode::CreateParameter => {
2638 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2639 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2642 AnonymousLifetimeMode::PassThrough => {
2643 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2646 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2648 AnonymousLifetimeMode::Replace(replacement) => {
2649 let hir_id = self.lower_node_id(l.id);
2650 self.replace_elided_lifetime(hir_id, span, replacement)
2654 self.maybe_collect_in_band_lifetime(ident);
2655 let param_name = ParamName::Plain(ident);
2656 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2661 fn new_named_lifetime(
2665 name: hir::LifetimeName,
2666 ) -> hir::Lifetime {
2668 hir_id: self.lower_node_id(id),
2674 /// Replace a return-position elided lifetime with the elided lifetime
2675 /// from the arguments.
2676 fn replace_elided_lifetime(
2680 replacement: LtReplacement,
2681 ) -> hir::Lifetime {
2682 let multiple_or_none = match replacement {
2683 LtReplacement::Some(name) => {
2684 return hir::Lifetime {
2687 name: hir::LifetimeName::Param(name),
2690 LtReplacement::MultipleLifetimes => "multiple",
2691 LtReplacement::NoLifetimes => "none",
2694 let mut err = crate::middle::resolve_lifetime::report_missing_lifetime_specifiers(
2700 "return-position elided lifetimes require exactly one \
2701 input-position elided lifetime, found {}.", multiple_or_none));
2704 hir::Lifetime { hir_id, span, name: hir::LifetimeName::Error }
2707 fn lower_generic_params(
2709 params: &[GenericParam],
2710 add_bounds: &NodeMap<Vec<GenericBound>>,
2711 mut itctx: ImplTraitContext<'_>,
2712 ) -> hir::HirVec<hir::GenericParam> {
2713 params.iter().map(|param| {
2714 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2718 fn lower_generic_param(&mut self,
2719 param: &GenericParam,
2720 add_bounds: &NodeMap<Vec<GenericBound>>,
2721 mut itctx: ImplTraitContext<'_>)
2722 -> hir::GenericParam {
2723 let mut bounds = self.with_anonymous_lifetime_mode(
2724 AnonymousLifetimeMode::ReportError,
2725 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2728 let (name, kind) = match param.kind {
2729 GenericParamKind::Lifetime => {
2730 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2731 self.is_collecting_in_band_lifetimes = false;
2733 let lt = self.with_anonymous_lifetime_mode(
2734 AnonymousLifetimeMode::ReportError,
2735 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2737 let param_name = match lt.name {
2738 hir::LifetimeName::Param(param_name) => param_name,
2739 hir::LifetimeName::Implicit
2740 | hir::LifetimeName::Underscore
2741 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2742 hir::LifetimeName::Error => ParamName::Error,
2745 let kind = hir::GenericParamKind::Lifetime {
2746 kind: hir::LifetimeParamKind::Explicit
2749 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2753 GenericParamKind::Type { ref default, .. } => {
2754 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2755 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2756 // Instead, use `gensym("Self")` to create a distinct name that looks the same.
2757 let ident = if param.ident.name == kw::SelfUpper {
2758 param.ident.gensym()
2763 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2764 if !add_bounds.is_empty() {
2765 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2766 bounds = bounds.into_iter()
2771 let kind = hir::GenericParamKind::Type {
2772 default: default.as_ref().map(|x| {
2773 self.lower_ty(x, ImplTraitContext::disallowed())
2775 synthetic: param.attrs.iter()
2776 .filter(|attr| attr.check_name(sym::rustc_synthetic))
2777 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2781 (hir::ParamName::Plain(ident), kind)
2783 GenericParamKind::Const { ref ty } => {
2784 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const {
2785 ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2791 hir_id: self.lower_node_id(param.id),
2793 span: param.ident.span,
2794 pure_wrt_drop: attr::contains_name(¶m.attrs, sym::may_dangle),
2795 attrs: self.lower_attrs(¶m.attrs),
2803 generics: &Generics,
2804 itctx: ImplTraitContext<'_>)
2807 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2808 // FIXME: this could probably be done with less rightward drift. It also looks like two
2809 // control paths where `report_error` is called are the only paths that advance to after the
2810 // match statement, so the error reporting could probably just be moved there.
2811 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
2812 for pred in &generics.where_clause.predicates {
2813 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2814 'next_bound: for bound in &bound_pred.bounds {
2815 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2816 let report_error = |this: &mut Self| {
2817 this.diagnostic().span_err(
2818 bound_pred.bounded_ty.span,
2819 "`?Trait` bounds are only permitted at the \
2820 point where a type parameter is declared",
2823 // Check if the where clause type is a plain type parameter.
2824 match bound_pred.bounded_ty.node {
2825 TyKind::Path(None, ref path)
2826 if path.segments.len() == 1
2827 && bound_pred.bound_generic_params.is_empty() =>
2829 if let Some(Res::Def(DefKind::TyParam, def_id)) = self.resolver
2830 .get_partial_res(bound_pred.bounded_ty.id)
2831 .map(|d| d.base_res())
2833 if let Some(node_id) =
2834 self.resolver.definitions().as_local_node_id(def_id)
2836 for param in &generics.params {
2838 GenericParamKind::Type { .. } => {
2839 if node_id == param.id {
2840 add_bounds.entry(param.id)
2842 .push(bound.clone());
2843 continue 'next_bound;
2853 _ => report_error(self),
2861 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2862 where_clause: self.lower_where_clause(&generics.where_clause),
2863 span: generics.span,
2867 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2868 self.with_anonymous_lifetime_mode(
2869 AnonymousLifetimeMode::ReportError,
2872 hir_id: this.lower_node_id(wc.id),
2873 predicates: wc.predicates
2875 .map(|predicate| this.lower_where_predicate(predicate))
2882 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2884 WherePredicate::BoundPredicate(WhereBoundPredicate {
2885 ref bound_generic_params,
2890 self.with_in_scope_lifetime_defs(
2891 &bound_generic_params,
2893 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2894 bound_generic_params: this.lower_generic_params(
2895 bound_generic_params,
2896 &NodeMap::default(),
2897 ImplTraitContext::disallowed(),
2899 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
2902 .filter_map(|bound| match *bound {
2903 // Ignore `?Trait` bounds.
2904 // They were copied into type parameters already.
2905 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2906 _ => Some(this.lower_param_bound(
2908 ImplTraitContext::disallowed(),
2917 WherePredicate::RegionPredicate(WhereRegionPredicate {
2921 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2923 lifetime: self.lower_lifetime(lifetime),
2924 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2926 WherePredicate::EqPredicate(WhereEqPredicate {
2932 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2933 hir_id: self.lower_node_id(id),
2934 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
2935 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
2942 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2944 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
2945 fields.iter().enumerate().map(|f| self.lower_struct_field(f)).collect(),
2948 VariantData::Tuple(ref fields, id) => {
2949 hir::VariantData::Tuple(
2953 .map(|f| self.lower_struct_field(f))
2955 self.lower_node_id(id),
2958 VariantData::Unit(id) => {
2959 hir::VariantData::Unit(self.lower_node_id(id))
2964 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2965 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2966 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2967 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2971 hir_ref_id: self.lower_node_id(p.ref_id),
2975 fn lower_poly_trait_ref(
2978 mut itctx: ImplTraitContext<'_>,
2979 ) -> hir::PolyTraitRef {
2980 let bound_generic_params = self.lower_generic_params(
2981 &p.bound_generic_params,
2982 &NodeMap::default(),
2985 let trait_ref = self.with_parent_impl_lifetime_defs(
2986 &bound_generic_params,
2987 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2991 bound_generic_params,
2997 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
3000 hir_id: self.lower_node_id(f.id),
3001 ident: match f.ident {
3002 Some(ident) => ident,
3003 // FIXME(jseyfried): positional field hygiene.
3004 None => Ident::new(sym::integer(index), f.span),
3006 vis: self.lower_visibility(&f.vis, None),
3007 ty: self.lower_ty(&f.ty, ImplTraitContext::disallowed()),
3008 attrs: self.lower_attrs(&f.attrs),
3012 fn lower_field(&mut self, f: &Field) -> hir::Field {
3014 hir_id: self.next_id(),
3016 expr: P(self.lower_expr(&f.expr)),
3018 is_shorthand: f.is_shorthand,
3022 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
3024 ty: self.lower_ty(&mt.ty, itctx),
3025 mutbl: self.lower_mutability(mt.mutbl),
3029 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
3030 -> hir::GenericBounds {
3031 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
3034 fn lower_block_with_stmts(
3037 targeted_by_break: bool,
3038 mut stmts: Vec<hir::Stmt>,
3039 ) -> P<hir::Block> {
3040 let mut expr = None;
3042 for (index, stmt) in b.stmts.iter().enumerate() {
3043 if index == b.stmts.len() - 1 {
3044 if let StmtKind::Expr(ref e) = stmt.node {
3045 expr = Some(P(self.lower_expr(e)));
3047 stmts.extend(self.lower_stmt(stmt));
3050 stmts.extend(self.lower_stmt(stmt));
3055 hir_id: self.lower_node_id(b.id),
3056 stmts: stmts.into(),
3058 rules: self.lower_block_check_mode(&b.rules),
3064 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
3065 self.lower_block_with_stmts(b, targeted_by_break, vec![])
3068 fn lower_maybe_async_body(
3074 let closure_id = match asyncness {
3075 IsAsync::Async { closure_id, .. } => closure_id,
3076 IsAsync::NotAsync => return self.lower_fn_body(&decl, |this| {
3077 let body = this.lower_block(body, false);
3078 this.expr_block(body, ThinVec::new())
3082 self.lower_body(|this| {
3083 let mut arguments: Vec<hir::Arg> = Vec::new();
3084 let mut statements: Vec<hir::Stmt> = Vec::new();
3086 // Async function arguments are lowered into the closure body so that they are
3087 // captured and so that the drop order matches the equivalent non-async functions.
3091 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
3098 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
3100 // let __arg2 = __arg2;
3101 // let <pattern> = __arg2;
3102 // let __arg1 = __arg1;
3103 // let <pattern> = __arg1;
3104 // let __arg0 = __arg0;
3105 // let <pattern> = __arg0;
3109 // If `<pattern>` is a simple ident, then it is lowered to a single
3110 // `let <pattern> = <pattern>;` statement as an optimization.
3111 for (index, argument) in decl.inputs.iter().enumerate() {
3112 let argument = this.lower_arg(argument);
3113 let span = argument.pat.span;
3115 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
3116 // `let <pat> = __argN;` statement. In this case, we do not rename the argument.
3117 let (ident, is_simple_argument) = match argument.pat.node {
3118 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _) =>
3121 // Replace the ident for bindings that aren't simple.
3122 let name = format!("__arg{}", index);
3123 let ident = Ident::from_str(&name);
3129 let desugared_span =
3130 this.mark_span_with_reason(CompilerDesugaringKind::Async, span, None);
3132 // Construct an argument representing `__argN: <ty>` to replace the argument of the
3135 // If this is the simple case, this argument will end up being the same as the
3136 // original argument, but with a different pattern id.
3137 let (new_argument_pat, new_argument_id) = this.pat_ident(desugared_span, ident);
3138 let new_argument = hir::Arg {
3139 hir_id: argument.hir_id,
3140 pat: new_argument_pat,
3143 if is_simple_argument {
3144 // If this is the simple case, then we only insert one statement that is
3145 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
3146 // `HirId`s are densely assigned.
3147 let expr = this.expr_ident(desugared_span, ident, new_argument_id);
3148 let stmt = this.stmt_let_pat(
3149 desugared_span, Some(P(expr)), argument.pat, hir::LocalSource::AsyncFn);
3150 statements.push(stmt);
3152 // If this is not the simple case, then we construct two statements:
3155 // let __argN = __argN;
3156 // let <pat> = __argN;
3159 // The first statement moves the argument into the closure and thus ensures
3160 // that the drop order is correct.
3162 // The second statement creates the bindings that the user wrote.
3164 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
3165 // because the user may have specified a `ref mut` binding in the next
3167 let (move_pat, move_id) = this.pat_ident_binding_mode(
3168 desugared_span, ident, hir::BindingAnnotation::Mutable);
3169 let move_expr = this.expr_ident(desugared_span, ident, new_argument_id);
3170 let move_stmt = this.stmt_let_pat(
3171 desugared_span, Some(P(move_expr)), move_pat, hir::LocalSource::AsyncFn);
3173 // Construct the `let <pat> = __argN;` statement. We re-use the original
3174 // argument's pattern so that `HirId`s are densely assigned.
3175 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
3176 let pattern_stmt = this.stmt_let_pat(
3177 desugared_span, Some(P(pattern_expr)), argument.pat,
3178 hir::LocalSource::AsyncFn);
3180 statements.push(move_stmt);
3181 statements.push(pattern_stmt);
3184 arguments.push(new_argument);
3187 let async_expr = this.make_async_expr(
3188 CaptureBy::Value, closure_id, None, body.span,
3190 let body = this.lower_block_with_stmts(body, false, statements);
3191 this.expr_block(body, ThinVec::new())
3193 (HirVec::from(arguments), this.expr(body.span, async_expr, ThinVec::new()))
3201 attrs: &hir::HirVec<Attribute>,
3202 vis: &mut hir::Visibility,
3204 ) -> hir::ItemKind {
3206 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
3207 ItemKind::Use(ref use_tree) => {
3208 // Start with an empty prefix.
3211 span: use_tree.span,
3214 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
3216 ItemKind::Static(ref t, m, ref e) => {
3217 hir::ItemKind::Static(
3220 if self.sess.features_untracked().impl_trait_in_bindings {
3221 ImplTraitContext::Existential(None)
3223 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3226 self.lower_mutability(m),
3227 self.lower_const_body(e),
3230 ItemKind::Const(ref t, ref e) => {
3231 hir::ItemKind::Const(
3234 if self.sess.features_untracked().impl_trait_in_bindings {
3235 ImplTraitContext::Existential(None)
3237 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3240 self.lower_const_body(e)
3243 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
3244 let fn_def_id = self.resolver.definitions().local_def_id(id);
3245 self.with_new_scopes(|this| {
3246 this.current_item = Some(ident.span);
3248 // Note: we don't need to change the return type from `T` to
3249 // `impl Future<Output = T>` here because lower_body
3250 // only cares about the input argument patterns in the function
3251 // declaration (decl), not the return types.
3252 let body_id = this.lower_maybe_async_body(&decl, header.asyncness.node, body);
3254 let (generics, fn_decl) = this.add_in_band_defs(
3257 AnonymousLifetimeMode::PassThrough,
3258 |this, idty| this.lower_fn_decl(
3260 Some((fn_def_id, idty)),
3262 header.asyncness.node.opt_return_id()
3268 this.lower_fn_header(header),
3274 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
3275 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
3276 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
3277 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
3278 self.lower_ty(t, ImplTraitContext::AssociatedTy),
3279 self.lower_generics(generics, ImplTraitContext::AssociatedTy),
3281 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(
3283 generics: self.lower_generics(generics, ImplTraitContext::AssociatedTy),
3284 bounds: self.lower_param_bounds(b, ImplTraitContext::AssociatedTy),
3285 impl_trait_fn: None,
3286 origin: hir::ExistTyOrigin::ExistentialType,
3289 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
3291 variants: enum_definition
3294 .map(|x| self.lower_variant(x))
3297 self.lower_generics(generics, ImplTraitContext::AssociatedTy),
3299 ItemKind::Struct(ref struct_def, ref generics) => {
3300 let struct_def = self.lower_variant_data(struct_def);
3301 hir::ItemKind::Struct(
3303 self.lower_generics(generics, ImplTraitContext::AssociatedTy),
3306 ItemKind::Union(ref vdata, ref generics) => {
3307 let vdata = self.lower_variant_data(vdata);
3308 hir::ItemKind::Union(
3310 self.lower_generics(generics, ImplTraitContext::AssociatedTy),
3322 let def_id = self.resolver.definitions().local_def_id(id);
3324 // Lower the "impl header" first. This ordering is important
3325 // for in-band lifetimes! Consider `'a` here:
3327 // impl Foo<'a> for u32 {
3328 // fn method(&'a self) { .. }
3331 // Because we start by lowering the `Foo<'a> for u32`
3332 // part, we will add `'a` to the list of generics on
3333 // the impl. When we then encounter it later in the
3334 // method, it will not be considered an in-band
3335 // lifetime to be added, but rather a reference to a
3337 let lowered_trait_impl_id = self.lower_node_id(id);
3338 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
3341 AnonymousLifetimeMode::CreateParameter,
3343 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
3344 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
3347 if let Some(ref trait_ref) = trait_ref {
3348 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
3349 this.trait_impls.entry(def_id).or_default().push(
3350 lowered_trait_impl_id);
3354 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
3356 (trait_ref, lowered_ty)
3360 let new_impl_items = self.with_in_scope_lifetime_defs(
3361 &ast_generics.params,
3365 .map(|item| this.lower_impl_item_ref(item))
3370 hir::ItemKind::Impl(
3371 self.lower_unsafety(unsafety),
3372 self.lower_impl_polarity(polarity),
3373 self.lower_defaultness(defaultness, true /* [1] */),
3380 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
3381 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
3384 .map(|item| self.lower_trait_item_ref(item))
3386 hir::ItemKind::Trait(
3387 self.lower_is_auto(is_auto),
3388 self.lower_unsafety(unsafety),
3389 self.lower_generics(generics, ImplTraitContext::disallowed()),
3394 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
3395 self.lower_generics(generics, ImplTraitContext::disallowed()),
3396 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3398 ItemKind::MacroDef(..)
3399 | ItemKind::Mac(..) => bug!("`TyMac` should have been expanded by now"),
3402 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
3403 // not cause an assertion failure inside the `lower_defaultness` function.
3411 vis: &mut hir::Visibility,
3413 attrs: &hir::HirVec<Attribute>,
3414 ) -> hir::ItemKind {
3415 debug!("lower_use_tree(tree={:?})", tree);
3416 debug!("lower_use_tree: vis = {:?}", vis);
3418 let path = &tree.prefix;
3419 let segments = prefix
3422 .chain(path.segments.iter())
3427 UseTreeKind::Simple(rename, id1, id2) => {
3428 *ident = tree.ident();
3430 // First, apply the prefix to the path.
3431 let mut path = Path {
3436 // Correctly resolve `self` imports.
3437 if path.segments.len() > 1
3438 && path.segments.last().unwrap().ident.name == kw::SelfLower
3440 let _ = path.segments.pop();
3441 if rename.is_none() {
3442 *ident = path.segments.last().unwrap().ident;
3446 let mut resolutions = self.expect_full_res_from_use(id);
3447 // We want to return *something* from this function, so hold onto the first item
3449 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
3451 // Here, we are looping over namespaces, if they exist for the definition
3452 // being imported. We only handle type and value namespaces because we
3453 // won't be dealing with macros in the rest of the compiler.
3454 // Essentially a single `use` which imports two names is desugared into
3456 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
3457 let vis = vis.clone();
3458 let ident = ident.clone();
3459 let mut path = path.clone();
3460 for seg in &mut path.segments {
3461 seg.id = self.sess.next_node_id();
3463 let span = path.span;
3465 self.with_hir_id_owner(new_node_id, |this| {
3466 let new_id = this.lower_node_id(new_node_id);
3467 let res = this.lower_res(res);
3469 this.lower_path_extra(res, &path, ParamMode::Explicit, None);
3470 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
3471 let vis_kind = match vis.node {
3472 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3473 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3474 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3475 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
3476 let path = this.renumber_segment_ids(path);
3477 hir::VisibilityKind::Restricted {
3479 hir_id: this.next_id(),
3483 let vis = respan(vis.span, vis_kind);
3489 attrs: attrs.clone(),
3499 P(self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None));
3500 hir::ItemKind::Use(path, hir::UseKind::Single)
3502 UseTreeKind::Glob => {
3503 let path = P(self.lower_path(
3509 ParamMode::Explicit,
3511 hir::ItemKind::Use(path, hir::UseKind::Glob)
3513 UseTreeKind::Nested(ref trees) => {
3514 // Nested imports are desugared into simple imports.
3515 // So, if we start with
3518 // pub(x) use foo::{a, b};
3521 // we will create three items:
3524 // pub(x) use foo::a;
3525 // pub(x) use foo::b;
3526 // pub(x) use foo::{}; // <-- this is called the `ListStem`
3529 // The first two are produced by recursively invoking
3530 // `lower_use_tree` (and indeed there may be things
3531 // like `use foo::{a::{b, c}}` and so forth). They
3532 // wind up being directly added to
3533 // `self.items`. However, the structure of this
3534 // function also requires us to return one item, and
3535 // for that we return the `{}` import (called the
3540 span: prefix.span.to(path.span),
3543 // Add all the nested `PathListItem`s to the HIR.
3544 for &(ref use_tree, id) in trees {
3545 let new_hir_id = self.lower_node_id(id);
3547 let mut vis = vis.clone();
3548 let mut ident = ident.clone();
3549 let mut prefix = prefix.clone();
3551 // Give the segments new node-ids since they are being cloned.
3552 for seg in &mut prefix.segments {
3553 seg.id = self.sess.next_node_id();
3556 // Each `use` import is an item and thus are owners of the
3557 // names in the path. Up to this point the nested import is
3558 // the current owner, since we want each desugared import to
3559 // own its own names, we have to adjust the owner before
3560 // lowering the rest of the import.
3561 self.with_hir_id_owner(id, |this| {
3562 let item = this.lower_use_tree(use_tree,
3569 let vis_kind = match vis.node {
3570 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3571 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3572 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3573 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
3574 let path = this.renumber_segment_ids(path);
3575 hir::VisibilityKind::Restricted {
3577 hir_id: this.next_id(),
3581 let vis = respan(vis.span, vis_kind);
3587 attrs: attrs.clone(),
3590 span: use_tree.span,
3596 // Subtle and a bit hacky: we lower the privacy level
3597 // of the list stem to "private" most of the time, but
3598 // not for "restricted" paths. The key thing is that
3599 // we don't want it to stay as `pub` (with no caveats)
3600 // because that affects rustdoc and also the lints
3601 // about `pub` items. But we can't *always* make it
3602 // private -- particularly not for restricted paths --
3603 // because it contains node-ids that would then be
3604 // unused, failing the check that HirIds are "densely
3607 hir::VisibilityKind::Public |
3608 hir::VisibilityKind::Crate(_) |
3609 hir::VisibilityKind::Inherited => {
3610 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3612 hir::VisibilityKind::Restricted { .. } => {
3613 // Do nothing here, as described in the comment on the match.
3617 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
3618 let res = self.lower_res(res);
3619 let path = P(self.lower_path_extra(res, &prefix, ParamMode::Explicit, None));
3620 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3625 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
3626 /// many times in the HIR tree; for each occurrence, we need to assign distinct
3627 /// `NodeId`s. (See, e.g., #56128.)
3628 fn renumber_segment_ids(&mut self, path: &P<hir::Path>) -> P<hir::Path> {
3629 debug!("renumber_segment_ids(path = {:?})", path);
3630 let mut path = path.clone();
3631 for seg in path.segments.iter_mut() {
3632 if seg.hir_id.is_some() {
3633 seg.hir_id = Some(self.next_id());
3639 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3640 let trait_item_def_id = self.resolver.definitions().local_def_id(i.id);
3642 let (generics, node) = match i.node {
3643 TraitItemKind::Const(ref ty, ref default) => (
3644 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3645 hir::TraitItemKind::Const(
3646 self.lower_ty(ty, ImplTraitContext::disallowed()),
3649 .map(|x| self.lower_const_body(x)),
3652 TraitItemKind::Method(ref sig, None) => {
3653 let names = self.lower_fn_args_to_names(&sig.decl);
3654 let (generics, sig) = self.lower_method_sig(
3661 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3663 TraitItemKind::Method(ref sig, Some(ref body)) => {
3664 let body_id = self.lower_fn_body(&sig.decl, |this| {
3665 let body = this.lower_block(body, false);
3666 this.expr_block(body, ThinVec::new())
3668 let (generics, sig) = self.lower_method_sig(
3675 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3677 TraitItemKind::Type(ref bounds, ref default) => {
3678 let generics = self.lower_generics(&i.generics, ImplTraitContext::AssociatedTy);
3679 let node = hir::TraitItemKind::Type(
3680 self.lower_param_bounds(bounds, ImplTraitContext::AssociatedTy),
3683 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3688 TraitItemKind::Macro(..) => bug!("macro item shouldn't exist at this point"),
3692 hir_id: self.lower_node_id(i.id),
3694 attrs: self.lower_attrs(&i.attrs),
3701 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3702 let (kind, has_default) = match i.node {
3703 TraitItemKind::Const(_, ref default) => {
3704 (hir::AssocItemKind::Const, default.is_some())
3706 TraitItemKind::Type(_, ref default) => {
3707 (hir::AssocItemKind::Type, default.is_some())
3709 TraitItemKind::Method(ref sig, ref default) => (
3710 hir::AssocItemKind::Method {
3711 has_self: sig.decl.has_self(),
3715 TraitItemKind::Macro(..) => unimplemented!(),
3718 id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) },
3721 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3726 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3727 let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
3729 let (generics, node) = match i.node {
3730 ImplItemKind::Const(ref ty, ref expr) => (
3731 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3732 hir::ImplItemKind::Const(
3733 self.lower_ty(ty, ImplTraitContext::disallowed()),
3734 self.lower_const_body(expr),
3737 ImplItemKind::Method(ref sig, ref body) => {
3738 self.current_item = Some(i.span);
3739 let body_id = self.lower_maybe_async_body(
3740 &sig.decl, sig.header.asyncness.node, body
3742 let impl_trait_return_allow = !self.is_in_trait_impl;
3743 let (generics, sig) = self.lower_method_sig(
3747 impl_trait_return_allow,
3748 sig.header.asyncness.node.opt_return_id(),
3751 (generics, hir::ImplItemKind::Method(sig, body_id))
3753 ImplItemKind::Type(ref ty) => (
3754 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3755 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3757 ImplItemKind::Existential(ref bounds) => (
3758 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3759 hir::ImplItemKind::Existential(
3760 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3763 ImplItemKind::Macro(..) => bug!("`TyMac` should have been expanded by now"),
3767 hir_id: self.lower_node_id(i.id),
3769 attrs: self.lower_attrs(&i.attrs),
3771 vis: self.lower_visibility(&i.vis, None),
3772 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3777 // [1] since `default impl` is not yet implemented, this is always true in impls
3780 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3782 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
3785 vis: self.lower_visibility(&i.vis, Some(i.id)),
3786 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3787 kind: match i.node {
3788 ImplItemKind::Const(..) => hir::AssocItemKind::Const,
3789 ImplItemKind::Type(..) => hir::AssocItemKind::Type,
3790 ImplItemKind::Existential(..) => hir::AssocItemKind::Existential,
3791 ImplItemKind::Method(ref sig, _) => hir::AssocItemKind::Method {
3792 has_self: sig.decl.has_self(),
3794 ImplItemKind::Macro(..) => unimplemented!(),
3798 // [1] since `default impl` is not yet implemented, this is always true in impls
3801 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3804 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3808 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3809 let node_ids = match i.node {
3810 ItemKind::Use(ref use_tree) => {
3811 let mut vec = smallvec![i.id];
3812 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3815 ItemKind::MacroDef(..) => SmallVec::new(),
3817 ItemKind::Impl(.., None, _, _) => smallvec![i.id],
3818 ItemKind::Static(ref ty, ..) => {
3819 let mut ids = smallvec![i.id];
3820 if self.sess.features_untracked().impl_trait_in_bindings {
3821 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3822 visitor.visit_ty(ty);
3826 ItemKind::Const(ref ty, ..) => {
3827 let mut ids = smallvec![i.id];
3828 if self.sess.features_untracked().impl_trait_in_bindings {
3829 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3830 visitor.visit_ty(ty);
3834 _ => smallvec![i.id],
3837 node_ids.into_iter().map(|node_id| hir::ItemId {
3838 id: self.allocate_hir_id_counter(node_id)
3842 fn lower_item_id_use_tree(&mut self,
3845 vec: &mut SmallVec<[NodeId; 1]>)
3848 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3850 self.lower_item_id_use_tree(nested, id, vec);
3852 UseTreeKind::Glob => {}
3853 UseTreeKind::Simple(_, id1, id2) => {
3854 for (_, &id) in self.expect_full_res_from_use(base_id)
3856 .zip([id1, id2].iter())
3864 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3865 let mut ident = i.ident;
3866 let mut vis = self.lower_visibility(&i.vis, None);
3867 let attrs = self.lower_attrs(&i.attrs);
3868 if let ItemKind::MacroDef(ref def) = i.node {
3869 if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) ||
3870 attr::contains_name(&i.attrs, sym::rustc_doc_only_macro) {
3871 let body = self.lower_token_stream(def.stream());
3872 let hir_id = self.lower_node_id(i.id);
3873 self.exported_macros.push(hir::MacroDef {
3886 let node = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.node);
3889 hir_id: self.lower_node_id(i.id),
3898 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3899 let def_id = self.resolver.definitions().local_def_id(i.id);
3901 hir_id: self.lower_node_id(i.id),
3903 attrs: self.lower_attrs(&i.attrs),
3904 node: match i.node {
3905 ForeignItemKind::Fn(ref fdec, ref generics) => {
3906 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3909 AnonymousLifetimeMode::PassThrough,
3912 // Disallow impl Trait in foreign items
3913 this.lower_fn_decl(fdec, None, false, None),
3914 this.lower_fn_args_to_names(fdec),
3919 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3921 ForeignItemKind::Static(ref t, m) => {
3922 hir::ForeignItemKind::Static(
3923 self.lower_ty(t, ImplTraitContext::disallowed()), self.lower_mutability(m))
3925 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3926 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3928 vis: self.lower_visibility(&i.vis, None),
3933 fn lower_method_sig(
3935 generics: &Generics,
3938 impl_trait_return_allow: bool,
3939 is_async: Option<NodeId>,
3940 ) -> (hir::Generics, hir::MethodSig) {
3941 let header = self.lower_fn_header(sig.header);
3942 let (generics, decl) = self.add_in_band_defs(
3945 AnonymousLifetimeMode::PassThrough,
3946 |this, idty| this.lower_fn_decl(
3948 Some((fn_def_id, idty)),
3949 impl_trait_return_allow,
3953 (generics, hir::MethodSig { header, decl })
3956 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3958 IsAuto::Yes => hir::IsAuto::Yes,
3959 IsAuto::No => hir::IsAuto::No,
3963 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3965 unsafety: self.lower_unsafety(h.unsafety),
3966 asyncness: self.lower_asyncness(h.asyncness.node),
3967 constness: self.lower_constness(h.constness),
3972 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3974 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3975 Unsafety::Normal => hir::Unsafety::Normal,
3979 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3981 Constness::Const => hir::Constness::Const,
3982 Constness::NotConst => hir::Constness::NotConst,
3986 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3988 IsAsync::Async { .. } => hir::IsAsync::Async,
3989 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3993 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3995 UnOp::Deref => hir::UnDeref,
3996 UnOp::Not => hir::UnNot,
3997 UnOp::Neg => hir::UnNeg,
4001 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
4003 node: match b.node {
4004 BinOpKind::Add => hir::BinOpKind::Add,
4005 BinOpKind::Sub => hir::BinOpKind::Sub,
4006 BinOpKind::Mul => hir::BinOpKind::Mul,
4007 BinOpKind::Div => hir::BinOpKind::Div,
4008 BinOpKind::Rem => hir::BinOpKind::Rem,
4009 BinOpKind::And => hir::BinOpKind::And,
4010 BinOpKind::Or => hir::BinOpKind::Or,
4011 BinOpKind::BitXor => hir::BinOpKind::BitXor,
4012 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
4013 BinOpKind::BitOr => hir::BinOpKind::BitOr,
4014 BinOpKind::Shl => hir::BinOpKind::Shl,
4015 BinOpKind::Shr => hir::BinOpKind::Shr,
4016 BinOpKind::Eq => hir::BinOpKind::Eq,
4017 BinOpKind::Lt => hir::BinOpKind::Lt,
4018 BinOpKind::Le => hir::BinOpKind::Le,
4019 BinOpKind::Ne => hir::BinOpKind::Ne,
4020 BinOpKind::Ge => hir::BinOpKind::Ge,
4021 BinOpKind::Gt => hir::BinOpKind::Gt,
4027 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
4028 let node = match p.node {
4029 PatKind::Wild => hir::PatKind::Wild,
4030 PatKind::Ident(ref binding_mode, ident, ref sub) => {
4031 match self.resolver.get_partial_res(p.id).map(|d| d.base_res()) {
4032 // `None` can occur in body-less function signatures
4033 res @ None | res @ Some(Res::Local(_)) => {
4034 let canonical_id = match res {
4035 Some(Res::Local(id)) => id,
4039 hir::PatKind::Binding(
4040 self.lower_binding_mode(binding_mode),
4041 self.lower_node_id(canonical_id),
4043 sub.as_ref().map(|x| self.lower_pat(x)),
4046 Some(res) => hir::PatKind::Path(hir::QPath::Resolved(
4050 res: self.lower_res(res),
4051 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4056 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
4057 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
4058 let qpath = self.lower_qpath(
4062 ParamMode::Optional,
4063 ImplTraitContext::disallowed(),
4065 hir::PatKind::TupleStruct(
4067 pats.iter().map(|x| self.lower_pat(x)).collect(),
4071 PatKind::Path(ref qself, ref path) => {
4072 let qpath = self.lower_qpath(
4076 ParamMode::Optional,
4077 ImplTraitContext::disallowed(),
4079 hir::PatKind::Path(qpath)
4081 PatKind::Struct(ref path, ref fields, etc) => {
4082 let qpath = self.lower_qpath(
4086 ParamMode::Optional,
4087 ImplTraitContext::disallowed(),
4095 node: hir::FieldPat {
4096 hir_id: self.next_id(),
4097 ident: f.node.ident,
4098 pat: self.lower_pat(&f.node.pat),
4099 is_shorthand: f.node.is_shorthand,
4104 hir::PatKind::Struct(qpath, fs, etc)
4106 PatKind::Tuple(ref elts, ddpos) => {
4107 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
4109 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
4110 PatKind::Ref(ref inner, mutbl) => {
4111 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
4113 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
4114 P(self.lower_expr(e1)),
4115 P(self.lower_expr(e2)),
4116 self.lower_range_end(end),
4118 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
4119 before.iter().map(|x| self.lower_pat(x)).collect(),
4120 slice.as_ref().map(|x| self.lower_pat(x)),
4121 after.iter().map(|x| self.lower_pat(x)).collect(),
4123 PatKind::Paren(ref inner) => return self.lower_pat(inner),
4124 PatKind::Mac(_) => panic!("Shouldn't exist here"),
4128 hir_id: self.lower_node_id(p.id),
4134 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
4136 RangeEnd::Included(_) => hir::RangeEnd::Included,
4137 RangeEnd::Excluded => hir::RangeEnd::Excluded,
4141 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
4142 self.with_new_scopes(|this| {
4144 hir_id: this.lower_node_id(c.id),
4145 body: this.lower_const_body(&c.value),
4150 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
4151 let kind = match e.node {
4152 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
4153 ExprKind::Array(ref exprs) => {
4154 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
4156 ExprKind::Repeat(ref expr, ref count) => {
4157 let expr = P(self.lower_expr(expr));
4158 let count = self.lower_anon_const(count);
4159 hir::ExprKind::Repeat(expr, count)
4161 ExprKind::Tup(ref elts) => {
4162 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
4164 ExprKind::Call(ref f, ref args) => {
4165 let f = P(self.lower_expr(f));
4166 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
4168 ExprKind::MethodCall(ref seg, ref args) => {
4169 let hir_seg = P(self.lower_path_segment(
4172 ParamMode::Optional,
4174 ParenthesizedGenericArgs::Err,
4175 ImplTraitContext::disallowed(),
4178 let args = args.iter().map(|x| self.lower_expr(x)).collect();
4179 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
4181 ExprKind::Binary(binop, ref lhs, ref rhs) => {
4182 let binop = self.lower_binop(binop);
4183 let lhs = P(self.lower_expr(lhs));
4184 let rhs = P(self.lower_expr(rhs));
4185 hir::ExprKind::Binary(binop, lhs, rhs)
4187 ExprKind::Unary(op, ref ohs) => {
4188 let op = self.lower_unop(op);
4189 let ohs = P(self.lower_expr(ohs));
4190 hir::ExprKind::Unary(op, ohs)
4192 ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.node.clone())),
4193 ExprKind::Cast(ref expr, ref ty) => {
4194 let expr = P(self.lower_expr(expr));
4195 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4197 ExprKind::Type(ref expr, ref ty) => {
4198 let expr = P(self.lower_expr(expr));
4199 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4201 ExprKind::AddrOf(m, ref ohs) => {
4202 let m = self.lower_mutability(m);
4203 let ohs = P(self.lower_expr(ohs));
4204 hir::ExprKind::AddrOf(m, ohs)
4206 // More complicated than you might expect because the else branch
4207 // might be `if let`.
4208 ExprKind::If(ref cond, ref then, ref else_opt) => {
4210 let then_pat = self.pat_bool(e.span, true);
4211 let then_blk = self.lower_block(then, false);
4212 let then_expr = self.expr_block(then_blk, ThinVec::new());
4213 let then_arm = self.arm(hir_vec![then_pat], P(then_expr));
4215 // `_ => else_block` where `else_block` is `{}` if there's `None`:
4216 let else_pat = self.pat_wild(e.span);
4217 let else_expr = match else_opt {
4218 None => self.expr_block_empty(e.span),
4219 Some(els) => match els.node {
4220 ExprKind::IfLet(..) => {
4221 // Wrap the `if let` expr in a block.
4222 let els = self.lower_expr(els);
4223 let blk = self.block_all(els.span, hir_vec![], Some(P(els)));
4224 self.expr_block(P(blk), ThinVec::new())
4226 _ => self.lower_expr(els),
4229 let else_arm = self.arm(hir_vec![else_pat], P(else_expr));
4232 let span_block = self.mark_span_with_reason(IfTemporary, cond.span, None);
4233 let cond = self.lower_expr(cond);
4234 // Wrap in a construct equivalent to `{ let _t = $cond; _t }` to preserve drop
4235 // semantics since `if cond { ... }` don't let temporaries live outside of `cond`.
4236 let cond = self.expr_drop_temps(span_block, P(cond), ThinVec::new());
4238 hir::ExprKind::Match(
4240 vec![then_arm, else_arm].into(),
4241 hir::MatchSource::IfDesugar {
4242 contains_else_clause: else_opt.is_some()
4246 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4247 hir::ExprKind::While(
4248 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
4249 this.lower_block(body, false),
4250 this.lower_label(opt_label),
4253 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4254 hir::ExprKind::Loop(
4255 this.lower_block(body, false),
4256 this.lower_label(opt_label),
4257 hir::LoopSource::Loop,
4260 ExprKind::TryBlock(ref body) => {
4261 self.with_catch_scope(body.id, |this| {
4262 let unstable_span = this.mark_span_with_reason(
4263 CompilerDesugaringKind::TryBlock,
4265 Some(vec![sym::try_trait].into()),
4267 let mut block = this.lower_block(body, true).into_inner();
4268 let tail = block.expr.take().map_or_else(
4270 let span = this.sess.source_map().end_point(unstable_span);
4273 node: hir::ExprKind::Tup(hir_vec![]),
4274 attrs: ThinVec::new(),
4275 hir_id: this.next_id(),
4278 |x: P<hir::Expr>| x.into_inner(),
4280 block.expr = Some(this.wrap_in_try_constructor(
4281 sym::from_ok, tail, unstable_span));
4282 hir::ExprKind::Block(P(block), None)
4285 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
4286 P(self.lower_expr(expr)),
4287 arms.iter().map(|x| self.lower_arm(x)).collect(),
4288 hir::MatchSource::Normal,
4290 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
4291 self.make_async_expr(capture_clause, closure_node_id, None, block.span, |this| {
4292 this.with_new_scopes(|this| {
4293 let block = this.lower_block(block, false);
4294 this.expr_block(block, ThinVec::new())
4298 ExprKind::Await(_origin, ref expr) => self.lower_await(e.span, expr),
4300 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
4302 if let IsAsync::Async { closure_id, .. } = asyncness {
4303 let outer_decl = FnDecl {
4304 inputs: decl.inputs.clone(),
4305 output: FunctionRetTy::Default(fn_decl_span),
4308 // We need to lower the declaration outside the new scope, because we
4309 // have to conserve the state of being inside a loop condition for the
4310 // closure argument types.
4311 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
4313 self.with_new_scopes(|this| {
4314 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
4315 if capture_clause == CaptureBy::Ref &&
4316 !decl.inputs.is_empty()
4322 "`async` non-`move` closures with arguments \
4323 are not currently supported",
4325 .help("consider using `let` statements to manually capture \
4326 variables by reference before entering an \
4327 `async move` closure")
4331 // Transform `async |x: u8| -> X { ... }` into
4332 // `|x: u8| future_from_generator(|| -> X { ... })`.
4333 let body_id = this.lower_fn_body(&outer_decl, |this| {
4334 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
4337 let async_body = this.make_async_expr(
4338 capture_clause, closure_id, async_ret_ty, body.span,
4340 this.with_new_scopes(|this| this.lower_expr(body))
4342 this.expr(fn_decl_span, async_body, ThinVec::new())
4344 hir::ExprKind::Closure(
4345 this.lower_capture_clause(capture_clause),
4353 // Lower outside new scope to preserve `is_in_loop_condition`.
4354 let fn_decl = self.lower_fn_decl(decl, None, false, None);
4356 self.with_new_scopes(|this| {
4357 this.current_item = Some(fn_decl_span);
4358 let mut is_generator = false;
4359 let body_id = this.lower_fn_body(decl, |this| {
4360 let e = this.lower_expr(body);
4361 is_generator = this.is_generator;
4364 let generator_option = if is_generator {
4365 if !decl.inputs.is_empty() {
4370 "generators cannot have explicit arguments"
4372 this.sess.abort_if_errors();
4374 Some(match movability {
4375 Movability::Movable => hir::GeneratorMovability::Movable,
4376 Movability::Static => hir::GeneratorMovability::Static,
4379 if movability == Movability::Static {
4384 "closures cannot be static"
4389 hir::ExprKind::Closure(
4390 this.lower_capture_clause(capture_clause),
4399 ExprKind::Block(ref blk, opt_label) => {
4400 hir::ExprKind::Block(self.lower_block(blk,
4401 opt_label.is_some()),
4402 self.lower_label(opt_label))
4404 ExprKind::Assign(ref el, ref er) => {
4405 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
4407 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
4408 self.lower_binop(op),
4409 P(self.lower_expr(el)),
4410 P(self.lower_expr(er)),
4412 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
4413 ExprKind::Index(ref el, ref er) => {
4414 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
4416 // Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
4417 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
4418 let id = self.next_id();
4419 let e1 = self.lower_expr(e1);
4420 let e2 = self.lower_expr(e2);
4421 self.expr_call_std_assoc_fn(
4424 &[sym::ops, sym::RangeInclusive],
4429 ExprKind::Range(ref e1, ref e2, lims) => {
4430 use syntax::ast::RangeLimits::*;
4432 let path = match (e1, e2, lims) {
4433 (&None, &None, HalfOpen) => sym::RangeFull,
4434 (&Some(..), &None, HalfOpen) => sym::RangeFrom,
4435 (&None, &Some(..), HalfOpen) => sym::RangeTo,
4436 (&Some(..), &Some(..), HalfOpen) => sym::Range,
4437 (&None, &Some(..), Closed) => sym::RangeToInclusive,
4438 (&Some(..), &Some(..), Closed) => unreachable!(),
4439 (_, &None, Closed) => self.diagnostic()
4440 .span_fatal(e.span, "inclusive range with no end")
4444 let fields = e1.iter()
4445 .map(|e| ("start", e))
4446 .chain(e2.iter().map(|e| ("end", e)))
4448 let expr = P(self.lower_expr(&e));
4449 let ident = Ident::new(Symbol::intern(s), e.span);
4450 self.field(ident, expr, e.span)
4452 .collect::<P<[hir::Field]>>();
4454 let is_unit = fields.is_empty();
4455 let struct_path = [sym::ops, path];
4456 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
4457 let struct_path = hir::QPath::Resolved(None, P(struct_path));
4460 hir_id: self.lower_node_id(e.id),
4462 hir::ExprKind::Path(struct_path)
4464 hir::ExprKind::Struct(P(struct_path), fields, None)
4467 attrs: e.attrs.clone(),
4470 ExprKind::Path(ref qself, ref path) => {
4471 let qpath = self.lower_qpath(
4475 ParamMode::Optional,
4476 ImplTraitContext::disallowed(),
4478 hir::ExprKind::Path(qpath)
4480 ExprKind::Break(opt_label, ref opt_expr) => {
4481 let destination = if self.is_in_loop_condition && opt_label.is_none() {
4484 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4487 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4489 hir::ExprKind::Break(
4491 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
4494 ExprKind::Continue(opt_label) => {
4495 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
4498 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4501 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4504 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
4505 ExprKind::InlineAsm(ref asm) => {
4506 let hir_asm = hir::InlineAsm {
4507 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
4508 outputs: asm.outputs
4510 .map(|out| hir::InlineAsmOutput {
4511 constraint: out.constraint.clone(),
4513 is_indirect: out.is_indirect,
4514 span: out.expr.span,
4517 asm: asm.asm.clone(),
4518 asm_str_style: asm.asm_str_style,
4519 clobbers: asm.clobbers.clone().into(),
4520 volatile: asm.volatile,
4521 alignstack: asm.alignstack,
4522 dialect: asm.dialect,
4525 let outputs = asm.outputs
4527 .map(|out| self.lower_expr(&out.expr))
4529 let inputs = asm.inputs
4531 .map(|&(_, ref input)| self.lower_expr(input))
4533 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
4535 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4540 ParamMode::Optional,
4541 ImplTraitContext::disallowed(),
4543 fields.iter().map(|x| self.lower_field(x)).collect(),
4544 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4546 ExprKind::Paren(ref ex) => {
4547 let mut ex = self.lower_expr(ex);
4548 // Include parens in span, but only if it is a super-span.
4549 if e.span.contains(ex.span) {
4552 // Merge attributes into the inner expression.
4553 let mut attrs = e.attrs.clone();
4554 attrs.extend::<Vec<_>>(ex.attrs.into());
4559 ExprKind::Yield(ref opt_expr) => {
4560 self.is_generator = true;
4563 .map(|x| self.lower_expr(x))
4564 .unwrap_or_else(|| self.expr_unit(e.span));
4565 hir::ExprKind::Yield(P(expr))
4568 ExprKind::Err => hir::ExprKind::Err,
4570 // Desugar `ExprIfLet`
4571 // from: `if let <pat> = <sub_expr> <body> [<else_opt>]`
4572 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4575 // match <sub_expr> {
4577 // _ => [<else_opt> | ()]
4580 let mut arms = vec![];
4582 // `<pat> => <body>`
4584 let body = self.lower_block(body, false);
4585 let body_expr = P(self.expr_block(body, ThinVec::new()));
4586 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4587 arms.push(self.arm(pats, body_expr));
4590 // _ => [<else_opt>|{}]
4592 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4593 let wildcard_pattern = self.pat_wild(e.span);
4594 let body = if let Some(else_expr) = wildcard_arm {
4595 self.lower_expr(else_expr)
4597 self.expr_block_empty(e.span)
4599 arms.push(self.arm(hir_vec![wildcard_pattern], P(body)));
4602 let contains_else_clause = else_opt.is_some();
4604 let sub_expr = P(self.lower_expr(sub_expr));
4606 hir::ExprKind::Match(
4609 hir::MatchSource::IfLetDesugar {
4610 contains_else_clause,
4615 // Desugar `ExprWhileLet`
4616 // from: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4617 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4620 // [opt_ident]: loop {
4621 // match <sub_expr> {
4627 // Note that the block AND the condition are evaluated in the loop scope.
4628 // This is done to allow `break` from inside the condition of the loop.
4629 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4631 this.lower_block(body, false),
4632 this.expr_break(e.span, ThinVec::new()),
4633 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4637 // `<pat> => <body>`
4639 let body_expr = P(self.expr_block(body, ThinVec::new()));
4640 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4641 self.arm(pats, body_expr)
4646 let pat_under = self.pat_wild(e.span);
4647 self.arm(hir_vec![pat_under], break_expr)
4650 // `match <sub_expr> { ... }`
4651 let arms = hir_vec![pat_arm, break_arm];
4652 let match_expr = self.expr(
4654 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4658 // `[opt_ident]: loop { ... }`
4659 let loop_block = P(self.block_expr(P(match_expr)));
4660 let loop_expr = hir::ExprKind::Loop(
4662 self.lower_label(opt_label),
4663 hir::LoopSource::WhileLet,
4665 // Add attributes to the outer returned expr node.
4669 // Desugar `ExprForLoop`
4670 // from: `[opt_ident]: for <pat> in <head> <body>`
4671 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4675 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4677 // [opt_ident]: loop {
4679 // match ::std::iter::Iterator::next(&mut iter) {
4680 // ::std::option::Option::Some(val) => __next = val,
4681 // ::std::option::Option::None => break
4683 // let <pat> = __next;
4684 // StmtKind::Expr(<body>);
4692 let mut head = self.lower_expr(head);
4693 let head_sp = head.span;
4694 let desugared_span = self.mark_span_with_reason(
4695 CompilerDesugaringKind::ForLoop,
4699 head.span = desugared_span;
4701 let iter = Ident::with_empty_ctxt(sym::iter);
4703 let next_ident = Ident::with_empty_ctxt(sym::__next);
4704 let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
4707 hir::BindingAnnotation::Mutable,
4710 // `::std::option::Option::Some(val) => __next = val`
4712 let val_ident = Ident::with_empty_ctxt(sym::val);
4713 let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
4714 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat_hid));
4715 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat_hid));
4716 let assign = P(self.expr(
4718 hir::ExprKind::Assign(next_expr, val_expr),
4721 let some_pat = self.pat_some(pat.span, val_pat);
4722 self.arm(hir_vec![some_pat], assign)
4725 // `::std::option::Option::None => break`
4728 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4729 let pat = self.pat_none(e.span);
4730 self.arm(hir_vec![pat], break_expr)
4734 let (iter_pat, iter_pat_nid) = self.pat_ident_binding_mode(
4737 hir::BindingAnnotation::Mutable
4740 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4742 let iter = P(self.expr_ident(head_sp, iter, iter_pat_nid));
4743 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4744 let next_path = &[sym::iter, sym::Iterator, sym::next];
4745 let next_expr = P(self.expr_call_std_path(
4748 hir_vec![ref_mut_iter],
4750 let arms = hir_vec![pat_arm, break_arm];
4754 hir::ExprKind::Match(
4757 hir::MatchSource::ForLoopDesugar
4762 let match_stmt = self.stmt(head_sp, hir::StmtKind::Expr(match_expr));
4764 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat_hid));
4767 let next_let = self.stmt_let_pat(
4771 hir::LocalSource::ForLoopDesugar,
4774 // `let <pat> = __next`
4775 let pat = self.lower_pat(pat);
4776 let pat_let = self.stmt_let_pat(
4780 hir::LocalSource::ForLoopDesugar,
4783 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4784 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4785 let body_stmt = self.stmt(body.span, hir::StmtKind::Expr(body_expr));
4787 let loop_block = P(self.block_all(
4789 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4793 // `[opt_ident]: loop { ... }`
4794 let loop_expr = hir::ExprKind::Loop(
4796 self.lower_label(opt_label),
4797 hir::LoopSource::ForLoop,
4799 let loop_expr = P(hir::Expr {
4800 hir_id: self.lower_node_id(e.id),
4803 attrs: ThinVec::new(),
4806 // `mut iter => { ... }`
4807 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4809 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4810 let into_iter_expr = {
4811 let into_iter_path =
4812 &[sym::iter, sym::IntoIterator, sym::into_iter];
4813 P(self.expr_call_std_path(
4820 let match_expr = P(self.expr_match(
4824 hir::MatchSource::ForLoopDesugar,
4827 // This is effectively `{ let _result = ...; _result }`.
4828 // The construct was introduced in #21984.
4829 // FIXME(60253): Is this still necessary?
4830 // Also, add the attributes to the outer returned expr node.
4831 return self.expr_drop_temps(head_sp, match_expr, e.attrs.clone())
4834 // Desugar `ExprKind::Try`
4836 ExprKind::Try(ref sub_expr) => {
4839 // match Try::into_result(<expr>) {
4840 // Ok(val) => #[allow(unreachable_code)] val,
4841 // Err(err) => #[allow(unreachable_code)]
4842 // // If there is an enclosing `catch {...}`
4843 // break 'catch_target Try::from_error(From::from(err)),
4845 // return Try::from_error(From::from(err)),
4848 let unstable_span = self.mark_span_with_reason(
4849 CompilerDesugaringKind::QuestionMark,
4851 Some(vec![sym::try_trait].into()),
4853 let try_span = self.sess.source_map().end_point(e.span);
4854 let try_span = self.mark_span_with_reason(
4855 CompilerDesugaringKind::QuestionMark,
4857 Some(vec![sym::try_trait].into()),
4860 // `Try::into_result(<expr>)`
4863 let sub_expr = self.lower_expr(sub_expr);
4865 let path = &[sym::ops, sym::Try, sym::into_result];
4866 P(self.expr_call_std_path(
4873 // `#[allow(unreachable_code)]`
4875 // `allow(unreachable_code)`
4877 let allow_ident = Ident::with_empty_ctxt(sym::allow).with_span_pos(e.span);
4878 let uc_ident = Ident::with_empty_ctxt(sym::unreachable_code)
4879 .with_span_pos(e.span);
4880 let uc_nested = attr::mk_nested_word_item(uc_ident);
4881 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4883 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4885 let attrs = vec![attr];
4887 // `Ok(val) => #[allow(unreachable_code)] val,`
4889 let val_ident = Ident::with_empty_ctxt(sym::val);
4890 let (val_pat, val_pat_nid) = self.pat_ident(e.span, val_ident);
4891 let val_expr = P(self.expr_ident_with_attrs(
4895 ThinVec::from(attrs.clone()),
4897 let ok_pat = self.pat_ok(e.span, val_pat);
4899 self.arm(hir_vec![ok_pat], val_expr)
4902 // `Err(err) => #[allow(unreachable_code)]
4903 // return Try::from_error(From::from(err)),`
4905 let err_ident = Ident::with_empty_ctxt(sym::err);
4906 let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
4908 let from_path = &[sym::convert, sym::From, sym::from];
4909 let err_expr = self.expr_ident(try_span, err_ident, err_local_nid);
4910 self.expr_call_std_path(try_span, from_path, hir_vec![err_expr])
4913 self.wrap_in_try_constructor(sym::from_error, from_expr, unstable_span);
4914 let thin_attrs = ThinVec::from(attrs);
4915 let catch_scope = self.catch_scopes.last().map(|x| *x);
4916 let ret_expr = if let Some(catch_node) = catch_scope {
4917 let target_id = Ok(self.lower_node_id(catch_node));
4920 hir::ExprKind::Break(
4925 Some(from_err_expr),
4930 P(self.expr(try_span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4933 let err_pat = self.pat_err(try_span, err_local);
4934 self.arm(hir_vec![err_pat], ret_expr)
4937 hir::ExprKind::Match(
4939 hir_vec![err_arm, ok_arm],
4940 hir::MatchSource::TryDesugar,
4944 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4948 hir_id: self.lower_node_id(e.id),
4951 attrs: e.attrs.clone(),
4955 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
4956 smallvec![match s.node {
4957 StmtKind::Local(ref l) => {
4958 let (l, item_ids) = self.lower_local(l);
4959 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
4962 let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
4963 self.stmt(s.span, hir::StmtKind::Item(item_id))
4968 hir_id: self.lower_node_id(s.id),
4969 node: hir::StmtKind::Local(P(l)),
4975 StmtKind::Item(ref it) => {
4976 // Can only use the ID once.
4977 let mut id = Some(s.id);
4978 return self.lower_item_id(it)
4981 let hir_id = id.take()
4982 .map(|id| self.lower_node_id(id))
4983 .unwrap_or_else(|| self.next_id());
4987 node: hir::StmtKind::Item(item_id),
4993 StmtKind::Expr(ref e) => {
4995 hir_id: self.lower_node_id(s.id),
4996 node: hir::StmtKind::Expr(P(self.lower_expr(e))),
5000 StmtKind::Semi(ref e) => {
5002 hir_id: self.lower_node_id(s.id),
5003 node: hir::StmtKind::Semi(P(self.lower_expr(e))),
5007 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
5011 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
5013 CaptureBy::Value => hir::CaptureByValue,
5014 CaptureBy::Ref => hir::CaptureByRef,
5018 /// If an `explicit_owner` is given, this method allocates the `HirId` in
5019 /// the address space of that item instead of the item currently being
5020 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
5021 /// lower a `Visibility` value although we haven't lowered the owning
5022 /// `ImplItem` in question yet.
5023 fn lower_visibility(
5026 explicit_owner: Option<NodeId>,
5027 ) -> hir::Visibility {
5028 let node = match v.node {
5029 VisibilityKind::Public => hir::VisibilityKind::Public,
5030 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
5031 VisibilityKind::Restricted { ref path, id } => {
5032 debug!("lower_visibility: restricted path id = {:?}", id);
5033 let lowered_id = if let Some(owner) = explicit_owner {
5034 self.lower_node_id_with_owner(id, owner)
5036 self.lower_node_id(id)
5038 let res = self.expect_full_res(id);
5039 let res = self.lower_res(res);
5040 hir::VisibilityKind::Restricted {
5041 path: P(self.lower_path_extra(
5044 ParamMode::Explicit,
5050 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
5052 respan(v.span, node)
5055 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
5057 Defaultness::Default => hir::Defaultness::Default {
5058 has_value: has_value,
5060 Defaultness::Final => {
5062 hir::Defaultness::Final
5067 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
5069 BlockCheckMode::Default => hir::DefaultBlock,
5070 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
5074 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
5076 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
5077 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
5078 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
5079 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
5083 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
5085 CompilerGenerated => hir::CompilerGenerated,
5086 UserProvided => hir::UserProvided,
5090 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
5092 ImplPolarity::Positive => hir::ImplPolarity::Positive,
5093 ImplPolarity::Negative => hir::ImplPolarity::Negative,
5097 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
5099 TraitBoundModifier::None => hir::TraitBoundModifier::None,
5100 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
5104 // Helper methods for building HIR.
5106 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
5108 hir_id: self.next_id(),
5117 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
5119 hir_id: self.next_id(),
5123 is_shorthand: false,
5127 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
5128 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
5129 P(self.expr(span, expr_break, attrs))
5136 args: hir::HirVec<hir::Expr>,
5138 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
5141 // Note: associated functions must use `expr_call_std_path`.
5142 fn expr_call_std_path(
5145 path_components: &[Symbol],
5146 args: hir::HirVec<hir::Expr>,
5148 let path = P(self.expr_std_path(span, path_components, None, ThinVec::new()));
5149 self.expr_call(span, path, args)
5152 // Create an expression calling an associated function of an std type.
5154 // Associated functions cannot be resolved through the normal `std_path` function,
5155 // as they are resolved differently and so cannot use `expr_call_std_path`.
5157 // This function accepts the path component (`ty_path_components`) separately from
5158 // the name of the associated function (`assoc_fn_name`) in order to facilitate
5159 // separate resolution of the type and creation of a path referring to its associated
5161 fn expr_call_std_assoc_fn(
5163 ty_path_id: hir::HirId,
5165 ty_path_components: &[Symbol],
5166 assoc_fn_name: &str,
5167 args: hir::HirVec<hir::Expr>,
5168 ) -> hir::ExprKind {
5169 let ty_path = P(self.std_path(span, ty_path_components, None, false));
5170 let ty = P(self.ty_path(ty_path_id, span, hir::QPath::Resolved(None, ty_path)));
5171 let fn_seg = P(hir::PathSegment::from_ident(Ident::from_str(assoc_fn_name)));
5172 let fn_path = hir::QPath::TypeRelative(ty, fn_seg);
5173 let fn_expr = P(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
5174 hir::ExprKind::Call(fn_expr, args)
5177 fn expr_ident(&mut self, span: Span, ident: Ident, binding: hir::HirId) -> hir::Expr {
5178 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
5181 fn expr_ident_with_attrs(
5185 binding: hir::HirId,
5186 attrs: ThinVec<Attribute>,
5188 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
5192 res: Res::Local(binding),
5193 segments: hir_vec![hir::PathSegment::from_ident(ident)],
5197 self.expr(span, expr_path, attrs)
5200 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
5201 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
5207 components: &[Symbol],
5208 params: Option<P<hir::GenericArgs>>,
5209 attrs: ThinVec<Attribute>,
5211 let path = self.std_path(span, components, params, true);
5214 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
5219 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
5221 /// In terms of drop order, it has the same effect as wrapping `expr` in
5222 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
5224 /// The drop order can be important in e.g. `if expr { .. }`.
5229 attrs: ThinVec<Attribute>
5231 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
5238 arms: hir::HirVec<hir::Arm>,
5239 source: hir::MatchSource,
5241 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
5244 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
5245 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
5248 fn expr_unit(&mut self, sp: Span) -> hir::Expr {
5249 self.expr_tuple(sp, hir_vec![])
5252 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> hir::Expr {
5253 self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new())
5256 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
5258 hir_id: self.next_id(),
5265 fn stmt(&mut self, span: Span, node: hir::StmtKind) -> hir::Stmt {
5266 hir::Stmt { span, node, hir_id: self.next_id() }
5272 init: Option<P<hir::Expr>>,
5274 source: hir::LocalSource,
5276 let local = hir::Local {
5280 hir_id: self.next_id(),
5283 attrs: ThinVec::new()
5285 self.stmt(span, hir::StmtKind::Local(P(local)))
5288 fn expr_block_empty(&mut self, span: Span) -> hir::Expr {
5289 let blk = self.block_all(span, hir_vec![], None);
5290 self.expr_block(P(blk), ThinVec::new())
5293 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
5294 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
5300 stmts: hir::HirVec<hir::Stmt>,
5301 expr: Option<P<hir::Expr>>,
5306 hir_id: self.next_id(),
5307 rules: hir::DefaultBlock,
5309 targeted_by_break: false,
5313 fn expr_unsafe(&mut self, expr: P<hir::Expr>) -> hir::Expr {
5314 let hir_id = self.next_id();
5315 let span = expr.span;
5318 hir::ExprKind::Block(P(hir::Block {
5322 rules: hir::UnsafeBlock(hir::CompilerGenerated),
5324 targeted_by_break: false,
5330 /// Constructs a `true` or `false` literal pattern.
5331 fn pat_bool(&mut self, span: Span, val: bool) -> P<hir::Pat> {
5332 let lit = Spanned { span, node: LitKind::Bool(val) };
5333 let expr = self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new());
5334 self.pat(span, hir::PatKind::Lit(P(expr)))
5337 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5338 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![pat])
5341 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5342 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![pat])
5345 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5346 self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![pat])
5349 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
5350 self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], hir_vec![])
5356 components: &[Symbol],
5357 subpats: hir::HirVec<P<hir::Pat>>,
5359 let path = self.std_path(span, components, None, true);
5360 let qpath = hir::QPath::Resolved(None, P(path));
5361 let pt = if subpats.is_empty() {
5362 hir::PatKind::Path(qpath)
5364 hir::PatKind::TupleStruct(qpath, subpats, None)
5369 fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<hir::Pat>, hir::HirId) {
5370 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
5373 fn pat_ident_binding_mode(
5377 bm: hir::BindingAnnotation,
5378 ) -> (P<hir::Pat>, hir::HirId) {
5379 let hir_id = self.next_id();
5384 node: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
5391 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
5392 self.pat(span, hir::PatKind::Wild)
5395 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
5397 hir_id: self.next_id(),
5403 /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when
5404 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
5405 /// The path is also resolved according to `is_value`.
5409 components: &[Symbol],
5410 params: Option<P<hir::GenericArgs>>,
5413 let mut path = self.resolver
5414 .resolve_str_path(span, self.crate_root, components, is_value);
5415 path.segments.last_mut().unwrap().args = params;
5417 for seg in path.segments.iter_mut() {
5418 if seg.hir_id.is_some() {
5419 seg.hir_id = Some(self.next_id());
5425 fn ty_path(&mut self, mut hir_id: hir::HirId, span: Span, qpath: hir::QPath) -> hir::Ty {
5426 let node = match qpath {
5427 hir::QPath::Resolved(None, path) => {
5428 // Turn trait object paths into `TyKind::TraitObject` instead.
5430 Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
5431 let principal = hir::PolyTraitRef {
5432 bound_generic_params: hir::HirVec::new(),
5433 trait_ref: hir::TraitRef {
5434 path: path.and_then(|path| path),
5440 // The original ID is taken by the `PolyTraitRef`,
5441 // so the `Ty` itself needs a different one.
5442 hir_id = self.next_id();
5443 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
5445 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
5448 _ => hir::TyKind::Path(qpath),
5457 /// Invoked to create the lifetime argument for a type `&T`
5458 /// with no explicit lifetime.
5459 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
5460 match self.anonymous_lifetime_mode {
5461 // Intercept when we are in an impl header or async fn and introduce an in-band
5463 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
5465 AnonymousLifetimeMode::CreateParameter => {
5466 let fresh_name = self.collect_fresh_in_band_lifetime(span);
5468 hir_id: self.next_id(),
5470 name: hir::LifetimeName::Param(fresh_name),
5474 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5476 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5478 AnonymousLifetimeMode::Replace(replacement) => {
5479 self.new_replacement_lifetime(replacement, span)
5484 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
5485 /// return a "error lifetime".
5486 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
5487 let (id, msg, label) = match id {
5488 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
5491 self.sess.next_node_id(),
5492 "`&` without an explicit lifetime name cannot be used here",
5493 "explicit lifetime name needed here",
5497 let mut err = struct_span_err!(
5504 err.span_label(span, label);
5507 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5510 /// Invoked to create the lifetime argument(s) for a path like
5511 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
5512 /// sorts of cases are deprecated. This may therefore report a warning or an
5513 /// error, depending on the mode.
5514 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
5516 .map(|_| self.elided_path_lifetime(span))
5520 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
5521 match self.anonymous_lifetime_mode {
5522 AnonymousLifetimeMode::CreateParameter => {
5523 // We should have emitted E0726 when processing this path above
5524 self.sess.delay_span_bug(
5526 "expected 'implicit elided lifetime not allowed' error",
5528 let id = self.sess.next_node_id();
5529 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5531 // This is the normal case.
5532 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5534 AnonymousLifetimeMode::Replace(replacement) => {
5535 self.new_replacement_lifetime(replacement, span)
5538 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5542 /// Invoked to create the lifetime argument(s) for an elided trait object
5543 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
5544 /// when the bound is written, even if it is written with `'_` like in
5545 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
5546 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
5547 match self.anonymous_lifetime_mode {
5548 // NB. We intentionally ignore the create-parameter mode here.
5549 // and instead "pass through" to resolve-lifetimes, which will apply
5550 // the object-lifetime-defaulting rules. Elided object lifetime defaults
5551 // do not act like other elided lifetimes. In other words, given this:
5553 // impl Foo for Box<dyn Debug>
5555 // we do not introduce a fresh `'_` to serve as the bound, but instead
5556 // ultimately translate to the equivalent of:
5558 // impl Foo for Box<dyn Debug + 'static>
5560 // `resolve_lifetime` has the code to make that happen.
5561 AnonymousLifetimeMode::CreateParameter => {}
5563 AnonymousLifetimeMode::ReportError => {
5564 // ReportError applies to explicit use of `'_`.
5567 // This is the normal case.
5568 AnonymousLifetimeMode::PassThrough => {}
5570 // We don't need to do any replacement here as this lifetime
5571 // doesn't refer to an elided lifetime elsewhere in the function
5573 AnonymousLifetimeMode::Replace(_) => {}
5576 self.new_implicit_lifetime(span)
5579 fn new_replacement_lifetime(
5581 replacement: LtReplacement,
5583 ) -> hir::Lifetime {
5584 let hir_id = self.next_id();
5585 self.replace_elided_lifetime(hir_id, span, replacement)
5588 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
5590 hir_id: self.next_id(),
5592 name: hir::LifetimeName::Implicit,
5596 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
5597 self.sess.buffer_lint_with_diagnostic(
5598 builtin::BARE_TRAIT_OBJECTS,
5601 "trait objects without an explicit `dyn` are deprecated",
5602 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
5606 fn wrap_in_try_constructor(
5610 unstable_span: Span,
5612 let path = &[sym::ops, sym::Try, method];
5613 let from_err = P(self.expr_std_path(unstable_span, path, None,
5615 P(self.expr_call(e.span, from_err, hir_vec![e]))
5622 ) -> hir::ExprKind {
5626 // let mut pinned = <expr>;
5628 // match ::std::future::poll_with_tls_context(unsafe {
5629 // ::std::pin::Pin::new_unchecked(&mut pinned)
5631 // ::std::task::Poll::Ready(result) => break result,
5632 // ::std::task::Poll::Pending => {},
5637 if !self.is_async_body {
5638 let mut err = struct_span_err!(
5642 "`await` is only allowed inside `async` functions and blocks"
5644 err.span_label(await_span, "only allowed inside `async` functions and blocks");
5645 if let Some(item_sp) = self.current_item {
5646 err.span_label(item_sp, "this is not `async`");
5649 return hir::ExprKind::Err;
5651 let span = self.mark_span_with_reason(
5652 CompilerDesugaringKind::Await,
5656 let gen_future_span = self.mark_span_with_reason(
5657 CompilerDesugaringKind::Await,
5659 Some(vec![sym::gen_future].into()),
5662 // let mut pinned = <expr>;
5663 let expr = P(self.lower_expr(expr));
5664 let pinned_ident = Ident::with_empty_ctxt(sym::pinned);
5665 let (pinned_pat, pinned_pat_hid) = self.pat_ident_binding_mode(
5668 hir::BindingAnnotation::Mutable,
5670 let pinned_let = self.stmt_let_pat(
5674 hir::LocalSource::AwaitDesugar,
5677 // ::std::future::poll_with_tls_context(unsafe {
5678 // ::std::pin::Pin::new_unchecked(&mut pinned)
5681 let pinned = P(self.expr_ident(span, pinned_ident, pinned_pat_hid));
5682 let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
5683 let pin_ty_id = self.next_id();
5684 let new_unchecked_expr_kind = self.expr_call_std_assoc_fn(
5687 &[sym::pin, sym::Pin],
5689 hir_vec![ref_mut_pinned],
5691 let new_unchecked = P(self.expr(span, new_unchecked_expr_kind, ThinVec::new()));
5692 let unsafe_expr = self.expr_unsafe(new_unchecked);
5693 P(self.expr_call_std_path(
5695 &[sym::future, sym::poll_with_tls_context],
5696 hir_vec![unsafe_expr],
5700 // `::std::task::Poll::Ready(result) => break result`
5701 let loop_node_id = self.sess.next_node_id();
5702 let loop_hir_id = self.lower_node_id(loop_node_id);
5704 let x_ident = Ident::with_empty_ctxt(sym::result);
5705 let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
5706 let x_expr = P(self.expr_ident(span, x_ident, x_pat_hid));
5707 let ready_pat = self.pat_std_enum(
5709 &[sym::task, sym::Poll, sym::Ready],
5712 let break_x = self.with_loop_scope(loop_node_id, |this| {
5713 let expr_break = hir::ExprKind::Break(
5714 this.lower_loop_destination(None),
5717 P(this.expr(await_span, expr_break, ThinVec::new()))
5719 self.arm(hir_vec![ready_pat], break_x)
5722 // `::std::task::Poll::Pending => {}`
5724 let pending_pat = self.pat_std_enum(
5726 &[sym::task, sym::Poll, sym::Pending],
5729 let empty_block = P(self.expr_block_empty(span));
5730 self.arm(hir_vec![pending_pat], empty_block)
5734 let match_expr = P(self.expr_match(
5737 hir_vec![ready_arm, pending_arm],
5738 hir::MatchSource::AwaitDesugar,
5740 self.stmt(span, hir::StmtKind::Expr(match_expr))
5744 let unit = self.expr_unit(span);
5745 let yield_expr = P(self.expr(
5747 hir::ExprKind::Yield(P(unit)),
5750 self.stmt(span, hir::StmtKind::Expr(yield_expr))
5753 let loop_block = P(self.block_all(
5755 hir_vec![match_stmt, yield_stmt],
5759 let loop_expr = P(hir::Expr {
5760 hir_id: loop_hir_id,
5761 node: hir::ExprKind::Loop(
5764 hir::LoopSource::Loop,
5767 attrs: ThinVec::new(),
5770 hir::ExprKind::Block(
5771 P(self.block_all(span, hir_vec![pinned_let], Some(loop_expr))),
5777 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5778 // Sorting by span ensures that we get things in order within a
5779 // file, and also puts the files in a sensible order.
5780 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5781 body_ids.sort_by_key(|b| bodies[b].value.span);
5785 /// Checks if the specified expression is a built-in range literal.
5786 /// (See: `LoweringContext::lower_expr()`).
5787 pub fn is_range_literal(sess: &Session, expr: &hir::Expr) -> bool {
5788 use hir::{Path, QPath, ExprKind, TyKind};
5790 // Returns whether the given path represents a (desugared) range,
5791 // either in std or core, i.e. has either a `::std::ops::Range` or
5792 // `::core::ops::Range` prefix.
5793 fn is_range_path(path: &Path) -> bool {
5794 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.as_str().to_string()).collect();
5795 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
5797 // "{{root}}" is the equivalent of `::` prefix in `Path`.
5798 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
5799 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
5805 // Check whether a span corresponding to a range expression is a
5806 // range literal, rather than an explicit struct or `new()` call.
5807 fn is_lit(sess: &Session, span: &Span) -> bool {
5808 let source_map = sess.source_map();
5809 let end_point = source_map.end_point(*span);
5811 if let Ok(end_string) = source_map.span_to_snippet(end_point) {
5812 !(end_string.ends_with("}") || end_string.ends_with(")"))
5819 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
5820 ExprKind::Struct(ref qpath, _, _) => {
5821 if let QPath::Resolved(None, ref path) = **qpath {
5822 return is_range_path(&path) && is_lit(sess, &expr.span);
5826 // `..` desugars to its struct path.
5827 ExprKind::Path(QPath::Resolved(None, ref path)) => {
5828 return is_range_path(&path) && is_lit(sess, &expr.span);
5831 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
5832 ExprKind::Call(ref func, _) => {
5833 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.node {
5834 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.node {
5835 let new_call = segment.ident.as_str() == "new";
5836 return is_range_path(&path) && is_lit(sess, &expr.span) && new_call;