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;
54 use std::collections::{BTreeSet, BTreeMap};
56 use smallvec::SmallVec;
61 use syntax::ext::hygiene::Mark;
62 use syntax::print::pprust;
64 use syntax::source_map::{respan, CompilerDesugaringKind, Spanned};
65 use syntax::source_map::CompilerDesugaringKind::IfTemporary;
66 use syntax::std_inject;
67 use syntax::symbol::{kw, sym, Symbol};
68 use syntax::tokenstream::{TokenStream, TokenTree};
69 use syntax::parse::token::Token;
70 use syntax::visit::{self, Visitor};
73 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
75 pub struct LoweringContext<'a> {
76 crate_root: Option<Symbol>,
78 /// Used to assign ids to HIR nodes that do not directly correspond to an AST node.
81 cstore: &'a dyn CrateStore,
83 resolver: &'a mut dyn Resolver,
85 /// The items being lowered are collected here.
86 items: BTreeMap<hir::HirId, hir::Item>,
88 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
89 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
90 bodies: BTreeMap<hir::BodyId, hir::Body>,
91 exported_macros: Vec<hir::MacroDef>,
93 trait_impls: BTreeMap<DefId, Vec<hir::HirId>>,
95 modules: BTreeMap<NodeId, hir::ModuleItems>,
100 /// Used to get the current `fn`'s def span to point to when using `await`
101 /// outside of an `async fn`.
102 current_item: Option<Span>,
104 catch_scopes: Vec<NodeId>,
105 loop_scopes: Vec<NodeId>,
106 is_in_loop_condition: bool,
107 is_in_trait_impl: bool,
109 /// What to do when we encounter either an "anonymous lifetime
110 /// reference". The term "anonymous" is meant to encompass both
111 /// `'_` lifetimes as well as fully elided cases where nothing is
112 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
113 anonymous_lifetime_mode: AnonymousLifetimeMode,
115 /// Used to create lifetime definitions from in-band lifetime usages.
116 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
117 /// When a named lifetime is encountered in a function or impl header and
118 /// has not been defined
119 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
120 /// to this list. The results of this list are then added to the list of
121 /// lifetime definitions in the corresponding impl or function generics.
122 lifetimes_to_define: Vec<(Span, ParamName)>,
124 /// Whether or not in-band lifetimes are being collected. This is used to
125 /// indicate whether or not we're in a place where new lifetimes will result
126 /// in in-band lifetime definitions, such a function or an impl header,
127 /// including implicit lifetimes from `impl_header_lifetime_elision`.
128 is_collecting_in_band_lifetimes: bool,
130 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
131 /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
132 /// against this list to see if it is already in-scope, or if a definition
133 /// needs to be created for it.
134 in_scope_lifetimes: Vec<Ident>,
136 current_module: NodeId,
138 type_def_lifetime_params: DefIdMap<usize>,
140 current_hir_id_owner: Vec<(DefIndex, u32)>,
141 item_local_id_counters: NodeMap<u32>,
142 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
146 /// Resolve a path generated by the lowerer when expanding `for`, `if let`, etc.
153 /// Obtain resolution for a `NodeId` with a single resolution.
154 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
156 /// Obtain per-namespace resolutions for `use` statement with the given `NoedId`.
157 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
159 /// Obtain resolution for a label with the given `NodeId`.
160 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
162 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
163 /// This should only return `None` during testing.
164 fn definitions(&mut self) -> &mut Definitions;
166 /// Given suffix `["b", "c", "d"]`, creates a HIR path for `[::crate_root]::b::c::d` and
167 /// resolves it based on `is_value`.
171 crate_root: Option<Symbol>,
172 components: &[Symbol],
178 enum ImplTraitContext<'a> {
179 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
180 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
181 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
183 /// Newly generated parameters should be inserted into the given `Vec`.
184 Universal(&'a mut Vec<hir::GenericParam>),
186 /// Treat `impl Trait` as shorthand for a new existential parameter.
187 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
188 /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
190 /// We optionally store a `DefId` for the parent item here so we can look up necessary
191 /// information later. It is `None` when no information about the context should be stored,
192 /// e.g., for consts and statics.
193 Existential(Option<DefId>),
195 /// `impl Trait` is not accepted in this position.
196 Disallowed(ImplTraitPosition),
199 /// Position in which `impl Trait` is disallowed. Used for error reporting.
200 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
201 enum ImplTraitPosition {
206 impl<'a> ImplTraitContext<'a> {
208 fn disallowed() -> Self {
209 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
212 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
213 use self::ImplTraitContext::*;
215 Universal(params) => Universal(params),
216 Existential(did) => Existential(*did),
217 Disallowed(pos) => Disallowed(*pos),
224 cstore: &dyn CrateStore,
225 dep_graph: &DepGraph,
227 resolver: &mut dyn Resolver,
229 // We're constructing the HIR here; we don't care what we will
230 // read, since we haven't even constructed the *input* to
232 dep_graph.assert_ignored();
235 crate_root: std_inject::injected_crate_name().map(Symbol::intern),
239 items: BTreeMap::new(),
240 trait_items: BTreeMap::new(),
241 impl_items: BTreeMap::new(),
242 bodies: BTreeMap::new(),
243 trait_impls: BTreeMap::new(),
244 modules: BTreeMap::new(),
245 exported_macros: Vec::new(),
246 catch_scopes: Vec::new(),
247 loop_scopes: Vec::new(),
248 is_in_loop_condition: false,
249 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
250 type_def_lifetime_params: Default::default(),
251 current_module: CRATE_NODE_ID,
252 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
253 item_local_id_counters: Default::default(),
254 node_id_to_hir_id: IndexVec::new(),
256 is_async_body: false,
258 is_in_trait_impl: false,
259 lifetimes_to_define: Vec::new(),
260 is_collecting_in_band_lifetimes: false,
261 in_scope_lifetimes: Vec::new(),
265 #[derive(Copy, Clone, PartialEq)]
267 /// Any path in a type context.
269 /// The `module::Type` in `module::Type::method` in an expression.
273 enum ParenthesizedGenericArgs {
279 /// What to do when we encounter an **anonymous** lifetime
280 /// reference. Anonymous lifetime references come in two flavors. You
281 /// have implicit, or fully elided, references to lifetimes, like the
282 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
283 /// or `Ref<'_, T>`. These often behave the same, but not always:
285 /// - certain usages of implicit references are deprecated, like
286 /// `Ref<T>`, and we sometimes just give hard errors in those cases
288 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
289 /// the same as `Box<dyn Foo + '_>`.
291 /// We describe the effects of the various modes in terms of three cases:
293 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
294 /// of a `&` (e.g., the missing lifetime in something like `&T`)
295 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
296 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
297 /// elided bounds follow special rules. Note that this only covers
298 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
299 /// '_>` is a case of "modern" elision.
300 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
301 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
302 /// non-deprecated equivalent.
304 /// Currently, the handling of lifetime elision is somewhat spread out
305 /// between HIR lowering and -- as described below -- the
306 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
307 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
308 /// everything into HIR lowering.
309 #[derive(Copy, Clone)]
310 enum AnonymousLifetimeMode {
311 /// For **Modern** cases, create a new anonymous region parameter
312 /// and reference that.
314 /// For **Dyn Bound** cases, pass responsibility to
315 /// `resolve_lifetime` code.
317 /// For **Deprecated** cases, report an error.
320 /// Give a hard error when either `&` or `'_` is written. Used to
321 /// rule out things like `where T: Foo<'_>`. Does not imply an
322 /// error on default object bounds (e.g., `Box<dyn Foo>`).
325 /// Pass responsibility to `resolve_lifetime` code for all cases.
328 /// Used in the return types of `async fn` where there exists
329 /// exactly one argument-position elided lifetime.
331 /// In `async fn`, we lower the arguments types using the `CreateParameter`
332 /// mode, meaning that non-`dyn` elided lifetimes are assigned a fresh name.
333 /// If any corresponding elided lifetimes appear in the output, we need to
334 /// replace them with references to the fresh name assigned to the corresponding
335 /// elided lifetime in the arguments.
337 /// For **Modern cases**, replace the anonymous parameter with a
338 /// reference to a specific freshly-named lifetime that was
339 /// introduced in argument
341 /// For **Dyn Bound** cases, pass responsibility to
342 /// `resole_lifetime` code.
343 Replace(LtReplacement),
346 /// The type of elided lifetime replacement to perform on `async fn` return types.
347 #[derive(Copy, Clone)]
349 /// Fresh name introduced by the single non-dyn elided lifetime
350 /// in the arguments of the async fn.
353 /// There is no single non-dyn elided lifetime because no lifetimes
354 /// appeared in the arguments.
357 /// There is no single non-dyn elided lifetime because multiple
358 /// lifetimes appeared in the arguments.
362 /// Calculates the `LtReplacement` to use for elided lifetimes in the return
363 /// type based on the fresh elided lifetimes introduced in argument position.
364 fn get_elided_lt_replacement(arg_position_lifetimes: &[(Span, ParamName)]) -> LtReplacement {
365 match arg_position_lifetimes {
366 [] => LtReplacement::NoLifetimes,
367 [(_span, param)] => LtReplacement::Some(*param),
368 _ => LtReplacement::MultipleLifetimes,
372 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[NodeId; 1]> }
374 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
375 fn visit_ty(&mut self, ty: &'a Ty) {
381 TyKind::ImplTrait(id, _) => self.ids.push(id),
384 visit::walk_ty(self, ty);
387 fn visit_path_segment(
390 path_segment: &'v PathSegment,
392 if let Some(ref p) = path_segment.args {
393 if let GenericArgs::Parenthesized(_) = **p {
397 visit::walk_path_segment(self, path_span, path_segment)
401 impl<'a> LoweringContext<'a> {
402 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
403 /// Full-crate AST visitor that inserts into a fresh
404 /// `LoweringContext` any information that may be
405 /// needed from arbitrary locations in the crate,
406 /// e.g., the number of lifetime generic parameters
407 /// declared for every type and trait definition.
408 struct MiscCollector<'lcx, 'interner: 'lcx> {
409 lctx: &'lcx mut LoweringContext<'interner>,
410 hir_id_owner: Option<NodeId>,
413 impl MiscCollector<'_, '_> {
414 fn allocate_use_tree_hir_id_counters(
420 UseTreeKind::Simple(_, id1, id2) => {
421 for &id in &[id1, id2] {
422 self.lctx.resolver.definitions().create_def_with_parent(
429 self.lctx.allocate_hir_id_counter(id);
432 UseTreeKind::Glob => (),
433 UseTreeKind::Nested(ref trees) => {
434 for &(ref use_tree, id) in trees {
435 let hir_id = self.lctx.allocate_hir_id_counter(id);
436 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
442 fn with_hir_id_owner<F, T>(&mut self, owner: Option<NodeId>, f: F) -> T
444 F: FnOnce(&mut Self) -> T,
446 let old = mem::replace(&mut self.hir_id_owner, owner);
448 self.hir_id_owner = old;
453 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
454 fn visit_pat(&mut self, p: &'lcx Pat) {
456 // Doesn't generate a HIR node
457 PatKind::Paren(..) => {},
459 if let Some(owner) = self.hir_id_owner {
460 self.lctx.lower_node_id_with_owner(p.id, owner);
465 visit::walk_pat(self, p)
468 fn visit_fn(&mut self, fk: visit::FnKind<'lcx>, fd: &'lcx FnDecl, s: Span, _: NodeId) {
469 if fk.header().map(|h| h.asyncness.node.is_async()).unwrap_or(false) {
470 // Don't visit the original pattern for async functions as it will be
472 for arg in &fd.inputs {
473 if let ArgSource::AsyncFn(pat) = &arg.source { self.visit_pat(pat); }
474 self.visit_ty(&arg.ty)
476 self.visit_fn_ret_ty(&fd.output);
479 visit::FnKind::ItemFn(_, decl, _, body) => {
480 self.visit_fn_header(decl);
481 self.visit_block(body)
483 visit::FnKind::Method(_, sig, _, body) => {
484 self.visit_fn_header(&sig.header);
485 self.visit_block(body)
487 visit::FnKind::Closure(body) => self.visit_expr(body),
490 visit::walk_fn(self, fk, fd, s)
494 fn visit_item(&mut self, item: &'lcx Item) {
495 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
498 ItemKind::Struct(_, ref generics)
499 | ItemKind::Union(_, ref generics)
500 | ItemKind::Enum(_, ref generics)
501 | ItemKind::Ty(_, ref generics)
502 | ItemKind::Existential(_, ref generics)
503 | ItemKind::Trait(_, _, ref generics, ..) => {
504 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
508 .filter(|param| match param.kind {
509 ast::GenericParamKind::Lifetime { .. } => true,
513 self.lctx.type_def_lifetime_params.insert(def_id, count);
515 ItemKind::Use(ref use_tree) => {
516 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
521 self.with_hir_id_owner(Some(item.id), |this| {
522 visit::walk_item(this, item);
526 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
527 self.lctx.allocate_hir_id_counter(item.id);
530 TraitItemKind::Method(_, None) => {
531 // Ignore patterns in trait methods without bodies
532 self.with_hir_id_owner(None, |this| {
533 visit::walk_trait_item(this, item)
536 _ => self.with_hir_id_owner(Some(item.id), |this| {
537 visit::walk_trait_item(this, item);
542 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
543 self.lctx.allocate_hir_id_counter(item.id);
544 self.with_hir_id_owner(Some(item.id), |this| {
545 visit::walk_impl_item(this, item);
549 fn visit_foreign_item(&mut self, i: &'lcx ForeignItem) {
550 // Ignore patterns in foreign items
551 self.with_hir_id_owner(None, |this| {
552 visit::walk_foreign_item(this, i)
556 fn visit_ty(&mut self, t: &'lcx Ty) {
558 // Mirrors the case in visit::walk_ty
559 TyKind::BareFn(ref f) => {
565 // Mirrors visit::walk_fn_decl
566 for argument in &f.decl.inputs {
567 // We don't lower the ids of argument patterns
568 self.with_hir_id_owner(None, |this| {
569 this.visit_pat(&argument.pat);
571 self.visit_ty(&argument.ty)
573 self.visit_fn_ret_ty(&f.decl.output)
575 _ => visit::walk_ty(self, t),
580 struct ItemLowerer<'lcx, 'interner: 'lcx> {
581 lctx: &'lcx mut LoweringContext<'interner>,
584 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
585 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
587 F: FnOnce(&mut Self),
589 let old = self.lctx.is_in_trait_impl;
590 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
596 self.lctx.is_in_trait_impl = old;
600 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
601 fn visit_mod(&mut self, m: &'lcx Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
602 self.lctx.modules.insert(n, hir::ModuleItems {
603 items: BTreeSet::new(),
604 trait_items: BTreeSet::new(),
605 impl_items: BTreeSet::new(),
608 let old = self.lctx.current_module;
609 self.lctx.current_module = n;
610 visit::walk_mod(self, m);
611 self.lctx.current_module = old;
614 fn visit_item(&mut self, item: &'lcx Item) {
615 let mut item_hir_id = None;
616 self.lctx.with_hir_id_owner(item.id, |lctx| {
617 if let Some(hir_item) = lctx.lower_item(item) {
618 item_hir_id = Some(hir_item.hir_id);
619 lctx.insert_item(hir_item);
623 if let Some(hir_id) = item_hir_id {
624 let item_generics = match self.lctx.items.get(&hir_id).unwrap().node {
625 hir::ItemKind::Impl(_, _, _, ref generics, ..)
626 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
627 generics.params.clone()
632 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
633 let this = &mut ItemLowerer { lctx: this };
634 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
635 this.with_trait_impl_ref(opt_trait_ref, |this| {
636 visit::walk_item(this, item)
639 visit::walk_item(this, item);
645 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
646 self.lctx.with_hir_id_owner(item.id, |lctx| {
647 let hir_item = lctx.lower_trait_item(item);
648 let id = hir::TraitItemId { hir_id: hir_item.hir_id };
649 lctx.trait_items.insert(id, hir_item);
650 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
653 visit::walk_trait_item(self, item);
656 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
657 self.lctx.with_hir_id_owner(item.id, |lctx| {
658 let hir_item = lctx.lower_impl_item(item);
659 let id = hir::ImplItemId { hir_id: hir_item.hir_id };
660 lctx.impl_items.insert(id, hir_item);
661 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
663 visit::walk_impl_item(self, item);
667 self.lower_node_id(CRATE_NODE_ID);
668 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
670 visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
671 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
673 let module = self.lower_mod(&c.module);
674 let attrs = self.lower_attrs(&c.attrs);
675 let body_ids = body_ids(&self.bodies);
679 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
685 exported_macros: hir::HirVec::from(self.exported_macros),
687 trait_items: self.trait_items,
688 impl_items: self.impl_items,
691 trait_impls: self.trait_impls,
692 modules: self.modules,
696 fn insert_item(&mut self, item: hir::Item) {
697 let id = item.hir_id;
698 // FIXME: Use debug_asset-rt
699 assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
700 self.items.insert(id, item);
701 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
704 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
705 // Setup the counter if needed
706 self.item_local_id_counters.entry(owner).or_insert(0);
707 // Always allocate the first `HirId` for the owner itself.
708 let lowered = self.lower_node_id_with_owner(owner, owner);
709 debug_assert_eq!(lowered.local_id.as_u32(), 0);
713 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> hir::HirId
715 F: FnOnce(&mut Self) -> hir::HirId,
717 if ast_node_id == DUMMY_NODE_ID {
718 return hir::DUMMY_HIR_ID;
721 let min_size = ast_node_id.as_usize() + 1;
723 if min_size > self.node_id_to_hir_id.len() {
724 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
727 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
729 if existing_hir_id == hir::DUMMY_HIR_ID {
730 // Generate a new `HirId`.
731 let hir_id = alloc_hir_id(self);
732 self.node_id_to_hir_id[ast_node_id] = hir_id;
740 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
742 F: FnOnce(&mut Self) -> T,
744 let counter = self.item_local_id_counters
745 .insert(owner, HIR_ID_COUNTER_LOCKED)
746 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
747 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
748 self.current_hir_id_owner.push((def_index, counter));
750 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
752 debug_assert!(def_index == new_def_index);
753 debug_assert!(new_counter >= counter);
755 let prev = self.item_local_id_counters
756 .insert(owner, new_counter)
758 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
762 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
763 /// the `LoweringContext`'s `NodeId => HirId` map.
764 /// Take care not to call this method if the resulting `HirId` is then not
765 /// actually used in the HIR, as that would trigger an assertion in the
766 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
767 /// properly. Calling the method twice with the same `NodeId` is fine though.
768 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
769 self.lower_node_id_generic(ast_node_id, |this| {
770 let &mut (def_index, ref mut local_id_counter) =
771 this.current_hir_id_owner.last_mut().unwrap();
772 let local_id = *local_id_counter;
773 *local_id_counter += 1;
776 local_id: hir::ItemLocalId::from_u32(local_id),
781 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
782 self.lower_node_id_generic(ast_node_id, |this| {
783 let local_id_counter = this
784 .item_local_id_counters
786 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
787 let local_id = *local_id_counter;
789 // We want to be sure not to modify the counter in the map while it
790 // is also on the stack. Otherwise we'll get lost updates when writing
791 // back from the stack to the map.
792 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
794 *local_id_counter += 1;
798 .opt_def_index(owner)
799 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
800 that do not belong to the current owner");
804 local_id: hir::ItemLocalId::from_u32(local_id),
809 fn record_body(&mut self, value: hir::Expr, arguments: HirVec<hir::Arg>) -> hir::BodyId {
810 if self.is_generator && self.is_async_body {
815 "`async` generators are not yet supported",
817 self.sess.abort_if_errors();
819 let body = hir::Body {
820 is_generator: self.is_generator || self.is_async_body,
825 self.bodies.insert(id, body);
829 fn next_id(&mut self) -> hir::HirId {
830 self.lower_node_id(self.sess.next_node_id())
833 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
835 self.lower_node_id_generic(id, |_| {
836 panic!("expected node_id to be lowered already for res {:#?}", res)
841 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
842 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
843 if pr.unresolved_segments() != 0 {
844 bug!("path not fully resolved: {:?}", pr);
850 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
851 self.resolver.get_import_res(id).present_items()
854 fn diagnostic(&self) -> &errors::Handler {
855 self.sess.diagnostic()
858 fn with_anonymous_lifetime_mode<R>(
860 anonymous_lifetime_mode: AnonymousLifetimeMode,
861 op: impl FnOnce(&mut Self) -> R,
863 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
864 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
865 let result = op(self);
866 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
870 /// Creates a new hir::GenericParam for every new lifetime and
871 /// type parameter encountered while evaluating `f`. Definitions
872 /// are created with the parent provided. If no `parent_id` is
873 /// provided, no definitions will be returned.
875 /// Presuming that in-band lifetimes are enabled, then
876 /// `self.anonymous_lifetime_mode` will be updated to match the
877 /// argument while `f` is running (and restored afterwards).
878 fn collect_in_band_defs<T, F>(
881 anonymous_lifetime_mode: AnonymousLifetimeMode,
883 ) -> (Vec<hir::GenericParam>, T)
885 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
887 assert!(!self.is_collecting_in_band_lifetimes);
888 assert!(self.lifetimes_to_define.is_empty());
889 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
891 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
892 self.is_collecting_in_band_lifetimes = true;
894 let (in_band_ty_params, res) = f(self);
896 self.is_collecting_in_band_lifetimes = false;
897 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
899 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
901 let params = lifetimes_to_define
903 .map(|(span, hir_name)| self.lifetime_to_generic_param(
904 span, hir_name, parent_id.index,
906 .chain(in_band_ty_params.into_iter())
912 /// Converts a lifetime into a new generic parameter.
913 fn lifetime_to_generic_param(
917 parent_index: DefIndex,
918 ) -> hir::GenericParam {
919 let node_id = self.sess.next_node_id();
921 // Get the name we'll use to make the def-path. Note
922 // that collisions are ok here and this shouldn't
923 // really show up for end-user.
924 let (str_name, kind) = match hir_name {
925 ParamName::Plain(ident) => (
926 ident.as_interned_str(),
927 hir::LifetimeParamKind::InBand,
929 ParamName::Fresh(_) => (
930 kw::UnderscoreLifetime.as_interned_str(),
931 hir::LifetimeParamKind::Elided,
933 ParamName::Error => (
934 kw::UnderscoreLifetime.as_interned_str(),
935 hir::LifetimeParamKind::Error,
939 // Add a definition for the in-band lifetime def.
940 self.resolver.definitions().create_def_with_parent(
943 DefPathData::LifetimeNs(str_name),
949 hir_id: self.lower_node_id(node_id),
954 pure_wrt_drop: false,
955 kind: hir::GenericParamKind::Lifetime { kind }
959 /// When there is a reference to some lifetime `'a`, and in-band
960 /// lifetimes are enabled, then we want to push that lifetime into
961 /// the vector of names to define later. In that case, it will get
962 /// added to the appropriate generics.
963 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
964 if !self.is_collecting_in_band_lifetimes {
968 if !self.sess.features_untracked().in_band_lifetimes {
972 if self.in_scope_lifetimes.contains(&ident.modern()) {
976 let hir_name = ParamName::Plain(ident);
978 if self.lifetimes_to_define.iter()
979 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
983 self.lifetimes_to_define.push((ident.span, hir_name));
986 /// When we have either an elided or `'_` lifetime in an impl
987 /// header, we convert it to an in-band lifetime.
988 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
989 assert!(self.is_collecting_in_band_lifetimes);
990 let index = self.lifetimes_to_define.len();
991 let hir_name = ParamName::Fresh(index);
992 self.lifetimes_to_define.push((span, hir_name));
996 // Evaluates `f` with the lifetimes in `params` in-scope.
997 // This is used to track which lifetimes have already been defined, and
998 // which are new in-band lifetimes that need to have a definition created
1000 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
1002 F: FnOnce(&mut LoweringContext<'_>) -> T,
1004 let old_len = self.in_scope_lifetimes.len();
1005 let lt_def_names = params.iter().filter_map(|param| match param.kind {
1006 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
1009 self.in_scope_lifetimes.extend(lt_def_names);
1013 self.in_scope_lifetimes.truncate(old_len);
1017 // Same as the method above, but accepts `hir::GenericParam`s
1018 // instead of `ast::GenericParam`s.
1019 // This should only be used with generics that have already had their
1020 // in-band lifetimes added. In practice, this means that this function is
1021 // only used when lowering a child item of a trait or impl.
1022 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
1023 params: &HirVec<hir::GenericParam>,
1026 F: FnOnce(&mut LoweringContext<'_>) -> T,
1028 let old_len = self.in_scope_lifetimes.len();
1029 let lt_def_names = params.iter().filter_map(|param| match param.kind {
1030 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
1033 self.in_scope_lifetimes.extend(lt_def_names);
1037 self.in_scope_lifetimes.truncate(old_len);
1041 /// Appends in-band lifetime defs and argument-position `impl
1042 /// Trait` defs to the existing set of generics.
1044 /// Presuming that in-band lifetimes are enabled, then
1045 /// `self.anonymous_lifetime_mode` will be updated to match the
1046 /// argument while `f` is running (and restored afterwards).
1047 fn add_in_band_defs<F, T>(
1049 generics: &Generics,
1051 anonymous_lifetime_mode: AnonymousLifetimeMode,
1053 ) -> (hir::Generics, T)
1055 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
1057 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
1060 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
1061 let mut params = Vec::new();
1062 // Note: it is necessary to lower generics *before* calling `f`.
1063 // When lowering `async fn`, there's a final step when lowering
1064 // the return type that assumes that all in-scope lifetimes have
1065 // already been added to either `in_scope_lifetimes` or
1066 // `lifetimes_to_define`. If we swapped the order of these two,
1067 // in-band-lifetimes introduced by generics or where-clauses
1068 // wouldn't have been added yet.
1069 let generics = this.lower_generics(
1071 ImplTraitContext::Universal(&mut params),
1073 let res = f(this, &mut params);
1074 (params, (generics, res))
1079 lowered_generics.params = lowered_generics
1083 .chain(in_band_defs)
1086 (lowered_generics, res)
1089 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
1091 F: FnOnce(&mut LoweringContext<'_>) -> T,
1093 let len = self.catch_scopes.len();
1094 self.catch_scopes.push(catch_id);
1096 let result = f(self);
1099 self.catch_scopes.len(),
1100 "catch scopes should be added and removed in stack order"
1103 self.catch_scopes.pop().unwrap();
1110 capture_clause: CaptureBy,
1111 closure_node_id: NodeId,
1112 ret_ty: Option<&Ty>,
1114 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1115 ) -> hir::ExprKind {
1116 let prev_is_generator = mem::replace(&mut self.is_generator, false);
1117 let prev_is_async_body = mem::replace(&mut self.is_async_body, true);
1118 let output = match ret_ty {
1119 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
1120 None => FunctionRetTy::Default(span),
1127 // Lower the arguments before the body otherwise the body will call `lower_res` expecting
1128 // the argument to have been assigned an id already.
1129 let arguments = self.lower_args(Some(&decl));
1130 let body_expr = body(self);
1131 let body_id = self.record_body(body_expr, arguments);
1132 self.is_generator = prev_is_generator;
1133 self.is_async_body = prev_is_async_body;
1135 let capture_clause = self.lower_capture_clause(capture_clause);
1136 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
1137 let generator = hir::Expr {
1138 hir_id: self.lower_node_id(closure_node_id),
1139 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
1140 Some(hir::GeneratorMovability::Static)),
1142 attrs: ThinVec::new(),
1145 let unstable_span = self.sess.source_map().mark_span_with_reason(
1146 CompilerDesugaringKind::Async,
1148 Some(vec![sym::gen_future].into()),
1150 let gen_future = self.expr_std_path(
1151 unstable_span, &[sym::future, sym::from_generator], None, ThinVec::new());
1152 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
1155 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
1157 F: FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1159 let prev_generator = mem::replace(&mut self.is_generator, false);
1160 let prev_async = mem::replace(&mut self.is_async_body, false);
1161 let arguments = self.lower_args(decl);
1162 let result = f(self);
1163 let r = self.record_body(result, arguments);
1164 self.is_generator = prev_generator;
1165 self.is_async_body = prev_async;
1169 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
1171 F: FnOnce(&mut LoweringContext<'_>) -> T,
1173 // We're no longer in the base loop's condition; we're in another loop.
1174 let was_in_loop_condition = self.is_in_loop_condition;
1175 self.is_in_loop_condition = false;
1177 let len = self.loop_scopes.len();
1178 self.loop_scopes.push(loop_id);
1180 let result = f(self);
1183 self.loop_scopes.len(),
1184 "Loop scopes should be added and removed in stack order"
1187 self.loop_scopes.pop().unwrap();
1189 self.is_in_loop_condition = was_in_loop_condition;
1194 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
1196 F: FnOnce(&mut LoweringContext<'_>) -> T,
1198 let was_in_loop_condition = self.is_in_loop_condition;
1199 self.is_in_loop_condition = true;
1201 let result = f(self);
1203 self.is_in_loop_condition = was_in_loop_condition;
1208 fn with_new_scopes<T, F>(&mut self, f: F) -> T
1210 F: FnOnce(&mut LoweringContext<'_>) -> T,
1212 let was_in_loop_condition = self.is_in_loop_condition;
1213 self.is_in_loop_condition = false;
1215 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
1216 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
1218 self.catch_scopes = catch_scopes;
1219 self.loop_scopes = loop_scopes;
1221 self.is_in_loop_condition = was_in_loop_condition;
1226 fn def_key(&mut self, id: DefId) -> DefKey {
1228 self.resolver.definitions().def_key(id.index)
1230 self.cstore.def_key(id)
1234 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1235 label.map(|label| hir::Label {
1240 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1241 let target_id = match destination {
1243 if let Some(loop_id) = self.resolver.get_label_res(id) {
1244 Ok(self.lower_node_id(loop_id))
1246 Err(hir::LoopIdError::UnresolvedLabel)
1253 .map(|id| Ok(self.lower_node_id(id)))
1254 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1259 label: self.lower_label(destination.map(|(_, label)| label)),
1264 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1267 .map(|a| self.lower_attr(a))
1271 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1272 // Note that we explicitly do not walk the path. Since we don't really
1273 // lower attributes (we use the AST version) there is nowhere to keep
1274 // the `HirId`s. We don't actually need HIR version of attributes anyway.
1278 path: attr.path.clone(),
1279 tokens: self.lower_token_stream(attr.tokens.clone()),
1280 is_sugared_doc: attr.is_sugared_doc,
1285 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1288 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1292 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1294 TokenTree::Token(span, token) => self.lower_token(token, span),
1295 TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1298 self.lower_token_stream(tts),
1303 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1305 Token::Interpolated(nt) => {
1306 let tts = nt.to_tokenstream(&self.sess.parse_sess, span);
1307 self.lower_token_stream(tts)
1309 other => TokenTree::Token(span, other).into(),
1313 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1315 hir_id: self.next_id(),
1316 attrs: self.lower_attrs(&arm.attrs),
1317 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1318 guard: match arm.guard {
1319 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1322 body: P(self.lower_expr(&arm.body)),
1327 fn lower_ty_binding(&mut self, b: &TypeBinding,
1328 itctx: ImplTraitContext<'_>) -> hir::TypeBinding {
1330 hir_id: self.lower_node_id(b.id),
1332 ty: self.lower_ty(&b.ty, itctx),
1337 fn lower_generic_arg(&mut self,
1338 arg: &ast::GenericArg,
1339 itctx: ImplTraitContext<'_>)
1340 -> hir::GenericArg {
1342 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1343 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1344 ast::GenericArg::Const(ct) => {
1345 GenericArg::Const(ConstArg {
1346 value: self.lower_anon_const(&ct),
1347 span: ct.value.span,
1353 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1354 P(self.lower_ty_direct(t, itctx))
1357 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1358 let kind = match t.node {
1359 TyKind::Infer => hir::TyKind::Infer,
1360 TyKind::Err => hir::TyKind::Err,
1361 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1362 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1363 TyKind::Rptr(ref region, ref mt) => {
1364 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1365 let lifetime = match *region {
1366 Some(ref lt) => self.lower_lifetime(lt),
1367 None => self.elided_ref_lifetime(span),
1369 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1371 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1374 this.with_anonymous_lifetime_mode(
1375 AnonymousLifetimeMode::PassThrough,
1377 hir::TyKind::BareFn(P(hir::BareFnTy {
1378 generic_params: this.lower_generic_params(
1380 &NodeMap::default(),
1381 ImplTraitContext::disallowed(),
1383 unsafety: this.lower_unsafety(f.unsafety),
1385 decl: this.lower_fn_decl(&f.decl, None, false, None),
1386 arg_names: this.lower_fn_args_to_names(&f.decl),
1392 TyKind::Never => hir::TyKind::Never,
1393 TyKind::Tup(ref tys) => {
1394 hir::TyKind::Tup(tys.iter().map(|ty| {
1395 self.lower_ty_direct(ty, itctx.reborrow())
1398 TyKind::Paren(ref ty) => {
1399 return self.lower_ty_direct(ty, itctx);
1401 TyKind::Path(ref qself, ref path) => {
1402 let id = self.lower_node_id(t.id);
1403 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1404 let ty = self.ty_path(id, t.span, qpath);
1405 if let hir::TyKind::TraitObject(..) = ty.node {
1406 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1410 TyKind::ImplicitSelf => {
1411 let res = self.expect_full_res(t.id);
1412 let res = self.lower_res(res);
1413 hir::TyKind::Path(hir::QPath::Resolved(
1417 segments: hir_vec![hir::PathSegment::from_ident(
1418 Ident::with_empty_ctxt(kw::SelfUpper)
1424 TyKind::Array(ref ty, ref length) => {
1425 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1427 TyKind::Typeof(ref expr) => {
1428 hir::TyKind::Typeof(self.lower_anon_const(expr))
1430 TyKind::TraitObject(ref bounds, kind) => {
1431 let mut lifetime_bound = None;
1434 .filter_map(|bound| match *bound {
1435 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1436 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1438 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1439 GenericBound::Outlives(ref lifetime) => {
1440 if lifetime_bound.is_none() {
1441 lifetime_bound = Some(self.lower_lifetime(lifetime));
1447 let lifetime_bound =
1448 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1449 if kind != TraitObjectSyntax::Dyn {
1450 self.maybe_lint_bare_trait(t.span, t.id, false);
1452 hir::TyKind::TraitObject(bounds, lifetime_bound)
1454 TyKind::ImplTrait(def_node_id, ref bounds) => {
1457 ImplTraitContext::Existential(fn_def_id) => {
1458 self.lower_existential_impl_trait(
1459 span, fn_def_id, def_node_id,
1460 |this| this.lower_param_bounds(bounds, itctx),
1463 ImplTraitContext::Universal(in_band_ty_params) => {
1464 // Add a definition for the in-band `Param`.
1465 let def_index = self
1468 .opt_def_index(def_node_id)
1471 let hir_bounds = self.lower_param_bounds(
1473 ImplTraitContext::Universal(in_band_ty_params),
1475 // Set the name to `impl Bound1 + Bound2`.
1476 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1477 in_band_ty_params.push(hir::GenericParam {
1478 hir_id: self.lower_node_id(def_node_id),
1479 name: ParamName::Plain(ident),
1480 pure_wrt_drop: false,
1484 kind: hir::GenericParamKind::Type {
1486 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1490 hir::TyKind::Path(hir::QPath::Resolved(
1494 res: Res::Def(DefKind::TyParam, DefId::local(def_index)),
1495 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1499 ImplTraitContext::Disallowed(pos) => {
1500 let allowed_in = if self.sess.features_untracked()
1501 .impl_trait_in_bindings {
1502 "bindings or function and inherent method return types"
1504 "function and inherent method return types"
1506 let mut err = struct_span_err!(
1510 "`impl Trait` not allowed outside of {}",
1513 if pos == ImplTraitPosition::Binding &&
1514 nightly_options::is_nightly_build() {
1516 "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1524 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1525 TyKind::CVarArgs => {
1526 // Create the implicit lifetime of the "spoofed" `VaList`.
1527 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1528 let lt = self.new_implicit_lifetime(span);
1529 hir::TyKind::CVarArgs(lt)
1536 hir_id: self.lower_node_id(t.id),
1540 fn lower_existential_impl_trait(
1543 fn_def_id: Option<DefId>,
1544 exist_ty_node_id: NodeId,
1545 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1547 // Make sure we know that some funky desugaring has been going on here.
1548 // This is a first: there is code in other places like for loop
1549 // desugaring that explicitly states that we don't want to track that.
1550 // Not tracking it makes lints in rustc and clippy very fragile as
1551 // frequently opened issues show.
1552 let exist_ty_span = self.sess.source_map().mark_span_with_reason(
1553 CompilerDesugaringKind::ExistentialReturnType,
1558 let exist_ty_def_index = self
1561 .opt_def_index(exist_ty_node_id)
1564 self.allocate_hir_id_counter(exist_ty_node_id);
1566 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1568 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1574 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1575 let exist_ty_item = hir::ExistTy {
1576 generics: hir::Generics {
1577 params: lifetime_defs,
1578 where_clause: hir::WhereClause {
1579 hir_id: lctx.next_id(),
1580 predicates: hir_vec![],
1585 impl_trait_fn: fn_def_id,
1586 origin: hir::ExistTyOrigin::ReturnImplTrait,
1589 trace!("exist ty from impl trait def index: {:#?}", exist_ty_def_index);
1590 let exist_ty_id = lctx.generate_existential_type(
1597 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1598 hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, lifetimes)
1602 /// Registers a new existential type with the proper NodeIds and
1603 /// returns the lowered node ID for the existential type.
1604 fn generate_existential_type(
1606 exist_ty_node_id: NodeId,
1607 exist_ty_item: hir::ExistTy,
1609 exist_ty_span: Span,
1611 let exist_ty_item_kind = hir::ItemKind::Existential(exist_ty_item);
1612 let exist_ty_id = self.lower_node_id(exist_ty_node_id);
1613 // Generate an `existential type Foo: Trait;` declaration.
1614 trace!("registering existential type with id {:#?}", exist_ty_id);
1615 let exist_ty_item = hir::Item {
1616 hir_id: exist_ty_id,
1617 ident: Ident::invalid(),
1618 attrs: Default::default(),
1619 node: exist_ty_item_kind,
1620 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1621 span: exist_ty_span,
1624 // Insert the item into the global item list. This usually happens
1625 // automatically for all AST items. But this existential type item
1626 // does not actually exist in the AST.
1627 self.insert_item(exist_ty_item);
1631 fn lifetimes_from_impl_trait_bounds(
1633 exist_ty_id: NodeId,
1634 parent_index: DefIndex,
1635 bounds: &hir::GenericBounds,
1636 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1637 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1638 // appear in the bounds, excluding lifetimes that are created within the bounds.
1639 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1640 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1641 context: &'r mut LoweringContext<'a>,
1643 exist_ty_id: NodeId,
1644 collect_elided_lifetimes: bool,
1645 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1646 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1647 output_lifetimes: Vec<hir::GenericArg>,
1648 output_lifetime_params: Vec<hir::GenericParam>,
1651 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1652 fn nested_visit_map<'this>(
1654 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1655 hir::intravisit::NestedVisitorMap::None
1658 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1659 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1660 if parameters.parenthesized {
1661 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1662 self.collect_elided_lifetimes = false;
1663 hir::intravisit::walk_generic_args(self, span, parameters);
1664 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1666 hir::intravisit::walk_generic_args(self, span, parameters);
1670 fn visit_ty(&mut self, t: &'v hir::Ty) {
1671 // Don't collect elided lifetimes used inside of `fn()` syntax.
1672 if let hir::TyKind::BareFn(_) = t.node {
1673 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1674 self.collect_elided_lifetimes = false;
1676 // Record the "stack height" of `for<'a>` lifetime bindings
1677 // to be able to later fully undo their introduction.
1678 let old_len = self.currently_bound_lifetimes.len();
1679 hir::intravisit::walk_ty(self, t);
1680 self.currently_bound_lifetimes.truncate(old_len);
1682 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1684 hir::intravisit::walk_ty(self, t)
1688 fn visit_poly_trait_ref(
1690 trait_ref: &'v hir::PolyTraitRef,
1691 modifier: hir::TraitBoundModifier,
1693 // Record the "stack height" of `for<'a>` lifetime bindings
1694 // to be able to later fully undo their introduction.
1695 let old_len = self.currently_bound_lifetimes.len();
1696 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1697 self.currently_bound_lifetimes.truncate(old_len);
1700 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1701 // Record the introduction of 'a in `for<'a> ...`.
1702 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1703 // Introduce lifetimes one at a time so that we can handle
1704 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1705 let lt_name = hir::LifetimeName::Param(param.name);
1706 self.currently_bound_lifetimes.push(lt_name);
1709 hir::intravisit::walk_generic_param(self, param);
1712 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1713 let name = match lifetime.name {
1714 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1715 if self.collect_elided_lifetimes {
1716 // Use `'_` for both implicit and underscore lifetimes in
1717 // `abstract type Foo<'_>: SomeTrait<'_>;`.
1718 hir::LifetimeName::Underscore
1723 hir::LifetimeName::Param(_) => lifetime.name,
1724 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1727 if !self.currently_bound_lifetimes.contains(&name)
1728 && !self.already_defined_lifetimes.contains(&name) {
1729 self.already_defined_lifetimes.insert(name);
1731 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1732 hir_id: self.context.next_id(),
1733 span: lifetime.span,
1737 let def_node_id = self.context.sess.next_node_id();
1739 self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1740 self.context.resolver.definitions().create_def_with_parent(
1743 DefPathData::LifetimeNs(name.ident().as_interned_str()),
1748 let (name, kind) = match name {
1749 hir::LifetimeName::Underscore => (
1750 hir::ParamName::Plain(Ident::with_empty_ctxt(kw::UnderscoreLifetime)),
1751 hir::LifetimeParamKind::Elided,
1753 hir::LifetimeName::Param(param_name) => (
1755 hir::LifetimeParamKind::Explicit,
1757 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1760 self.output_lifetime_params.push(hir::GenericParam {
1763 span: lifetime.span,
1764 pure_wrt_drop: false,
1767 kind: hir::GenericParamKind::Lifetime { kind }
1773 let mut lifetime_collector = ImplTraitLifetimeCollector {
1775 parent: parent_index,
1777 collect_elided_lifetimes: true,
1778 currently_bound_lifetimes: Vec::new(),
1779 already_defined_lifetimes: FxHashSet::default(),
1780 output_lifetimes: Vec::new(),
1781 output_lifetime_params: Vec::new(),
1784 for bound in bounds {
1785 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1789 lifetime_collector.output_lifetimes.into(),
1790 lifetime_collector.output_lifetime_params.into(),
1794 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1799 .map(|x| self.lower_foreign_item(x))
1804 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1811 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1813 node: hir::VariantKind {
1814 ident: v.node.ident,
1815 id: self.lower_node_id(v.node.id),
1816 attrs: self.lower_attrs(&v.node.attrs),
1817 data: self.lower_variant_data(&v.node.data),
1818 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1827 qself: &Option<QSelf>,
1829 param_mode: ParamMode,
1830 mut itctx: ImplTraitContext<'_>,
1832 let qself_position = qself.as_ref().map(|q| q.position);
1833 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1835 let partial_res = self.resolver
1836 .get_partial_res(id)
1837 .unwrap_or_else(|| PartialRes::new(Res::Err));
1839 let proj_start = p.segments.len() - partial_res.unresolved_segments();
1840 let path = P(hir::Path {
1841 res: self.lower_res(partial_res.base_res()),
1842 segments: p.segments[..proj_start]
1845 .map(|(i, segment)| {
1846 let param_mode = match (qself_position, param_mode) {
1847 (Some(j), ParamMode::Optional) if i < j => {
1848 // This segment is part of the trait path in a
1849 // qualified path - one of `a`, `b` or `Trait`
1850 // in `<X as a::b::Trait>::T::U::method`.
1856 // Figure out if this is a type/trait segment,
1857 // which may need lifetime elision performed.
1858 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1859 krate: def_id.krate,
1860 index: this.def_key(def_id).parent.expect("missing parent"),
1862 let type_def_id = match partial_res.base_res() {
1863 Res::Def(DefKind::AssociatedTy, def_id) if i + 2 == proj_start => {
1864 Some(parent_def_id(self, def_id))
1866 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
1867 Some(parent_def_id(self, def_id))
1869 Res::Def(DefKind::Struct, def_id)
1870 | Res::Def(DefKind::Union, def_id)
1871 | Res::Def(DefKind::Enum, def_id)
1872 | Res::Def(DefKind::TyAlias, def_id)
1873 | Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start =>
1879 let parenthesized_generic_args = match partial_res.base_res() {
1880 // `a::b::Trait(Args)`
1881 Res::Def(DefKind::Trait, _)
1882 if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1883 // `a::b::Trait(Args)::TraitItem`
1884 Res::Def(DefKind::Method, _)
1885 | Res::Def(DefKind::AssociatedConst, _)
1886 | Res::Def(DefKind::AssociatedTy, _)
1887 if i + 2 == proj_start =>
1889 ParenthesizedGenericArgs::Ok
1891 // Avoid duplicated errors.
1892 Res::Err => ParenthesizedGenericArgs::Ok,
1894 Res::Def(DefKind::Struct, _)
1895 | Res::Def(DefKind::Enum, _)
1896 | Res::Def(DefKind::Union, _)
1897 | Res::Def(DefKind::TyAlias, _)
1898 | Res::Def(DefKind::Variant, _) if i + 1 == proj_start =>
1900 ParenthesizedGenericArgs::Err
1902 // A warning for now, for compatibility reasons
1903 _ => ParenthesizedGenericArgs::Warn,
1906 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1907 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1910 assert!(!def_id.is_local());
1912 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1913 let n = item_generics.own_counts().lifetimes;
1914 self.type_def_lifetime_params.insert(def_id, n);
1917 self.lower_path_segment(
1922 parenthesized_generic_args,
1931 // Simple case, either no projections, or only fully-qualified.
1932 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
1933 if partial_res.unresolved_segments() == 0 {
1934 return hir::QPath::Resolved(qself, path);
1937 // Create the innermost type that we're projecting from.
1938 let mut ty = if path.segments.is_empty() {
1939 // If the base path is empty that means there exists a
1940 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
1941 qself.expect("missing QSelf for <T>::...")
1943 // Otherwise, the base path is an implicit `Self` type path,
1944 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1945 // `<I as Iterator>::Item::default`.
1946 let new_id = self.next_id();
1947 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1950 // Anything after the base path are associated "extensions",
1951 // out of which all but the last one are associated types,
1952 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1953 // * base path is `std::vec::Vec<T>`
1954 // * "extensions" are `IntoIter`, `Item` and `clone`
1955 // * type nodes are:
1956 // 1. `std::vec::Vec<T>` (created above)
1957 // 2. `<std::vec::Vec<T>>::IntoIter`
1958 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1959 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1960 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1961 let segment = P(self.lower_path_segment(
1966 ParenthesizedGenericArgs::Warn,
1970 let qpath = hir::QPath::TypeRelative(ty, segment);
1972 // It's finished, return the extension of the right node type.
1973 if i == p.segments.len() - 1 {
1977 // Wrap the associated extension in another type node.
1978 let new_id = self.next_id();
1979 ty = P(self.ty_path(new_id, p.span, qpath));
1982 // We should've returned in the for loop above.
1985 "lower_qpath: no final extension segment in {}..{}",
1991 fn lower_path_extra(
1995 param_mode: ParamMode,
1996 explicit_owner: Option<NodeId>,
2000 segments: p.segments
2003 self.lower_path_segment(
2008 ParenthesizedGenericArgs::Err,
2009 ImplTraitContext::disallowed(),
2018 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
2019 let res = self.expect_full_res(id);
2020 let res = self.lower_res(res);
2021 self.lower_path_extra(res, p, param_mode, None)
2024 fn lower_path_segment(
2027 segment: &PathSegment,
2028 param_mode: ParamMode,
2029 expected_lifetimes: usize,
2030 parenthesized_generic_args: ParenthesizedGenericArgs,
2031 itctx: ImplTraitContext<'_>,
2032 explicit_owner: Option<NodeId>,
2033 ) -> hir::PathSegment {
2034 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
2035 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
2036 match **generic_args {
2037 GenericArgs::AngleBracketed(ref data) => {
2038 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
2040 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
2041 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
2042 ParenthesizedGenericArgs::Warn => {
2043 self.sess.buffer_lint(
2044 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
2049 (hir::GenericArgs::none(), true)
2051 ParenthesizedGenericArgs::Err => {
2052 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
2053 err.span_label(data.span, "only `Fn` traits may use parentheses");
2054 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
2055 // Do not suggest going from `Trait()` to `Trait<>`
2056 if data.inputs.len() > 0 {
2057 err.span_suggestion(
2059 "use angle brackets instead",
2060 format!("<{}>", &snippet[1..snippet.len() - 1]),
2061 Applicability::MaybeIncorrect,
2066 (self.lower_angle_bracketed_parameter_data(
2067 &data.as_angle_bracketed_args(),
2075 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
2078 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
2079 GenericArg::Lifetime(_) => true,
2082 let first_generic_span = generic_args.args.iter().map(|a| a.span())
2083 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
2084 if !generic_args.parenthesized && !has_lifetimes {
2086 self.elided_path_lifetimes(path_span, expected_lifetimes)
2088 .map(|lt| GenericArg::Lifetime(lt))
2089 .chain(generic_args.args.into_iter())
2091 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
2092 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
2093 let no_ty_args = generic_args.args.len() == expected_lifetimes;
2094 let no_bindings = generic_args.bindings.is_empty();
2095 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
2096 // If there are no (non-implicit) generic args or associated-type
2097 // bindings, our suggestion includes the angle brackets.
2098 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
2100 // Otherwise—sorry, this is kind of gross—we need to infer the
2101 // place to splice in the `'_, ` from the generics that do exist.
2102 let first_generic_span = first_generic_span
2103 .expect("already checked that type args or bindings exist");
2104 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
2106 match self.anonymous_lifetime_mode {
2107 // In create-parameter mode we error here because we don't want to support
2108 // deprecated impl elision in new features like impl elision and `async fn`,
2109 // both of which work using the `CreateParameter` mode:
2111 // impl Foo for std::cell::Ref<u32> // note lack of '_
2112 // async fn foo(_: std::cell::Ref<u32>) { ... }
2113 AnonymousLifetimeMode::CreateParameter => {
2114 let mut err = struct_span_err!(
2118 "implicit elided lifetime not allowed here"
2120 crate::lint::builtin::add_elided_lifetime_in_path_suggestion(
2131 AnonymousLifetimeMode::PassThrough |
2132 AnonymousLifetimeMode::ReportError |
2133 AnonymousLifetimeMode::Replace(_) => {
2134 self.sess.buffer_lint_with_diagnostic(
2135 ELIDED_LIFETIMES_IN_PATHS,
2138 "hidden lifetime parameters in types are deprecated",
2139 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
2152 let res = self.expect_full_res(segment.id);
2153 let id = if let Some(owner) = explicit_owner {
2154 self.lower_node_id_with_owner(segment.id, owner)
2156 self.lower_node_id(segment.id)
2159 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
2160 segment.ident, segment.id, id,
2163 hir::PathSegment::new(
2166 Some(self.lower_res(res)),
2172 fn lower_angle_bracketed_parameter_data(
2174 data: &AngleBracketedArgs,
2175 param_mode: ParamMode,
2176 mut itctx: ImplTraitContext<'_>,
2177 ) -> (hir::GenericArgs, bool) {
2178 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
2179 let has_types = args.iter().any(|arg| match arg {
2180 ast::GenericArg::Type(_) => true,
2184 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
2185 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
2186 parenthesized: false,
2188 !has_types && param_mode == ParamMode::Optional)
2191 fn lower_parenthesized_parameter_data(
2193 data: &ParenthesizedArgs,
2194 ) -> (hir::GenericArgs, bool) {
2195 // Switch to `PassThrough` mode for anonymous lifetimes: this
2196 // means that we permit things like `&Ref<T>`, where `Ref` has
2197 // a hidden lifetime parameter. This is needed for backwards
2198 // compatibility, even in contexts like an impl header where
2199 // we generally don't permit such things (see #51008).
2200 self.with_anonymous_lifetime_mode(
2201 AnonymousLifetimeMode::PassThrough,
2203 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2206 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
2208 let mk_tup = |this: &mut Self, tys, span| {
2209 hir::Ty { node: hir::TyKind::Tup(tys), hir_id: this.next_id(), span }
2213 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
2216 hir_id: this.next_id(),
2217 ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
2220 .map(|ty| this.lower_ty(&ty, ImplTraitContext::disallowed()))
2221 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
2222 span: output.as_ref().map_or(span, |ty| ty.span),
2225 parenthesized: true,
2233 fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) {
2234 let mut ids = SmallVec::<[NodeId; 1]>::new();
2235 if self.sess.features_untracked().impl_trait_in_bindings {
2236 if let Some(ref ty) = l.ty {
2237 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2238 visitor.visit_ty(ty);
2241 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2243 hir_id: self.lower_node_id(l.id),
2246 .map(|t| self.lower_ty(t,
2247 if self.sess.features_untracked().impl_trait_in_bindings {
2248 ImplTraitContext::Existential(Some(parent_def_id))
2250 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2253 pat: self.lower_pat(&l.pat),
2254 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2256 attrs: l.attrs.clone(),
2257 source: self.lower_local_source(l.source),
2261 fn lower_local_source(&mut self, ls: LocalSource) -> hir::LocalSource {
2263 LocalSource::Normal => hir::LocalSource::Normal,
2264 LocalSource::AsyncFn => hir::LocalSource::AsyncFn,
2268 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
2270 Mutability::Mutable => hir::MutMutable,
2271 Mutability::Immutable => hir::MutImmutable,
2275 fn lower_args(&mut self, decl: Option<&FnDecl>) -> HirVec<hir::Arg> {
2276 decl.map_or(hir_vec![], |decl| decl.inputs.iter().map(|x| self.lower_arg(x)).collect())
2279 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
2281 hir_id: self.lower_node_id(arg.id),
2282 pat: self.lower_pat(&arg.pat),
2283 source: self.lower_arg_source(&arg.source),
2287 fn lower_arg_source(&mut self, source: &ArgSource) -> hir::ArgSource {
2289 ArgSource::Normal => hir::ArgSource::Normal,
2290 ArgSource::AsyncFn(pat) => hir::ArgSource::AsyncFn(self.lower_pat(pat)),
2294 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2297 .map(|arg| match arg.pat.node {
2298 PatKind::Ident(_, ident, _) => ident,
2299 _ => Ident::new(kw::Invalid, arg.pat.span),
2304 // Lowers a function declaration.
2306 // decl: the unlowered (ast) function declaration.
2307 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
2308 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2309 // make_ret_async is also `Some`.
2310 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
2311 // This guards against trait declarations and implementations where impl Trait is
2313 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2314 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
2315 // return type impl Trait item.
2319 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2320 impl_trait_return_allow: bool,
2321 make_ret_async: Option<NodeId>,
2322 ) -> P<hir::FnDecl> {
2323 let lt_mode = if make_ret_async.is_some() {
2324 // In `async fn`, argument-position elided lifetimes
2325 // must be transformed into fresh generic parameters so that
2326 // they can be applied to the existential return type.
2327 AnonymousLifetimeMode::CreateParameter
2329 self.anonymous_lifetime_mode
2332 // Remember how many lifetimes were already around so that we can
2333 // only look at the lifetime parameters introduced by the arguments.
2334 let lifetime_count_before_args = self.lifetimes_to_define.len();
2335 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2339 if let Some((_, ibty)) = &mut in_band_ty_params {
2340 this.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2342 this.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2345 .collect::<HirVec<_>>()
2348 let output = if let Some(ret_id) = make_ret_async {
2349 // Calculate the `LtReplacement` to use for any return-position elided
2350 // lifetimes based on the elided lifetime parameters introduced in the args.
2351 let lt_replacement = get_elided_lt_replacement(
2352 &self.lifetimes_to_define[lifetime_count_before_args..]
2354 self.lower_async_fn_ret_ty(
2356 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
2362 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2363 Some((def_id, _)) if impl_trait_return_allow => {
2364 hir::Return(self.lower_ty(ty,
2365 ImplTraitContext::Existential(Some(def_id))))
2368 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2371 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2378 c_variadic: decl.c_variadic,
2379 implicit_self: decl.inputs.get(0).map_or(
2380 hir::ImplicitSelfKind::None,
2382 let is_mutable_pat = match arg.pat.node {
2383 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2384 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2385 mt == Mutability::Mutable,
2390 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2391 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2392 // Given we are only considering `ImplicitSelf` types, we needn't consider
2393 // the case where we have a mutable pattern to a reference as that would
2394 // no longer be an `ImplicitSelf`.
2395 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2396 mt.mutbl == ast::Mutability::Mutable =>
2397 hir::ImplicitSelfKind::MutRef,
2398 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2399 hir::ImplicitSelfKind::ImmRef,
2400 _ => hir::ImplicitSelfKind::None,
2407 // Transform `-> T` for `async fn` into -> ExistTy { .. }
2408 // combined with the following definition of `ExistTy`:
2410 // existential type ExistTy<generics_from_parent_fn>: Future<Output = T>;
2412 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
2413 // output: unlowered output type (`T` in `-> T`)
2414 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
2415 // exist_ty_node_id: NodeId of the existential type that should be created.
2416 // elided_lt_replacement: replacement for elided lifetimes in the return type
2417 fn lower_async_fn_ret_ty(
2419 output: &FunctionRetTy,
2421 exist_ty_node_id: NodeId,
2422 elided_lt_replacement: LtReplacement,
2423 ) -> hir::FunctionRetTy {
2424 let span = output.span();
2426 let exist_ty_span = self.sess.source_map().mark_span_with_reason(
2427 CompilerDesugaringKind::Async,
2432 let exist_ty_def_index = self
2435 .opt_def_index(exist_ty_node_id)
2438 self.allocate_hir_id_counter(exist_ty_node_id);
2440 let (exist_ty_id, lifetime_params) = self.with_hir_id_owner(exist_ty_node_id, |this| {
2441 let future_bound = this.with_anonymous_lifetime_mode(
2442 AnonymousLifetimeMode::Replace(elided_lt_replacement),
2443 |this| this.lower_async_fn_output_type_to_future_bound(
2450 // Calculate all the lifetimes that should be captured
2451 // by the existential type. This should include all in-scope
2452 // lifetime parameters, including those defined in-band.
2454 // Note: this must be done after lowering the output type,
2455 // as the output type may introduce new in-band lifetimes.
2456 let lifetime_params: Vec<(Span, ParamName)> =
2457 this.in_scope_lifetimes
2459 .map(|ident| (ident.span, ParamName::Plain(ident)))
2460 .chain(this.lifetimes_to_define.iter().cloned())
2463 let generic_params =
2466 .map(|(span, hir_name)| {
2467 this.lifetime_to_generic_param(span, hir_name, exist_ty_def_index)
2471 let exist_ty_item = hir::ExistTy {
2472 generics: hir::Generics {
2473 params: generic_params,
2474 where_clause: hir::WhereClause {
2475 hir_id: this.next_id(),
2476 predicates: hir_vec![],
2480 bounds: hir_vec![future_bound],
2481 impl_trait_fn: Some(fn_def_id),
2482 origin: hir::ExistTyOrigin::AsyncFn,
2485 trace!("exist ty from async fn def index: {:#?}", exist_ty_def_index);
2486 let exist_ty_id = this.generate_existential_type(
2493 (exist_ty_id, lifetime_params)
2499 .map(|(span, hir_name)| {
2500 GenericArg::Lifetime(hir::Lifetime {
2501 hir_id: self.next_id(),
2503 name: hir::LifetimeName::Param(hir_name),
2508 let exist_ty_ref = hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, generic_args);
2510 hir::FunctionRetTy::Return(P(hir::Ty {
2513 hir_id: self.next_id(),
2517 /// Turns `-> T` into `Future<Output = T>`
2518 fn lower_async_fn_output_type_to_future_bound(
2520 output: &FunctionRetTy,
2523 ) -> hir::GenericBound {
2524 // Compute the `T` in `Future<Output = T>` from the return type.
2525 let output_ty = match output {
2526 FunctionRetTy::Ty(ty) => {
2527 self.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2529 FunctionRetTy::Default(ret_ty_span) => {
2531 hir_id: self.next_id(),
2532 node: hir::TyKind::Tup(hir_vec![]),
2539 let future_params = P(hir::GenericArgs {
2541 bindings: hir_vec![hir::TypeBinding {
2542 ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
2544 hir_id: self.next_id(),
2547 parenthesized: false,
2550 // ::std::future::Future<future_params>
2552 self.std_path(span, &[sym::future, sym::Future], Some(future_params), false);
2554 hir::GenericBound::Trait(
2556 trait_ref: hir::TraitRef {
2558 hir_ref_id: self.next_id(),
2560 bound_generic_params: hir_vec![],
2563 hir::TraitBoundModifier::None,
2567 fn lower_param_bound(
2570 itctx: ImplTraitContext<'_>,
2571 ) -> hir::GenericBound {
2573 GenericBound::Trait(ref ty, modifier) => {
2574 hir::GenericBound::Trait(
2575 self.lower_poly_trait_ref(ty, itctx),
2576 self.lower_trait_bound_modifier(modifier),
2579 GenericBound::Outlives(ref lifetime) => {
2580 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2585 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2586 let span = l.ident.span;
2588 ident if ident.name == kw::StaticLifetime =>
2589 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2590 ident if ident.name == kw::UnderscoreLifetime =>
2591 match self.anonymous_lifetime_mode {
2592 AnonymousLifetimeMode::CreateParameter => {
2593 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2594 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2597 AnonymousLifetimeMode::PassThrough => {
2598 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2601 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2603 AnonymousLifetimeMode::Replace(replacement) => {
2604 let hir_id = self.lower_node_id(l.id);
2605 self.replace_elided_lifetime(hir_id, span, replacement)
2609 self.maybe_collect_in_band_lifetime(ident);
2610 let param_name = ParamName::Plain(ident);
2611 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2616 fn new_named_lifetime(
2620 name: hir::LifetimeName,
2621 ) -> hir::Lifetime {
2623 hir_id: self.lower_node_id(id),
2629 /// Replace a return-position elided lifetime with the elided lifetime
2630 /// from the arguments.
2631 fn replace_elided_lifetime(
2635 replacement: LtReplacement,
2636 ) -> hir::Lifetime {
2637 let multiple_or_none = match replacement {
2638 LtReplacement::Some(name) => {
2639 return hir::Lifetime {
2642 name: hir::LifetimeName::Param(name),
2645 LtReplacement::MultipleLifetimes => "multiple",
2646 LtReplacement::NoLifetimes => "none",
2649 let mut err = crate::middle::resolve_lifetime::report_missing_lifetime_specifiers(
2655 "return-position elided lifetimes require exactly one \
2656 input-position elided lifetime, found {}.", multiple_or_none));
2659 hir::Lifetime { hir_id, span, name: hir::LifetimeName::Error }
2662 fn lower_generic_params(
2664 params: &[GenericParam],
2665 add_bounds: &NodeMap<Vec<GenericBound>>,
2666 mut itctx: ImplTraitContext<'_>,
2667 ) -> hir::HirVec<hir::GenericParam> {
2668 params.iter().map(|param| {
2669 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2673 fn lower_generic_param(&mut self,
2674 param: &GenericParam,
2675 add_bounds: &NodeMap<Vec<GenericBound>>,
2676 mut itctx: ImplTraitContext<'_>)
2677 -> hir::GenericParam {
2678 let mut bounds = self.with_anonymous_lifetime_mode(
2679 AnonymousLifetimeMode::ReportError,
2680 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2683 let (name, kind) = match param.kind {
2684 GenericParamKind::Lifetime => {
2685 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2686 self.is_collecting_in_band_lifetimes = false;
2688 let lt = self.with_anonymous_lifetime_mode(
2689 AnonymousLifetimeMode::ReportError,
2690 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2692 let param_name = match lt.name {
2693 hir::LifetimeName::Param(param_name) => param_name,
2694 hir::LifetimeName::Implicit
2695 | hir::LifetimeName::Underscore
2696 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2697 hir::LifetimeName::Error => ParamName::Error,
2700 let kind = hir::GenericParamKind::Lifetime {
2701 kind: hir::LifetimeParamKind::Explicit
2704 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2708 GenericParamKind::Type { ref default, .. } => {
2709 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2710 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2711 // Instead, use `gensym("Self")` to create a distinct name that looks the same.
2712 let ident = if param.ident.name == kw::SelfUpper {
2713 param.ident.gensym()
2718 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2719 if !add_bounds.is_empty() {
2720 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2721 bounds = bounds.into_iter()
2726 let kind = hir::GenericParamKind::Type {
2727 default: default.as_ref().map(|x| {
2728 self.lower_ty(x, ImplTraitContext::disallowed())
2730 synthetic: param.attrs.iter()
2731 .filter(|attr| attr.check_name(sym::rustc_synthetic))
2732 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2736 (hir::ParamName::Plain(ident), kind)
2738 GenericParamKind::Const { ref ty } => {
2739 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const {
2740 ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2746 hir_id: self.lower_node_id(param.id),
2748 span: param.ident.span,
2749 pure_wrt_drop: attr::contains_name(¶m.attrs, sym::may_dangle),
2750 attrs: self.lower_attrs(¶m.attrs),
2758 generics: &Generics,
2759 itctx: ImplTraitContext<'_>)
2762 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2763 // FIXME: this could probably be done with less rightward drift. Also looks like two control
2764 // paths where report_error is called are also the only paths that advance to after
2765 // the match statement, so the error reporting could probably just be moved there.
2766 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
2767 for pred in &generics.where_clause.predicates {
2768 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2769 'next_bound: for bound in &bound_pred.bounds {
2770 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2771 let report_error = |this: &mut Self| {
2772 this.diagnostic().span_err(
2773 bound_pred.bounded_ty.span,
2774 "`?Trait` bounds are only permitted at the \
2775 point where a type parameter is declared",
2778 // Check if the where clause type is a plain type parameter.
2779 match bound_pred.bounded_ty.node {
2780 TyKind::Path(None, ref path)
2781 if path.segments.len() == 1
2782 && bound_pred.bound_generic_params.is_empty() =>
2784 if let Some(Res::Def(DefKind::TyParam, def_id)) = self.resolver
2785 .get_partial_res(bound_pred.bounded_ty.id)
2786 .map(|d| d.base_res())
2788 if let Some(node_id) =
2789 self.resolver.definitions().as_local_node_id(def_id)
2791 for param in &generics.params {
2793 GenericParamKind::Type { .. } => {
2794 if node_id == param.id {
2795 add_bounds.entry(param.id)
2797 .push(bound.clone());
2798 continue 'next_bound;
2808 _ => report_error(self),
2816 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2817 where_clause: self.lower_where_clause(&generics.where_clause),
2818 span: generics.span,
2822 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2823 self.with_anonymous_lifetime_mode(
2824 AnonymousLifetimeMode::ReportError,
2827 hir_id: this.lower_node_id(wc.id),
2828 predicates: wc.predicates
2830 .map(|predicate| this.lower_where_predicate(predicate))
2837 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2839 WherePredicate::BoundPredicate(WhereBoundPredicate {
2840 ref bound_generic_params,
2845 self.with_in_scope_lifetime_defs(
2846 &bound_generic_params,
2848 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2849 bound_generic_params: this.lower_generic_params(
2850 bound_generic_params,
2851 &NodeMap::default(),
2852 ImplTraitContext::disallowed(),
2854 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
2857 .filter_map(|bound| match *bound {
2858 // Ignore `?Trait` bounds.
2859 // They were copied into type parameters already.
2860 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2861 _ => Some(this.lower_param_bound(
2863 ImplTraitContext::disallowed(),
2872 WherePredicate::RegionPredicate(WhereRegionPredicate {
2876 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2878 lifetime: self.lower_lifetime(lifetime),
2879 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2881 WherePredicate::EqPredicate(WhereEqPredicate {
2887 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2888 hir_id: self.lower_node_id(id),
2889 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
2890 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
2897 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2899 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
2900 fields.iter().enumerate().map(|f| self.lower_struct_field(f)).collect(),
2903 VariantData::Tuple(ref fields, id) => {
2904 hir::VariantData::Tuple(
2908 .map(|f| self.lower_struct_field(f))
2910 self.lower_node_id(id),
2913 VariantData::Unit(id) => {
2914 hir::VariantData::Unit(self.lower_node_id(id))
2919 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2920 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2921 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2922 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2926 hir_ref_id: self.lower_node_id(p.ref_id),
2930 fn lower_poly_trait_ref(
2933 mut itctx: ImplTraitContext<'_>,
2934 ) -> hir::PolyTraitRef {
2935 let bound_generic_params = self.lower_generic_params(
2936 &p.bound_generic_params,
2937 &NodeMap::default(),
2940 let trait_ref = self.with_parent_impl_lifetime_defs(
2941 &bound_generic_params,
2942 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2946 bound_generic_params,
2952 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2955 hir_id: self.lower_node_id(f.id),
2956 ident: match f.ident {
2957 Some(ident) => ident,
2958 // FIXME(jseyfried): positional field hygiene
2959 None => Ident::new(sym::integer(index), f.span),
2961 vis: self.lower_visibility(&f.vis, None),
2962 ty: self.lower_ty(&f.ty, ImplTraitContext::disallowed()),
2963 attrs: self.lower_attrs(&f.attrs),
2967 fn lower_field(&mut self, f: &Field) -> hir::Field {
2969 hir_id: self.next_id(),
2971 expr: P(self.lower_expr(&f.expr)),
2973 is_shorthand: f.is_shorthand,
2977 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2979 ty: self.lower_ty(&mt.ty, itctx),
2980 mutbl: self.lower_mutability(mt.mutbl),
2984 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2985 -> hir::GenericBounds {
2986 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2989 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2990 let mut expr = None;
2992 let mut stmts = vec![];
2994 for (index, stmt) in b.stmts.iter().enumerate() {
2995 if index == b.stmts.len() - 1 {
2996 if let StmtKind::Expr(ref e) = stmt.node {
2997 expr = Some(P(self.lower_expr(e)));
2999 stmts.extend(self.lower_stmt(stmt));
3002 stmts.extend(self.lower_stmt(stmt));
3007 hir_id: self.lower_node_id(b.id),
3008 stmts: stmts.into(),
3010 rules: self.lower_block_check_mode(&b.rules),
3016 fn lower_async_body(
3019 asyncness: &IsAsync,
3022 self.lower_body(Some(&decl), |this| {
3023 if let IsAsync::Async { closure_id, ref arguments, .. } = asyncness {
3024 let mut body = body.clone();
3026 // Async function arguments are lowered into the closure body so that they are
3027 // captured and so that the drop order matches the equivalent non-async functions.
3029 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
3035 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
3037 // let __arg2 = __arg2;
3038 // let <pattern> = __arg2;
3039 // let __arg1 = __arg1;
3040 // let <pattern> = __arg1;
3041 // let __arg0 = __arg0;
3042 // let <pattern> = __arg0;
3046 // If `<pattern>` is a simple ident, then it is lowered to a single
3047 // `let <pattern> = <pattern>;` statement as an optimization.
3048 for a in arguments.iter().rev() {
3049 if let Some(pat_stmt) = a.pat_stmt.clone() {
3050 body.stmts.insert(0, pat_stmt);
3052 body.stmts.insert(0, a.move_stmt.clone());
3055 let async_expr = this.make_async_expr(
3056 CaptureBy::Value, *closure_id, None, body.span,
3058 let body = this.lower_block(&body, false);
3059 this.expr_block(body, ThinVec::new())
3061 this.expr(body.span, async_expr, ThinVec::new())
3063 let body = this.lower_block(body, false);
3064 this.expr_block(body, ThinVec::new())
3073 attrs: &hir::HirVec<Attribute>,
3074 vis: &mut hir::Visibility,
3076 ) -> hir::ItemKind {
3078 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
3079 ItemKind::Use(ref use_tree) => {
3080 // Start with an empty prefix
3083 span: use_tree.span,
3086 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
3088 ItemKind::Static(ref t, m, ref e) => {
3089 let value = self.lower_body(None, |this| this.lower_expr(e));
3090 hir::ItemKind::Static(
3093 if self.sess.features_untracked().impl_trait_in_bindings {
3094 ImplTraitContext::Existential(None)
3096 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3099 self.lower_mutability(m),
3103 ItemKind::Const(ref t, ref e) => {
3104 let value = self.lower_body(None, |this| this.lower_expr(e));
3105 hir::ItemKind::Const(
3108 if self.sess.features_untracked().impl_trait_in_bindings {
3109 ImplTraitContext::Existential(None)
3111 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3117 ItemKind::Fn(ref decl, ref header, ref generics, ref body) => {
3118 let fn_def_id = self.resolver.definitions().local_def_id(id);
3119 self.with_new_scopes(|this| {
3120 this.current_item = Some(ident.span);
3121 let mut lower_fn = |decl: &FnDecl| {
3122 // Note: we don't need to change the return type from `T` to
3123 // `impl Future<Output = T>` here because lower_body
3124 // only cares about the input argument patterns in the function
3125 // declaration (decl), not the return types.
3126 let body_id = this.lower_async_body(&decl, &header.asyncness.node, body);
3128 let (generics, fn_decl) = this.add_in_band_defs(
3131 AnonymousLifetimeMode::PassThrough,
3132 |this, idty| this.lower_fn_decl(
3134 Some((fn_def_id, idty)),
3136 header.asyncness.node.opt_return_id()
3140 (body_id, generics, fn_decl)
3143 let (body_id, generics, fn_decl) = if let IsAsync::Async {
3145 } = &header.asyncness.node {
3146 let mut decl = decl.clone();
3147 // Replace the arguments of this async function with the generated
3148 // arguments that will be moved into the closure.
3149 for (i, a) in arguments.clone().drain(..).enumerate() {
3150 if let Some(arg) = a.arg {
3151 decl.inputs[i] = arg;
3161 this.lower_fn_header(header),
3167 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
3168 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
3169 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
3170 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
3171 self.lower_ty(t, ImplTraitContext::disallowed()),
3172 self.lower_generics(generics, ImplTraitContext::disallowed()),
3174 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
3175 generics: self.lower_generics(generics, ImplTraitContext::disallowed()),
3176 bounds: self.lower_param_bounds(b, ImplTraitContext::disallowed()),
3177 impl_trait_fn: None,
3178 origin: hir::ExistTyOrigin::ExistentialType,
3180 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
3182 variants: enum_definition
3185 .map(|x| self.lower_variant(x))
3188 self.lower_generics(generics, ImplTraitContext::disallowed()),
3190 ItemKind::Struct(ref struct_def, ref generics) => {
3191 let struct_def = self.lower_variant_data(struct_def);
3192 hir::ItemKind::Struct(
3194 self.lower_generics(generics, ImplTraitContext::disallowed()),
3197 ItemKind::Union(ref vdata, ref generics) => {
3198 let vdata = self.lower_variant_data(vdata);
3199 hir::ItemKind::Union(
3201 self.lower_generics(generics, ImplTraitContext::disallowed()),
3213 let def_id = self.resolver.definitions().local_def_id(id);
3215 // Lower the "impl header" first. This ordering is important
3216 // for in-band lifetimes! Consider `'a` here:
3218 // impl Foo<'a> for u32 {
3219 // fn method(&'a self) { .. }
3222 // Because we start by lowering the `Foo<'a> for u32`
3223 // part, we will add `'a` to the list of generics on
3224 // the impl. When we then encounter it later in the
3225 // method, it will not be considered an in-band
3226 // lifetime to be added, but rather a reference to a
3228 let lowered_trait_impl_id = self.lower_node_id(id);
3229 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
3232 AnonymousLifetimeMode::CreateParameter,
3234 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
3235 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
3238 if let Some(ref trait_ref) = trait_ref {
3239 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
3240 this.trait_impls.entry(def_id).or_default().push(
3241 lowered_trait_impl_id);
3245 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
3247 (trait_ref, lowered_ty)
3251 let new_impl_items = self.with_in_scope_lifetime_defs(
3252 &ast_generics.params,
3256 .map(|item| this.lower_impl_item_ref(item))
3261 hir::ItemKind::Impl(
3262 self.lower_unsafety(unsafety),
3263 self.lower_impl_polarity(polarity),
3264 self.lower_defaultness(defaultness, true /* [1] */),
3271 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
3272 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
3275 .map(|item| self.lower_trait_item_ref(item))
3277 hir::ItemKind::Trait(
3278 self.lower_is_auto(is_auto),
3279 self.lower_unsafety(unsafety),
3280 self.lower_generics(generics, ImplTraitContext::disallowed()),
3285 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
3286 self.lower_generics(generics, ImplTraitContext::disallowed()),
3287 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3289 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
3292 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
3293 // not cause an assertion failure inside the `lower_defaultness` function.
3301 vis: &mut hir::Visibility,
3303 attrs: &hir::HirVec<Attribute>,
3304 ) -> hir::ItemKind {
3305 debug!("lower_use_tree(tree={:?})", tree);
3306 debug!("lower_use_tree: vis = {:?}", vis);
3308 let path = &tree.prefix;
3309 let segments = prefix
3312 .chain(path.segments.iter())
3317 UseTreeKind::Simple(rename, id1, id2) => {
3318 *ident = tree.ident();
3320 // First, apply the prefix to the path.
3321 let mut path = Path {
3326 // Correctly resolve `self` imports.
3327 if path.segments.len() > 1
3328 && path.segments.last().unwrap().ident.name == kw::SelfLower
3330 let _ = path.segments.pop();
3331 if rename.is_none() {
3332 *ident = path.segments.last().unwrap().ident;
3336 let mut resolutions = self.expect_full_res_from_use(id);
3337 // We want to return *something* from this function, so hold onto the first item
3339 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
3341 // Here, we are looping over namespaces, if they exist for the definition
3342 // being imported. We only handle type and value namespaces because we
3343 // won't be dealing with macros in the rest of the compiler.
3344 // Essentially a single `use` which imports two names is desugared into
3346 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
3347 let vis = vis.clone();
3348 let ident = ident.clone();
3349 let mut path = path.clone();
3350 for seg in &mut path.segments {
3351 seg.id = self.sess.next_node_id();
3353 let span = path.span;
3355 self.with_hir_id_owner(new_node_id, |this| {
3356 let new_id = this.lower_node_id(new_node_id);
3357 let res = this.lower_res(res);
3359 this.lower_path_extra(res, &path, ParamMode::Explicit, None);
3360 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
3361 let vis_kind = match vis.node {
3362 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3363 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3364 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3365 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
3366 let path = this.renumber_segment_ids(path);
3367 hir::VisibilityKind::Restricted {
3369 hir_id: this.next_id(),
3373 let vis = respan(vis.span, vis_kind);
3379 attrs: attrs.clone(),
3389 P(self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None));
3390 hir::ItemKind::Use(path, hir::UseKind::Single)
3392 UseTreeKind::Glob => {
3393 let path = P(self.lower_path(
3399 ParamMode::Explicit,
3401 hir::ItemKind::Use(path, hir::UseKind::Glob)
3403 UseTreeKind::Nested(ref trees) => {
3404 // Nested imports are desugared into simple imports.
3405 // So, if we start with
3408 // pub(x) use foo::{a, b};
3411 // we will create three items:
3414 // pub(x) use foo::a;
3415 // pub(x) use foo::b;
3416 // pub(x) use foo::{}; // <-- this is called the `ListStem`
3419 // The first two are produced by recursively invoking
3420 // `lower_use_tree` (and indeed there may be things
3421 // like `use foo::{a::{b, c}}` and so forth). They
3422 // wind up being directly added to
3423 // `self.items`. However, the structure of this
3424 // function also requires us to return one item, and
3425 // for that we return the `{}` import (called the
3430 span: prefix.span.to(path.span),
3433 // Add all the nested `PathListItem`s to the HIR.
3434 for &(ref use_tree, id) in trees {
3435 let new_hir_id = self.lower_node_id(id);
3437 let mut vis = vis.clone();
3438 let mut ident = ident.clone();
3439 let mut prefix = prefix.clone();
3441 // Give the segments new node-ids since they are being cloned.
3442 for seg in &mut prefix.segments {
3443 seg.id = self.sess.next_node_id();
3446 // Each `use` import is an item and thus are owners of the
3447 // names in the path. Up to this point the nested import is
3448 // the current owner, since we want each desugared import to
3449 // own its own names, we have to adjust the owner before
3450 // lowering the rest of the import.
3451 self.with_hir_id_owner(id, |this| {
3452 let item = this.lower_use_tree(use_tree,
3459 let vis_kind = match vis.node {
3460 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3461 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3462 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3463 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
3464 let path = this.renumber_segment_ids(path);
3465 hir::VisibilityKind::Restricted {
3467 hir_id: this.next_id(),
3471 let vis = respan(vis.span, vis_kind);
3477 attrs: attrs.clone(),
3480 span: use_tree.span,
3486 // Subtle and a bit hacky: we lower the privacy level
3487 // of the list stem to "private" most of the time, but
3488 // not for "restricted" paths. The key thing is that
3489 // we don't want it to stay as `pub` (with no caveats)
3490 // because that affects rustdoc and also the lints
3491 // about `pub` items. But we can't *always* make it
3492 // private -- particularly not for restricted paths --
3493 // because it contains node-ids that would then be
3494 // unused, failing the check that HirIds are "densely
3497 hir::VisibilityKind::Public |
3498 hir::VisibilityKind::Crate(_) |
3499 hir::VisibilityKind::Inherited => {
3500 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3502 hir::VisibilityKind::Restricted { .. } => {
3503 // Do nothing here, as described in the comment on the match.
3507 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
3508 let res = self.lower_res(res);
3509 let path = P(self.lower_path_extra(res, &prefix, ParamMode::Explicit, None));
3510 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3515 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
3516 /// many times in the HIR tree; for each occurrence, we need to assign distinct
3517 /// `NodeId`s. (See, e.g., #56128.)
3518 fn renumber_segment_ids(&mut self, path: &P<hir::Path>) -> P<hir::Path> {
3519 debug!("renumber_segment_ids(path = {:?})", path);
3520 let mut path = path.clone();
3521 for seg in path.segments.iter_mut() {
3522 if seg.hir_id.is_some() {
3523 seg.hir_id = Some(self.next_id());
3529 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3530 let trait_item_def_id = self.resolver.definitions().local_def_id(i.id);
3532 let (generics, node) = match i.node {
3533 TraitItemKind::Const(ref ty, ref default) => (
3534 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3535 hir::TraitItemKind::Const(
3536 self.lower_ty(ty, ImplTraitContext::disallowed()),
3539 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
3542 TraitItemKind::Method(ref sig, None) => {
3543 let names = self.lower_fn_args_to_names(&sig.decl);
3544 let (generics, sig) = self.lower_method_sig(
3551 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3553 TraitItemKind::Method(ref sig, Some(ref body)) => {
3554 let body_id = self.lower_body(Some(&sig.decl), |this| {
3555 let body = this.lower_block(body, false);
3556 this.expr_block(body, ThinVec::new())
3558 let (generics, sig) = self.lower_method_sig(
3565 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3567 TraitItemKind::Type(ref bounds, ref default) => (
3568 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3569 hir::TraitItemKind::Type(
3570 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3573 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3576 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3580 hir_id: self.lower_node_id(i.id),
3582 attrs: self.lower_attrs(&i.attrs),
3589 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3590 let (kind, has_default) = match i.node {
3591 TraitItemKind::Const(_, ref default) => {
3592 (hir::AssociatedItemKind::Const, default.is_some())
3594 TraitItemKind::Type(_, ref default) => {
3595 (hir::AssociatedItemKind::Type, default.is_some())
3597 TraitItemKind::Method(ref sig, ref default) => (
3598 hir::AssociatedItemKind::Method {
3599 has_self: sig.decl.has_self(),
3603 TraitItemKind::Macro(..) => unimplemented!(),
3606 id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) },
3609 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3614 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3615 let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
3617 let (generics, node) = match i.node {
3618 ImplItemKind::Const(ref ty, ref expr) => {
3619 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3621 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3622 hir::ImplItemKind::Const(
3623 self.lower_ty(ty, ImplTraitContext::disallowed()),
3628 ImplItemKind::Method(ref sig, ref body) => {
3629 let mut lower_method = |sig: &MethodSig| {
3630 let body_id = self.lower_async_body(
3631 &sig.decl, &sig.header.asyncness.node, body
3633 let impl_trait_return_allow = !self.is_in_trait_impl;
3634 let (generics, sig) = self.lower_method_sig(
3638 impl_trait_return_allow,
3639 sig.header.asyncness.node.opt_return_id(),
3641 (body_id, generics, sig)
3644 let (body_id, generics, sig) = if let IsAsync::Async {
3646 } = sig.header.asyncness.node {
3647 let mut sig = sig.clone();
3648 // Replace the arguments of this async function with the generated
3649 // arguments that will be moved into the closure.
3650 for (i, a) in arguments.clone().drain(..).enumerate() {
3651 if let Some(arg) = a.arg {
3652 sig.decl.inputs[i] = arg;
3659 self.current_item = Some(i.span);
3661 (generics, hir::ImplItemKind::Method(sig, body_id))
3663 ImplItemKind::Type(ref ty) => (
3664 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3665 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3667 ImplItemKind::Existential(ref bounds) => (
3668 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3669 hir::ImplItemKind::Existential(
3670 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3673 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3677 hir_id: self.lower_node_id(i.id),
3679 attrs: self.lower_attrs(&i.attrs),
3681 vis: self.lower_visibility(&i.vis, None),
3682 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3687 // [1] since `default impl` is not yet implemented, this is always true in impls
3690 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3692 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
3695 vis: self.lower_visibility(&i.vis, Some(i.id)),
3696 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3697 kind: match i.node {
3698 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3699 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3700 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3701 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3702 has_self: sig.decl.has_self(),
3704 ImplItemKind::Macro(..) => unimplemented!(),
3708 // [1] since `default impl` is not yet implemented, this is always true in impls
3711 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3714 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3718 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3719 let node_ids = match i.node {
3720 ItemKind::Use(ref use_tree) => {
3721 let mut vec = smallvec![i.id];
3722 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3725 ItemKind::MacroDef(..) => SmallVec::new(),
3727 ItemKind::Impl(.., None, _, _) => smallvec![i.id],
3728 ItemKind::Static(ref ty, ..) => {
3729 let mut ids = smallvec![i.id];
3730 if self.sess.features_untracked().impl_trait_in_bindings {
3731 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3732 visitor.visit_ty(ty);
3736 ItemKind::Const(ref ty, ..) => {
3737 let mut ids = smallvec![i.id];
3738 if self.sess.features_untracked().impl_trait_in_bindings {
3739 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3740 visitor.visit_ty(ty);
3744 _ => smallvec![i.id],
3747 node_ids.into_iter().map(|node_id| hir::ItemId {
3748 id: self.allocate_hir_id_counter(node_id)
3752 fn lower_item_id_use_tree(&mut self,
3755 vec: &mut SmallVec<[NodeId; 1]>)
3758 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3760 self.lower_item_id_use_tree(nested, id, vec);
3762 UseTreeKind::Glob => {}
3763 UseTreeKind::Simple(_, id1, id2) => {
3764 for (_, &id) in self.expect_full_res_from_use(base_id)
3766 .zip([id1, id2].iter())
3774 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3775 let mut ident = i.ident;
3776 let mut vis = self.lower_visibility(&i.vis, None);
3777 let attrs = self.lower_attrs(&i.attrs);
3778 if let ItemKind::MacroDef(ref def) = i.node {
3779 if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) ||
3780 attr::contains_name(&i.attrs, sym::rustc_doc_only_macro) {
3781 let body = self.lower_token_stream(def.stream());
3782 let hir_id = self.lower_node_id(i.id);
3783 self.exported_macros.push(hir::MacroDef {
3796 let node = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.node);
3799 hir_id: self.lower_node_id(i.id),
3808 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3809 let def_id = self.resolver.definitions().local_def_id(i.id);
3811 hir_id: self.lower_node_id(i.id),
3813 attrs: self.lower_attrs(&i.attrs),
3814 node: match i.node {
3815 ForeignItemKind::Fn(ref fdec, ref generics) => {
3816 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3819 AnonymousLifetimeMode::PassThrough,
3822 // Disallow impl Trait in foreign items
3823 this.lower_fn_decl(fdec, None, false, None),
3824 this.lower_fn_args_to_names(fdec),
3829 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3831 ForeignItemKind::Static(ref t, m) => {
3832 hir::ForeignItemKind::Static(
3833 self.lower_ty(t, ImplTraitContext::disallowed()), self.lower_mutability(m))
3835 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3836 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3838 vis: self.lower_visibility(&i.vis, None),
3843 fn lower_method_sig(
3845 generics: &Generics,
3848 impl_trait_return_allow: bool,
3849 is_async: Option<NodeId>,
3850 ) -> (hir::Generics, hir::MethodSig) {
3851 let header = self.lower_fn_header(&sig.header);
3852 let (generics, decl) = self.add_in_band_defs(
3855 AnonymousLifetimeMode::PassThrough,
3856 |this, idty| this.lower_fn_decl(
3858 Some((fn_def_id, idty)),
3859 impl_trait_return_allow,
3863 (generics, hir::MethodSig { header, decl })
3866 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3868 IsAuto::Yes => hir::IsAuto::Yes,
3869 IsAuto::No => hir::IsAuto::No,
3873 fn lower_fn_header(&mut self, h: &FnHeader) -> hir::FnHeader {
3875 unsafety: self.lower_unsafety(h.unsafety),
3876 asyncness: self.lower_asyncness(&h.asyncness.node),
3877 constness: self.lower_constness(h.constness),
3882 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3884 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3885 Unsafety::Normal => hir::Unsafety::Normal,
3889 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3891 Constness::Const => hir::Constness::Const,
3892 Constness::NotConst => hir::Constness::NotConst,
3896 fn lower_asyncness(&mut self, a: &IsAsync) -> hir::IsAsync {
3898 IsAsync::Async { .. } => hir::IsAsync::Async,
3899 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3903 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3905 UnOp::Deref => hir::UnDeref,
3906 UnOp::Not => hir::UnNot,
3907 UnOp::Neg => hir::UnNeg,
3911 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3913 node: match b.node {
3914 BinOpKind::Add => hir::BinOpKind::Add,
3915 BinOpKind::Sub => hir::BinOpKind::Sub,
3916 BinOpKind::Mul => hir::BinOpKind::Mul,
3917 BinOpKind::Div => hir::BinOpKind::Div,
3918 BinOpKind::Rem => hir::BinOpKind::Rem,
3919 BinOpKind::And => hir::BinOpKind::And,
3920 BinOpKind::Or => hir::BinOpKind::Or,
3921 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3922 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3923 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3924 BinOpKind::Shl => hir::BinOpKind::Shl,
3925 BinOpKind::Shr => hir::BinOpKind::Shr,
3926 BinOpKind::Eq => hir::BinOpKind::Eq,
3927 BinOpKind::Lt => hir::BinOpKind::Lt,
3928 BinOpKind::Le => hir::BinOpKind::Le,
3929 BinOpKind::Ne => hir::BinOpKind::Ne,
3930 BinOpKind::Ge => hir::BinOpKind::Ge,
3931 BinOpKind::Gt => hir::BinOpKind::Gt,
3937 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3938 let node = match p.node {
3939 PatKind::Wild => hir::PatKind::Wild,
3940 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3941 match self.resolver.get_partial_res(p.id).map(|d| d.base_res()) {
3942 // `None` can occur in body-less function signatures
3943 res @ None | res @ Some(Res::Local(_)) => {
3944 let canonical_id = match res {
3945 Some(Res::Local(id)) => id,
3949 hir::PatKind::Binding(
3950 self.lower_binding_mode(binding_mode),
3951 self.lower_node_id(canonical_id),
3953 sub.as_ref().map(|x| self.lower_pat(x)),
3956 Some(res) => hir::PatKind::Path(hir::QPath::Resolved(
3960 res: self.lower_res(res),
3961 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3966 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3967 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3968 let qpath = self.lower_qpath(
3972 ParamMode::Optional,
3973 ImplTraitContext::disallowed(),
3975 hir::PatKind::TupleStruct(
3977 pats.iter().map(|x| self.lower_pat(x)).collect(),
3981 PatKind::Path(ref qself, ref path) => {
3982 let qpath = self.lower_qpath(
3986 ParamMode::Optional,
3987 ImplTraitContext::disallowed(),
3989 hir::PatKind::Path(qpath)
3991 PatKind::Struct(ref path, ref fields, etc) => {
3992 let qpath = self.lower_qpath(
3996 ParamMode::Optional,
3997 ImplTraitContext::disallowed(),
4005 node: hir::FieldPat {
4006 hir_id: self.next_id(),
4007 ident: f.node.ident,
4008 pat: self.lower_pat(&f.node.pat),
4009 is_shorthand: f.node.is_shorthand,
4014 hir::PatKind::Struct(qpath, fs, etc)
4016 PatKind::Tuple(ref elts, ddpos) => {
4017 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
4019 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
4020 PatKind::Ref(ref inner, mutbl) => {
4021 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
4023 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
4024 P(self.lower_expr(e1)),
4025 P(self.lower_expr(e2)),
4026 self.lower_range_end(end),
4028 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
4029 before.iter().map(|x| self.lower_pat(x)).collect(),
4030 slice.as_ref().map(|x| self.lower_pat(x)),
4031 after.iter().map(|x| self.lower_pat(x)).collect(),
4033 PatKind::Paren(ref inner) => return self.lower_pat(inner),
4034 PatKind::Mac(_) => panic!("Shouldn't exist here"),
4038 hir_id: self.lower_node_id(p.id),
4044 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
4046 RangeEnd::Included(_) => hir::RangeEnd::Included,
4047 RangeEnd::Excluded => hir::RangeEnd::Excluded,
4051 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
4052 self.with_new_scopes(|this| {
4054 hir_id: this.lower_node_id(c.id),
4055 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
4060 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
4061 let kind = match e.node {
4062 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
4063 ExprKind::Array(ref exprs) => {
4064 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
4066 ExprKind::Repeat(ref expr, ref count) => {
4067 let expr = P(self.lower_expr(expr));
4068 let count = self.lower_anon_const(count);
4069 hir::ExprKind::Repeat(expr, count)
4071 ExprKind::Tup(ref elts) => {
4072 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
4074 ExprKind::Call(ref f, ref args) => {
4075 let f = P(self.lower_expr(f));
4076 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
4078 ExprKind::MethodCall(ref seg, ref args) => {
4079 let hir_seg = P(self.lower_path_segment(
4082 ParamMode::Optional,
4084 ParenthesizedGenericArgs::Err,
4085 ImplTraitContext::disallowed(),
4088 let args = args.iter().map(|x| self.lower_expr(x)).collect();
4089 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
4091 ExprKind::Binary(binop, ref lhs, ref rhs) => {
4092 let binop = self.lower_binop(binop);
4093 let lhs = P(self.lower_expr(lhs));
4094 let rhs = P(self.lower_expr(rhs));
4095 hir::ExprKind::Binary(binop, lhs, rhs)
4097 ExprKind::Unary(op, ref ohs) => {
4098 let op = self.lower_unop(op);
4099 let ohs = P(self.lower_expr(ohs));
4100 hir::ExprKind::Unary(op, ohs)
4102 ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.node.clone())),
4103 ExprKind::Cast(ref expr, ref ty) => {
4104 let expr = P(self.lower_expr(expr));
4105 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4107 ExprKind::Type(ref expr, ref ty) => {
4108 let expr = P(self.lower_expr(expr));
4109 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4111 ExprKind::AddrOf(m, ref ohs) => {
4112 let m = self.lower_mutability(m);
4113 let ohs = P(self.lower_expr(ohs));
4114 hir::ExprKind::AddrOf(m, ohs)
4116 // More complicated than you might expect because the else branch
4117 // might be `if let`.
4118 ExprKind::If(ref cond, ref then, ref else_opt) => {
4120 let then_pat = self.pat_bool(e.span, true);
4121 let then_blk = self.lower_block(then, false);
4122 let then_expr = self.expr_block(then_blk, ThinVec::new());
4123 let then_arm = self.arm(hir_vec![then_pat], P(then_expr));
4125 // `_ => else_block` where `else_block` is `{}` if there's `None`:
4126 let else_pat = self.pat_wild(e.span);
4127 let else_expr = match else_opt {
4128 None => self.expr_block_empty(e.span),
4129 Some(els) => match els.node {
4130 ExprKind::IfLet(..) => {
4131 // Wrap the `if let` expr in a block.
4132 let els = self.lower_expr(els);
4133 let blk = self.block_all(els.span, hir_vec![], Some(P(els)));
4134 self.expr_block(P(blk), ThinVec::new())
4136 _ => self.lower_expr(els),
4139 let else_arm = self.arm(hir_vec![else_pat], P(else_expr));
4142 let span_block = self
4145 .mark_span_with_reason(IfTemporary, cond.span, None);
4146 let cond = self.lower_expr(cond);
4147 // Wrap in a construct equivalent to `{ let _t = $cond; _t }` to preserve drop
4148 // semantics since `if cond { ... }` don't let temporaries live outside of `cond`.
4149 let cond = self.expr_drop_temps(span_block, P(cond), ThinVec::new());
4151 hir::ExprKind::Match(
4153 vec![then_arm, else_arm].into(),
4154 hir::MatchSource::IfDesugar {
4155 contains_else_clause: else_opt.is_some()
4159 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4160 hir::ExprKind::While(
4161 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
4162 this.lower_block(body, false),
4163 this.lower_label(opt_label),
4166 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4167 hir::ExprKind::Loop(
4168 this.lower_block(body, false),
4169 this.lower_label(opt_label),
4170 hir::LoopSource::Loop,
4173 ExprKind::TryBlock(ref body) => {
4174 self.with_catch_scope(body.id, |this| {
4175 let unstable_span = this.sess.source_map().mark_span_with_reason(
4176 CompilerDesugaringKind::TryBlock,
4178 Some(vec![sym::try_trait].into()),
4180 let mut block = this.lower_block(body, true).into_inner();
4181 let tail = block.expr.take().map_or_else(
4183 let span = this.sess.source_map().end_point(unstable_span);
4186 node: hir::ExprKind::Tup(hir_vec![]),
4187 attrs: ThinVec::new(),
4188 hir_id: this.next_id(),
4191 |x: P<hir::Expr>| x.into_inner(),
4193 block.expr = Some(this.wrap_in_try_constructor(
4194 sym::from_ok, tail, unstable_span));
4195 hir::ExprKind::Block(P(block), None)
4198 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
4199 P(self.lower_expr(expr)),
4200 arms.iter().map(|x| self.lower_arm(x)).collect(),
4201 hir::MatchSource::Normal,
4203 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
4204 self.make_async_expr(capture_clause, closure_node_id, None, block.span, |this| {
4205 this.with_new_scopes(|this| {
4206 let block = this.lower_block(block, false);
4207 this.expr_block(block, ThinVec::new())
4211 ExprKind::Await(_origin, ref expr) => self.lower_await(e.span, expr),
4213 capture_clause, ref asyncness, movability, ref decl, ref body, fn_decl_span
4215 if let IsAsync::Async { closure_id, .. } = asyncness {
4216 let outer_decl = FnDecl {
4217 inputs: decl.inputs.clone(),
4218 output: FunctionRetTy::Default(fn_decl_span),
4221 // We need to lower the declaration outside the new scope, because we
4222 // have to conserve the state of being inside a loop condition for the
4223 // closure argument types.
4224 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
4226 self.with_new_scopes(|this| {
4227 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
4228 if capture_clause == CaptureBy::Ref &&
4229 !decl.inputs.is_empty()
4235 "`async` non-`move` closures with arguments \
4236 are not currently supported",
4238 .help("consider using `let` statements to manually capture \
4239 variables by reference before entering an \
4240 `async move` closure")
4244 // Transform `async |x: u8| -> X { ... }` into
4245 // `|x: u8| future_from_generator(|| -> X { ... })`.
4246 let body_id = this.lower_body(Some(&outer_decl), |this| {
4247 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
4250 let async_body = this.make_async_expr(
4251 capture_clause, *closure_id, async_ret_ty, body.span,
4253 this.with_new_scopes(|this| this.lower_expr(body))
4255 this.expr(fn_decl_span, async_body, ThinVec::new())
4257 hir::ExprKind::Closure(
4258 this.lower_capture_clause(capture_clause),
4266 // Lower outside new scope to preserve `is_in_loop_condition`.
4267 let fn_decl = self.lower_fn_decl(decl, None, false, None);
4269 self.with_new_scopes(|this| {
4270 this.current_item = Some(fn_decl_span);
4271 let mut is_generator = false;
4272 let body_id = this.lower_body(Some(decl), |this| {
4273 let e = this.lower_expr(body);
4274 is_generator = this.is_generator;
4277 let generator_option = if is_generator {
4278 if !decl.inputs.is_empty() {
4283 "generators cannot have explicit arguments"
4285 this.sess.abort_if_errors();
4287 Some(match movability {
4288 Movability::Movable => hir::GeneratorMovability::Movable,
4289 Movability::Static => hir::GeneratorMovability::Static,
4292 if movability == Movability::Static {
4297 "closures cannot be static"
4302 hir::ExprKind::Closure(
4303 this.lower_capture_clause(capture_clause),
4312 ExprKind::Block(ref blk, opt_label) => {
4313 hir::ExprKind::Block(self.lower_block(blk,
4314 opt_label.is_some()),
4315 self.lower_label(opt_label))
4317 ExprKind::Assign(ref el, ref er) => {
4318 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
4320 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
4321 self.lower_binop(op),
4322 P(self.lower_expr(el)),
4323 P(self.lower_expr(er)),
4325 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
4326 ExprKind::Index(ref el, ref er) => {
4327 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
4329 // Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
4330 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
4331 let id = self.next_id();
4332 let e1 = self.lower_expr(e1);
4333 let e2 = self.lower_expr(e2);
4334 self.expr_call_std_assoc_fn(
4337 &[sym::ops, sym::RangeInclusive],
4342 ExprKind::Range(ref e1, ref e2, lims) => {
4343 use syntax::ast::RangeLimits::*;
4345 let path = match (e1, e2, lims) {
4346 (&None, &None, HalfOpen) => sym::RangeFull,
4347 (&Some(..), &None, HalfOpen) => sym::RangeFrom,
4348 (&None, &Some(..), HalfOpen) => sym::RangeTo,
4349 (&Some(..), &Some(..), HalfOpen) => sym::Range,
4350 (&None, &Some(..), Closed) => sym::RangeToInclusive,
4351 (&Some(..), &Some(..), Closed) => unreachable!(),
4352 (_, &None, Closed) => self.diagnostic()
4353 .span_fatal(e.span, "inclusive range with no end")
4357 let fields = e1.iter()
4358 .map(|e| ("start", e))
4359 .chain(e2.iter().map(|e| ("end", e)))
4361 let expr = P(self.lower_expr(&e));
4362 let ident = Ident::new(Symbol::intern(s), e.span);
4363 self.field(ident, expr, e.span)
4365 .collect::<P<[hir::Field]>>();
4367 let is_unit = fields.is_empty();
4368 let struct_path = [sym::ops, path];
4369 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
4370 let struct_path = hir::QPath::Resolved(None, P(struct_path));
4373 hir_id: self.lower_node_id(e.id),
4375 hir::ExprKind::Path(struct_path)
4377 hir::ExprKind::Struct(P(struct_path), fields, None)
4380 attrs: e.attrs.clone(),
4383 ExprKind::Path(ref qself, ref path) => {
4384 let qpath = self.lower_qpath(
4388 ParamMode::Optional,
4389 ImplTraitContext::disallowed(),
4391 hir::ExprKind::Path(qpath)
4393 ExprKind::Break(opt_label, ref opt_expr) => {
4394 let destination = if self.is_in_loop_condition && opt_label.is_none() {
4397 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4400 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4402 hir::ExprKind::Break(
4404 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
4407 ExprKind::Continue(opt_label) => {
4408 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
4411 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4414 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4417 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
4418 ExprKind::InlineAsm(ref asm) => {
4419 let hir_asm = hir::InlineAsm {
4420 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
4421 outputs: asm.outputs
4423 .map(|out| hir::InlineAsmOutput {
4424 constraint: out.constraint.clone(),
4426 is_indirect: out.is_indirect,
4427 span: out.expr.span,
4430 asm: asm.asm.clone(),
4431 asm_str_style: asm.asm_str_style,
4432 clobbers: asm.clobbers.clone().into(),
4433 volatile: asm.volatile,
4434 alignstack: asm.alignstack,
4435 dialect: asm.dialect,
4438 let outputs = asm.outputs
4440 .map(|out| self.lower_expr(&out.expr))
4442 let inputs = asm.inputs
4444 .map(|&(_, ref input)| self.lower_expr(input))
4446 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
4448 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4453 ParamMode::Optional,
4454 ImplTraitContext::disallowed(),
4456 fields.iter().map(|x| self.lower_field(x)).collect(),
4457 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4459 ExprKind::Paren(ref ex) => {
4460 let mut ex = self.lower_expr(ex);
4461 // Include parens in span, but only if it is a super-span.
4462 if e.span.contains(ex.span) {
4465 // Merge attributes into the inner expression.
4466 let mut attrs = e.attrs.clone();
4467 attrs.extend::<Vec<_>>(ex.attrs.into());
4472 ExprKind::Yield(ref opt_expr) => {
4473 self.is_generator = true;
4476 .map(|x| self.lower_expr(x))
4477 .unwrap_or_else(|| self.expr_unit(e.span));
4478 hir::ExprKind::Yield(P(expr))
4481 ExprKind::Err => hir::ExprKind::Err,
4483 // Desugar `ExprIfLet`
4484 // from: `if let <pat> = <sub_expr> <body> [<else_opt>]`
4485 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4488 // match <sub_expr> {
4490 // _ => [<else_opt> | ()]
4493 let mut arms = vec![];
4495 // `<pat> => <body>`
4497 let body = self.lower_block(body, false);
4498 let body_expr = P(self.expr_block(body, ThinVec::new()));
4499 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4500 arms.push(self.arm(pats, body_expr));
4503 // _ => [<else_opt>|{}]
4505 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4506 let wildcard_pattern = self.pat_wild(e.span);
4507 let body = if let Some(else_expr) = wildcard_arm {
4508 self.lower_expr(else_expr)
4510 self.expr_block_empty(e.span)
4512 arms.push(self.arm(hir_vec![wildcard_pattern], P(body)));
4515 let contains_else_clause = else_opt.is_some();
4517 let sub_expr = P(self.lower_expr(sub_expr));
4519 hir::ExprKind::Match(
4522 hir::MatchSource::IfLetDesugar {
4523 contains_else_clause,
4528 // Desugar `ExprWhileLet`
4529 // from: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4530 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4533 // [opt_ident]: loop {
4534 // match <sub_expr> {
4540 // Note that the block AND the condition are evaluated in the loop scope.
4541 // This is done to allow `break` from inside the condition of the loop.
4542 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4544 this.lower_block(body, false),
4545 this.expr_break(e.span, ThinVec::new()),
4546 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4550 // `<pat> => <body>`
4552 let body_expr = P(self.expr_block(body, ThinVec::new()));
4553 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4554 self.arm(pats, body_expr)
4559 let pat_under = self.pat_wild(e.span);
4560 self.arm(hir_vec![pat_under], break_expr)
4563 // `match <sub_expr> { ... }`
4564 let arms = hir_vec![pat_arm, break_arm];
4565 let match_expr = self.expr(
4567 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4571 // `[opt_ident]: loop { ... }`
4572 let loop_block = P(self.block_expr(P(match_expr)));
4573 let loop_expr = hir::ExprKind::Loop(
4575 self.lower_label(opt_label),
4576 hir::LoopSource::WhileLet,
4578 // Add attributes to the outer returned expr node.
4582 // Desugar `ExprForLoop`
4583 // from: `[opt_ident]: for <pat> in <head> <body>`
4584 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4588 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4590 // [opt_ident]: loop {
4592 // match ::std::iter::Iterator::next(&mut iter) {
4593 // ::std::option::Option::Some(val) => __next = val,
4594 // ::std::option::Option::None => break
4596 // let <pat> = __next;
4597 // StmtKind::Expr(<body>);
4605 let mut head = self.lower_expr(head);
4606 let head_sp = head.span;
4607 let desugared_span = self.sess.source_map().mark_span_with_reason(
4608 CompilerDesugaringKind::ForLoop,
4612 head.span = desugared_span;
4614 let iter = Ident::with_empty_ctxt(sym::iter);
4616 let next_ident = Ident::with_empty_ctxt(sym::__next);
4617 let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
4620 hir::BindingAnnotation::Mutable,
4623 // `::std::option::Option::Some(val) => __next = val`
4625 let val_ident = Ident::with_empty_ctxt(sym::val);
4626 let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
4627 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat_hid));
4628 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat_hid));
4629 let assign = P(self.expr(
4631 hir::ExprKind::Assign(next_expr, val_expr),
4634 let some_pat = self.pat_some(pat.span, val_pat);
4635 self.arm(hir_vec![some_pat], assign)
4638 // `::std::option::Option::None => break`
4641 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4642 let pat = self.pat_none(e.span);
4643 self.arm(hir_vec![pat], break_expr)
4647 let (iter_pat, iter_pat_nid) = self.pat_ident_binding_mode(
4650 hir::BindingAnnotation::Mutable
4653 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4655 let iter = P(self.expr_ident(head_sp, iter, iter_pat_nid));
4656 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4657 let next_path = &[sym::iter, sym::Iterator, sym::next];
4658 let next_expr = P(self.expr_call_std_path(
4661 hir_vec![ref_mut_iter],
4663 let arms = hir_vec![pat_arm, break_arm];
4667 hir::ExprKind::Match(
4670 hir::MatchSource::ForLoopDesugar
4675 let match_stmt = self.stmt(head_sp, hir::StmtKind::Expr(match_expr));
4677 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat_hid));
4680 let next_let = self.stmt_let_pat(
4684 hir::LocalSource::ForLoopDesugar,
4687 // `let <pat> = __next`
4688 let pat = self.lower_pat(pat);
4689 let pat_let = self.stmt_let_pat(
4693 hir::LocalSource::ForLoopDesugar,
4696 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4697 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4698 let body_stmt = self.stmt(body.span, hir::StmtKind::Expr(body_expr));
4700 let loop_block = P(self.block_all(
4702 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4706 // `[opt_ident]: loop { ... }`
4707 let loop_expr = hir::ExprKind::Loop(
4709 self.lower_label(opt_label),
4710 hir::LoopSource::ForLoop,
4712 let loop_expr = P(hir::Expr {
4713 hir_id: self.lower_node_id(e.id),
4716 attrs: ThinVec::new(),
4719 // `mut iter => { ... }`
4720 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4722 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4723 let into_iter_expr = {
4724 let into_iter_path =
4725 &[sym::iter, sym::IntoIterator, sym::into_iter];
4726 P(self.expr_call_std_path(
4733 let match_expr = P(self.expr_match(
4737 hir::MatchSource::ForLoopDesugar,
4740 // This is effectively `{ let _result = ...; _result }`.
4741 // The construct was introduced in #21984.
4742 // FIXME(60253): Is this still necessary?
4743 // Also, add the attributes to the outer returned expr node.
4744 return self.expr_drop_temps(head_sp, match_expr, e.attrs.clone())
4747 // Desugar `ExprKind::Try`
4749 ExprKind::Try(ref sub_expr) => {
4752 // match Try::into_result(<expr>) {
4753 // Ok(val) => #[allow(unreachable_code)] val,
4754 // Err(err) => #[allow(unreachable_code)]
4755 // // If there is an enclosing `catch {...}`
4756 // break 'catch_target Try::from_error(From::from(err)),
4758 // return Try::from_error(From::from(err)),
4761 let unstable_span = self.sess.source_map().mark_span_with_reason(
4762 CompilerDesugaringKind::QuestionMark,
4764 Some(vec![sym::try_trait].into()),
4766 let try_span = self.sess.source_map().end_point(e.span);
4767 let try_span = self.sess.source_map().mark_span_with_reason(
4768 CompilerDesugaringKind::QuestionMark,
4770 Some(vec![sym::try_trait].into()),
4773 // `Try::into_result(<expr>)`
4776 let sub_expr = self.lower_expr(sub_expr);
4778 let path = &[sym::ops, sym::Try, sym::into_result];
4779 P(self.expr_call_std_path(
4786 // `#[allow(unreachable_code)]`
4788 // `allow(unreachable_code)`
4790 let allow_ident = Ident::with_empty_ctxt(sym::allow).with_span_pos(e.span);
4791 let uc_ident = Ident::with_empty_ctxt(sym::unreachable_code)
4792 .with_span_pos(e.span);
4793 let uc_nested = attr::mk_nested_word_item(uc_ident);
4794 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4796 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4798 let attrs = vec![attr];
4800 // `Ok(val) => #[allow(unreachable_code)] val,`
4802 let val_ident = Ident::with_empty_ctxt(sym::val);
4803 let (val_pat, val_pat_nid) = self.pat_ident(e.span, val_ident);
4804 let val_expr = P(self.expr_ident_with_attrs(
4808 ThinVec::from(attrs.clone()),
4810 let ok_pat = self.pat_ok(e.span, val_pat);
4812 self.arm(hir_vec![ok_pat], val_expr)
4815 // `Err(err) => #[allow(unreachable_code)]
4816 // return Try::from_error(From::from(err)),`
4818 let err_ident = Ident::with_empty_ctxt(sym::err);
4819 let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
4821 let from_path = &[sym::convert, sym::From, sym::from];
4822 let err_expr = self.expr_ident(try_span, err_ident, err_local_nid);
4823 self.expr_call_std_path(try_span, from_path, hir_vec![err_expr])
4826 self.wrap_in_try_constructor(sym::from_error, from_expr, unstable_span);
4827 let thin_attrs = ThinVec::from(attrs);
4828 let catch_scope = self.catch_scopes.last().map(|x| *x);
4829 let ret_expr = if let Some(catch_node) = catch_scope {
4830 let target_id = Ok(self.lower_node_id(catch_node));
4833 hir::ExprKind::Break(
4838 Some(from_err_expr),
4843 P(self.expr(try_span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4846 let err_pat = self.pat_err(try_span, err_local);
4847 self.arm(hir_vec![err_pat], ret_expr)
4850 hir::ExprKind::Match(
4852 hir_vec![err_arm, ok_arm],
4853 hir::MatchSource::TryDesugar,
4857 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4861 hir_id: self.lower_node_id(e.id),
4864 attrs: e.attrs.clone(),
4868 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
4869 smallvec![match s.node {
4870 StmtKind::Local(ref l) => {
4871 let (l, item_ids) = self.lower_local(l);
4872 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
4875 let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
4876 self.stmt(s.span, hir::StmtKind::Item(item_id))
4881 hir_id: self.lower_node_id(s.id),
4882 node: hir::StmtKind::Local(P(l)),
4888 StmtKind::Item(ref it) => {
4889 // Can only use the ID once.
4890 let mut id = Some(s.id);
4891 return self.lower_item_id(it)
4894 let hir_id = id.take()
4895 .map(|id| self.lower_node_id(id))
4896 .unwrap_or_else(|| self.next_id());
4900 node: hir::StmtKind::Item(item_id),
4906 StmtKind::Expr(ref e) => {
4908 hir_id: self.lower_node_id(s.id),
4909 node: hir::StmtKind::Expr(P(self.lower_expr(e))),
4913 StmtKind::Semi(ref e) => {
4915 hir_id: self.lower_node_id(s.id),
4916 node: hir::StmtKind::Semi(P(self.lower_expr(e))),
4920 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4924 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4926 CaptureBy::Value => hir::CaptureByValue,
4927 CaptureBy::Ref => hir::CaptureByRef,
4931 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4932 /// the address space of that item instead of the item currently being
4933 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4934 /// lower a `Visibility` value although we haven't lowered the owning
4935 /// `ImplItem` in question yet.
4936 fn lower_visibility(
4939 explicit_owner: Option<NodeId>,
4940 ) -> hir::Visibility {
4941 let node = match v.node {
4942 VisibilityKind::Public => hir::VisibilityKind::Public,
4943 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4944 VisibilityKind::Restricted { ref path, id } => {
4945 debug!("lower_visibility: restricted path id = {:?}", id);
4946 let lowered_id = if let Some(owner) = explicit_owner {
4947 self.lower_node_id_with_owner(id, owner)
4949 self.lower_node_id(id)
4951 let res = self.expect_full_res(id);
4952 let res = self.lower_res(res);
4953 hir::VisibilityKind::Restricted {
4954 path: P(self.lower_path_extra(
4957 ParamMode::Explicit,
4963 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4965 respan(v.span, node)
4968 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4970 Defaultness::Default => hir::Defaultness::Default {
4971 has_value: has_value,
4973 Defaultness::Final => {
4975 hir::Defaultness::Final
4980 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4982 BlockCheckMode::Default => hir::DefaultBlock,
4983 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4987 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4989 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4990 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4991 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4992 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4996 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4998 CompilerGenerated => hir::CompilerGenerated,
4999 UserProvided => hir::UserProvided,
5003 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
5005 ImplPolarity::Positive => hir::ImplPolarity::Positive,
5006 ImplPolarity::Negative => hir::ImplPolarity::Negative,
5010 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
5012 TraitBoundModifier::None => hir::TraitBoundModifier::None,
5013 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
5017 // Helper methods for building HIR.
5019 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
5021 hir_id: self.next_id(),
5030 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
5032 hir_id: self.next_id(),
5036 is_shorthand: false,
5040 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
5041 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
5042 P(self.expr(span, expr_break, attrs))
5049 args: hir::HirVec<hir::Expr>,
5051 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
5054 // Note: associated functions must use `expr_call_std_path`.
5055 fn expr_call_std_path(
5058 path_components: &[Symbol],
5059 args: hir::HirVec<hir::Expr>,
5061 let path = P(self.expr_std_path(span, path_components, None, ThinVec::new()));
5062 self.expr_call(span, path, args)
5065 // Create an expression calling an associated function of an std type.
5067 // Associated functions cannot be resolved through the normal `std_path` function,
5068 // as they are resolved differently and so cannot use `expr_call_std_path`.
5070 // This function accepts the path component (`ty_path_components`) separately from
5071 // the name of the associated function (`assoc_fn_name`) in order to facilitate
5072 // separate resolution of the type and creation of a path referring to its associated
5074 fn expr_call_std_assoc_fn(
5076 ty_path_id: hir::HirId,
5078 ty_path_components: &[Symbol],
5079 assoc_fn_name: &str,
5080 args: hir::HirVec<hir::Expr>,
5081 ) -> hir::ExprKind {
5082 let ty_path = P(self.std_path(span, ty_path_components, None, false));
5083 let ty = P(self.ty_path(ty_path_id, span, hir::QPath::Resolved(None, ty_path)));
5084 let fn_seg = P(hir::PathSegment::from_ident(Ident::from_str(assoc_fn_name)));
5085 let fn_path = hir::QPath::TypeRelative(ty, fn_seg);
5086 let fn_expr = P(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
5087 hir::ExprKind::Call(fn_expr, args)
5090 fn expr_ident(&mut self, span: Span, ident: Ident, binding: hir::HirId) -> hir::Expr {
5091 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
5094 fn expr_ident_with_attrs(
5098 binding: hir::HirId,
5099 attrs: ThinVec<Attribute>,
5101 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
5105 res: Res::Local(binding),
5106 segments: hir_vec![hir::PathSegment::from_ident(ident)],
5110 self.expr(span, expr_path, attrs)
5113 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
5114 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
5120 components: &[Symbol],
5121 params: Option<P<hir::GenericArgs>>,
5122 attrs: ThinVec<Attribute>,
5124 let path = self.std_path(span, components, params, true);
5127 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
5132 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
5134 /// In terms of drop order, it has the same effect as wrapping `expr` in
5135 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
5137 /// The drop order can be important in e.g. `if expr { .. }`.
5142 attrs: ThinVec<Attribute>
5144 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
5151 arms: hir::HirVec<hir::Arm>,
5152 source: hir::MatchSource,
5154 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
5157 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
5158 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
5161 fn expr_unit(&mut self, sp: Span) -> hir::Expr {
5162 self.expr_tuple(sp, hir_vec![])
5165 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> hir::Expr {
5166 self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new())
5169 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
5171 hir_id: self.next_id(),
5178 fn stmt(&mut self, span: Span, node: hir::StmtKind) -> hir::Stmt {
5179 hir::Stmt { span, node, hir_id: self.next_id() }
5185 init: Option<P<hir::Expr>>,
5187 source: hir::LocalSource,
5189 let local = hir::Local {
5193 hir_id: self.next_id(),
5196 attrs: ThinVec::new()
5198 self.stmt(span, hir::StmtKind::Local(P(local)))
5201 fn expr_block_empty(&mut self, span: Span) -> hir::Expr {
5202 let blk = self.block_all(span, hir_vec![], None);
5203 self.expr_block(P(blk), ThinVec::new())
5206 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
5207 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
5213 stmts: hir::HirVec<hir::Stmt>,
5214 expr: Option<P<hir::Expr>>,
5219 hir_id: self.next_id(),
5220 rules: hir::DefaultBlock,
5222 targeted_by_break: false,
5226 fn expr_unsafe(&mut self, expr: P<hir::Expr>) -> hir::Expr {
5227 let hir_id = self.next_id();
5228 let span = expr.span;
5231 hir::ExprKind::Block(P(hir::Block {
5235 rules: hir::UnsafeBlock(hir::CompilerGenerated),
5237 targeted_by_break: false,
5243 /// Constructs a `true` or `false` literal pattern.
5244 fn pat_bool(&mut self, span: Span, val: bool) -> P<hir::Pat> {
5245 let lit = Spanned { span, node: LitKind::Bool(val) };
5246 let expr = self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new());
5247 self.pat(span, hir::PatKind::Lit(P(expr)))
5250 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5251 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![pat])
5254 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5255 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![pat])
5258 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5259 self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![pat])
5262 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
5263 self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], hir_vec![])
5269 components: &[Symbol],
5270 subpats: hir::HirVec<P<hir::Pat>>,
5272 let path = self.std_path(span, components, None, true);
5273 let qpath = hir::QPath::Resolved(None, P(path));
5274 let pt = if subpats.is_empty() {
5275 hir::PatKind::Path(qpath)
5277 hir::PatKind::TupleStruct(qpath, subpats, None)
5282 fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<hir::Pat>, hir::HirId) {
5283 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
5286 fn pat_ident_binding_mode(
5290 bm: hir::BindingAnnotation,
5291 ) -> (P<hir::Pat>, hir::HirId) {
5292 let hir_id = self.next_id();
5297 node: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
5304 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
5305 self.pat(span, hir::PatKind::Wild)
5308 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
5310 hir_id: self.next_id(),
5316 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
5317 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
5318 /// The path is also resolved according to `is_value`.
5322 components: &[Symbol],
5323 params: Option<P<hir::GenericArgs>>,
5326 let mut path = self.resolver
5327 .resolve_str_path(span, self.crate_root, components, is_value);
5328 path.segments.last_mut().unwrap().args = params;
5330 for seg in path.segments.iter_mut() {
5331 if seg.hir_id.is_some() {
5332 seg.hir_id = Some(self.next_id());
5338 fn ty_path(&mut self, mut hir_id: hir::HirId, span: Span, qpath: hir::QPath) -> hir::Ty {
5339 let node = match qpath {
5340 hir::QPath::Resolved(None, path) => {
5341 // Turn trait object paths into `TyKind::TraitObject` instead.
5343 Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
5344 let principal = hir::PolyTraitRef {
5345 bound_generic_params: hir::HirVec::new(),
5346 trait_ref: hir::TraitRef {
5347 path: path.and_then(|path| path),
5353 // The original ID is taken by the `PolyTraitRef`,
5354 // so the `Ty` itself needs a different one.
5355 hir_id = self.next_id();
5356 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
5358 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
5361 _ => hir::TyKind::Path(qpath),
5370 /// Invoked to create the lifetime argument for a type `&T`
5371 /// with no explicit lifetime.
5372 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
5373 match self.anonymous_lifetime_mode {
5374 // Intercept when we are in an impl header or async fn and introduce an in-band
5376 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
5378 AnonymousLifetimeMode::CreateParameter => {
5379 let fresh_name = self.collect_fresh_in_band_lifetime(span);
5381 hir_id: self.next_id(),
5383 name: hir::LifetimeName::Param(fresh_name),
5387 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5389 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5391 AnonymousLifetimeMode::Replace(replacement) => {
5392 self.new_replacement_lifetime(replacement, span)
5397 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
5398 /// return a "error lifetime".
5399 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
5400 let (id, msg, label) = match id {
5401 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
5404 self.sess.next_node_id(),
5405 "`&` without an explicit lifetime name cannot be used here",
5406 "explicit lifetime name needed here",
5410 let mut err = struct_span_err!(
5417 err.span_label(span, label);
5420 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5423 /// Invoked to create the lifetime argument(s) for a path like
5424 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
5425 /// sorts of cases are deprecated. This may therefore report a warning or an
5426 /// error, depending on the mode.
5427 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
5429 .map(|_| self.elided_path_lifetime(span))
5433 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
5434 match self.anonymous_lifetime_mode {
5435 AnonymousLifetimeMode::CreateParameter => {
5436 // We should have emitted E0726 when processing this path above
5437 self.sess.delay_span_bug(
5439 "expected 'implicit elided lifetime not allowed' error",
5441 let id = self.sess.next_node_id();
5442 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5444 // This is the normal case.
5445 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5447 AnonymousLifetimeMode::Replace(replacement) => {
5448 self.new_replacement_lifetime(replacement, span)
5451 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5455 /// Invoked to create the lifetime argument(s) for an elided trait object
5456 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
5457 /// when the bound is written, even if it is written with `'_` like in
5458 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
5459 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
5460 match self.anonymous_lifetime_mode {
5461 // NB. We intentionally ignore the create-parameter mode here.
5462 // and instead "pass through" to resolve-lifetimes, which will apply
5463 // the object-lifetime-defaulting rules. Elided object lifetime defaults
5464 // do not act like other elided lifetimes. In other words, given this:
5466 // impl Foo for Box<dyn Debug>
5468 // we do not introduce a fresh `'_` to serve as the bound, but instead
5469 // ultimately translate to the equivalent of:
5471 // impl Foo for Box<dyn Debug + 'static>
5473 // `resolve_lifetime` has the code to make that happen.
5474 AnonymousLifetimeMode::CreateParameter => {}
5476 AnonymousLifetimeMode::ReportError => {
5477 // ReportError applies to explicit use of `'_`.
5480 // This is the normal case.
5481 AnonymousLifetimeMode::PassThrough => {}
5483 // We don't need to do any replacement here as this lifetime
5484 // doesn't refer to an elided lifetime elsewhere in the function
5486 AnonymousLifetimeMode::Replace(_) => {}
5489 self.new_implicit_lifetime(span)
5492 fn new_replacement_lifetime(
5494 replacement: LtReplacement,
5496 ) -> hir::Lifetime {
5497 let hir_id = self.next_id();
5498 self.replace_elided_lifetime(hir_id, span, replacement)
5501 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
5503 hir_id: self.next_id(),
5505 name: hir::LifetimeName::Implicit,
5509 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
5510 self.sess.buffer_lint_with_diagnostic(
5511 builtin::BARE_TRAIT_OBJECTS,
5514 "trait objects without an explicit `dyn` are deprecated",
5515 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
5519 fn wrap_in_try_constructor(
5523 unstable_span: Span,
5525 let path = &[sym::ops, sym::Try, method];
5526 let from_err = P(self.expr_std_path(unstable_span, path, None,
5528 P(self.expr_call(e.span, from_err, hir_vec![e]))
5535 ) -> hir::ExprKind {
5539 // let mut pinned = <expr>;
5541 // match ::std::future::poll_with_tls_context(unsafe {
5542 // ::std::pin::Pin::new_unchecked(&mut pinned)
5544 // ::std::task::Poll::Ready(result) => break result,
5545 // ::std::task::Poll::Pending => {},
5550 if !self.is_async_body {
5551 let mut err = struct_span_err!(
5555 "`await` is only allowed inside `async` functions and blocks"
5557 err.span_label(await_span, "only allowed inside `async` functions and blocks");
5558 if let Some(item_sp) = self.current_item {
5559 err.span_label(item_sp, "this is not `async`");
5562 return hir::ExprKind::Err;
5564 let span = self.sess.source_map().mark_span_with_reason(
5565 CompilerDesugaringKind::Await,
5569 let gen_future_span = self.sess.source_map().mark_span_with_reason(
5570 CompilerDesugaringKind::Await,
5572 Some(vec![sym::gen_future].into()),
5575 // let mut pinned = <expr>;
5576 let expr = P(self.lower_expr(expr));
5577 let pinned_ident = Ident::with_empty_ctxt(sym::pinned);
5578 let (pinned_pat, pinned_pat_hid) = self.pat_ident_binding_mode(
5581 hir::BindingAnnotation::Mutable,
5583 let pinned_let = self.stmt_let_pat(
5587 hir::LocalSource::AwaitDesugar,
5590 // ::std::future::poll_with_tls_context(unsafe {
5591 // ::std::pin::Pin::new_unchecked(&mut pinned)
5594 let pinned = P(self.expr_ident(span, pinned_ident, pinned_pat_hid));
5595 let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
5596 let pin_ty_id = self.next_id();
5597 let new_unchecked_expr_kind = self.expr_call_std_assoc_fn(
5600 &[sym::pin, sym::Pin],
5602 hir_vec![ref_mut_pinned],
5604 let new_unchecked = P(self.expr(span, new_unchecked_expr_kind, ThinVec::new()));
5605 let unsafe_expr = self.expr_unsafe(new_unchecked);
5606 P(self.expr_call_std_path(
5608 &[sym::future, sym::poll_with_tls_context],
5609 hir_vec![unsafe_expr],
5613 // `::std::task::Poll::Ready(result) => break result`
5614 let loop_node_id = self.sess.next_node_id();
5615 let loop_hir_id = self.lower_node_id(loop_node_id);
5617 let x_ident = Ident::with_empty_ctxt(sym::result);
5618 let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
5619 let x_expr = P(self.expr_ident(span, x_ident, x_pat_hid));
5620 let ready_pat = self.pat_std_enum(
5622 &[sym::task, sym::Poll, sym::Ready],
5625 let break_x = self.with_loop_scope(loop_node_id, |this| {
5626 let expr_break = hir::ExprKind::Break(
5627 this.lower_loop_destination(None),
5630 P(this.expr(await_span, expr_break, ThinVec::new()))
5632 self.arm(hir_vec![ready_pat], break_x)
5635 // `::std::task::Poll::Pending => {}`
5637 let pending_pat = self.pat_std_enum(
5639 &[sym::task, sym::Poll, sym::Pending],
5642 let empty_block = P(self.expr_block_empty(span));
5643 self.arm(hir_vec![pending_pat], empty_block)
5647 let match_expr = P(self.expr_match(
5650 hir_vec![ready_arm, pending_arm],
5651 hir::MatchSource::AwaitDesugar,
5653 self.stmt(span, hir::StmtKind::Expr(match_expr))
5657 let unit = self.expr_unit(span);
5658 let yield_expr = P(self.expr(
5660 hir::ExprKind::Yield(P(unit)),
5663 self.stmt(span, hir::StmtKind::Expr(yield_expr))
5666 let loop_block = P(self.block_all(
5668 hir_vec![match_stmt, yield_stmt],
5672 let loop_expr = P(hir::Expr {
5673 hir_id: loop_hir_id,
5674 node: hir::ExprKind::Loop(
5677 hir::LoopSource::Loop,
5680 attrs: ThinVec::new(),
5683 hir::ExprKind::Block(
5684 P(self.block_all(span, hir_vec![pinned_let], Some(loop_expr))),
5690 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5691 // Sorting by span ensures that we get things in order within a
5692 // file, and also puts the files in a sensible order.
5693 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5694 body_ids.sort_by_key(|b| bodies[b].value.span);
5698 /// Checks if the specified expression is a built-in range literal.
5699 /// (See: `LoweringContext::lower_expr()`).
5700 pub fn is_range_literal(sess: &Session, expr: &hir::Expr) -> bool {
5701 use hir::{Path, QPath, ExprKind, TyKind};
5703 // Returns whether the given path represents a (desugared) range,
5704 // either in std or core, i.e. has either a `::std::ops::Range` or
5705 // `::core::ops::Range` prefix.
5706 fn is_range_path(path: &Path) -> bool {
5707 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.as_str().to_string()).collect();
5708 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
5710 // "{{root}}" is the equivalent of `::` prefix in `Path`.
5711 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
5712 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
5718 // Check whether a span corresponding to a range expression is a
5719 // range literal, rather than an explicit struct or `new()` call.
5720 fn is_lit(sess: &Session, span: &Span) -> bool {
5721 let source_map = sess.source_map();
5722 let end_point = source_map.end_point(*span);
5724 if let Ok(end_string) = source_map.span_to_snippet(end_point) {
5725 !(end_string.ends_with("}") || end_string.ends_with(")"))
5732 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
5733 ExprKind::Struct(ref qpath, _, _) => {
5734 if let QPath::Resolved(None, ref path) = **qpath {
5735 return is_range_path(&path) && is_lit(sess, &expr.span);
5739 // `..` desugars to its struct path.
5740 ExprKind::Path(QPath::Resolved(None, ref path)) => {
5741 return is_range_path(&path) && is_lit(sess, &expr.span);
5744 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
5745 ExprKind::Call(ref func, _) => {
5746 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.node {
5747 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.node {
5748 let new_call = segment.ident.as_str() == "new";
5749 return is_range_path(&path) && is_lit(sess, &expr.span) && new_call;