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 // FIXME(const_generics): the compiler doesn't always cope with
1087 // unsorted generic parameters at the moment, so we make sure
1088 // that they're ordered correctly here for now. (When we chain
1089 // the `in_band_defs`, we might make the order unsorted.)
1090 lowered_generics.params.sort_by_key(|param| {
1092 hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime,
1093 hir::GenericParamKind::Type { .. } => ParamKindOrd::Type,
1094 hir::GenericParamKind::Const { .. } => ParamKindOrd::Const,
1098 (lowered_generics, res)
1101 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
1103 F: FnOnce(&mut LoweringContext<'_>) -> T,
1105 let len = self.catch_scopes.len();
1106 self.catch_scopes.push(catch_id);
1108 let result = f(self);
1111 self.catch_scopes.len(),
1112 "catch scopes should be added and removed in stack order"
1115 self.catch_scopes.pop().unwrap();
1122 capture_clause: CaptureBy,
1123 closure_node_id: NodeId,
1124 ret_ty: Option<&Ty>,
1126 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1127 ) -> hir::ExprKind {
1128 let prev_is_generator = mem::replace(&mut self.is_generator, false);
1129 let prev_is_async_body = mem::replace(&mut self.is_async_body, true);
1130 let output = match ret_ty {
1131 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
1132 None => FunctionRetTy::Default(span),
1139 // Lower the arguments before the body otherwise the body will call `lower_res` expecting
1140 // the argument to have been assigned an id already.
1141 let arguments = self.lower_args(Some(&decl));
1142 let body_expr = body(self);
1143 let body_id = self.record_body(body_expr, arguments);
1144 self.is_generator = prev_is_generator;
1145 self.is_async_body = prev_is_async_body;
1147 let capture_clause = self.lower_capture_clause(capture_clause);
1148 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
1149 let generator = hir::Expr {
1150 hir_id: self.lower_node_id(closure_node_id),
1151 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
1152 Some(hir::GeneratorMovability::Static)),
1154 attrs: ThinVec::new(),
1157 let unstable_span = self.sess.source_map().mark_span_with_reason(
1158 CompilerDesugaringKind::Async,
1160 Some(vec![sym::gen_future].into()),
1162 let gen_future = self.expr_std_path(
1163 unstable_span, &[sym::future, sym::from_generator], None, ThinVec::new());
1164 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
1167 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
1169 F: FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1171 let prev_generator = mem::replace(&mut self.is_generator, false);
1172 let prev_async = mem::replace(&mut self.is_async_body, false);
1173 let arguments = self.lower_args(decl);
1174 let result = f(self);
1175 let r = self.record_body(result, arguments);
1176 self.is_generator = prev_generator;
1177 self.is_async_body = prev_async;
1181 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
1183 F: FnOnce(&mut LoweringContext<'_>) -> T,
1185 // We're no longer in the base loop's condition; we're in another loop.
1186 let was_in_loop_condition = self.is_in_loop_condition;
1187 self.is_in_loop_condition = false;
1189 let len = self.loop_scopes.len();
1190 self.loop_scopes.push(loop_id);
1192 let result = f(self);
1195 self.loop_scopes.len(),
1196 "Loop scopes should be added and removed in stack order"
1199 self.loop_scopes.pop().unwrap();
1201 self.is_in_loop_condition = was_in_loop_condition;
1206 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
1208 F: FnOnce(&mut LoweringContext<'_>) -> T,
1210 let was_in_loop_condition = self.is_in_loop_condition;
1211 self.is_in_loop_condition = true;
1213 let result = f(self);
1215 self.is_in_loop_condition = was_in_loop_condition;
1220 fn with_new_scopes<T, F>(&mut self, f: F) -> T
1222 F: FnOnce(&mut LoweringContext<'_>) -> T,
1224 let was_in_loop_condition = self.is_in_loop_condition;
1225 self.is_in_loop_condition = false;
1227 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
1228 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
1230 self.catch_scopes = catch_scopes;
1231 self.loop_scopes = loop_scopes;
1233 self.is_in_loop_condition = was_in_loop_condition;
1238 fn def_key(&mut self, id: DefId) -> DefKey {
1240 self.resolver.definitions().def_key(id.index)
1242 self.cstore.def_key(id)
1246 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1247 label.map(|label| hir::Label {
1252 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1253 let target_id = match destination {
1255 if let Some(loop_id) = self.resolver.get_label_res(id) {
1256 Ok(self.lower_node_id(loop_id))
1258 Err(hir::LoopIdError::UnresolvedLabel)
1265 .map(|id| Ok(self.lower_node_id(id)))
1266 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1271 label: self.lower_label(destination.map(|(_, label)| label)),
1276 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1279 .map(|a| self.lower_attr(a))
1283 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1284 // Note that we explicitly do not walk the path. Since we don't really
1285 // lower attributes (we use the AST version) there is nowhere to keep
1286 // the `HirId`s. We don't actually need HIR version of attributes anyway.
1290 path: attr.path.clone(),
1291 tokens: self.lower_token_stream(attr.tokens.clone()),
1292 is_sugared_doc: attr.is_sugared_doc,
1297 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1300 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1304 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1306 TokenTree::Token(span, token) => self.lower_token(token, span),
1307 TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1310 self.lower_token_stream(tts),
1315 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1317 Token::Interpolated(nt) => {
1318 let tts = nt.to_tokenstream(&self.sess.parse_sess, span);
1319 self.lower_token_stream(tts)
1321 other => TokenTree::Token(span, other).into(),
1325 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1327 hir_id: self.next_id(),
1328 attrs: self.lower_attrs(&arm.attrs),
1329 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1330 guard: match arm.guard {
1331 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1334 body: P(self.lower_expr(&arm.body)),
1339 fn lower_ty_binding(&mut self, b: &TypeBinding,
1340 itctx: ImplTraitContext<'_>) -> hir::TypeBinding {
1342 hir_id: self.lower_node_id(b.id),
1344 ty: self.lower_ty(&b.ty, itctx),
1349 fn lower_generic_arg(&mut self,
1350 arg: &ast::GenericArg,
1351 itctx: ImplTraitContext<'_>)
1352 -> hir::GenericArg {
1354 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1355 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1356 ast::GenericArg::Const(ct) => {
1357 GenericArg::Const(ConstArg {
1358 value: self.lower_anon_const(&ct),
1359 span: ct.value.span,
1365 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1366 P(self.lower_ty_direct(t, itctx))
1369 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1370 let kind = match t.node {
1371 TyKind::Infer => hir::TyKind::Infer,
1372 TyKind::Err => hir::TyKind::Err,
1373 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1374 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1375 TyKind::Rptr(ref region, ref mt) => {
1376 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1377 let lifetime = match *region {
1378 Some(ref lt) => self.lower_lifetime(lt),
1379 None => self.elided_ref_lifetime(span),
1381 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1383 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1386 this.with_anonymous_lifetime_mode(
1387 AnonymousLifetimeMode::PassThrough,
1389 hir::TyKind::BareFn(P(hir::BareFnTy {
1390 generic_params: this.lower_generic_params(
1392 &NodeMap::default(),
1393 ImplTraitContext::disallowed(),
1395 unsafety: this.lower_unsafety(f.unsafety),
1397 decl: this.lower_fn_decl(&f.decl, None, false, None),
1398 arg_names: this.lower_fn_args_to_names(&f.decl),
1404 TyKind::Never => hir::TyKind::Never,
1405 TyKind::Tup(ref tys) => {
1406 hir::TyKind::Tup(tys.iter().map(|ty| {
1407 self.lower_ty_direct(ty, itctx.reborrow())
1410 TyKind::Paren(ref ty) => {
1411 return self.lower_ty_direct(ty, itctx);
1413 TyKind::Path(ref qself, ref path) => {
1414 let id = self.lower_node_id(t.id);
1415 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1416 let ty = self.ty_path(id, t.span, qpath);
1417 if let hir::TyKind::TraitObject(..) = ty.node {
1418 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1422 TyKind::ImplicitSelf => {
1423 let res = self.expect_full_res(t.id);
1424 let res = self.lower_res(res);
1425 hir::TyKind::Path(hir::QPath::Resolved(
1429 segments: hir_vec![hir::PathSegment::from_ident(
1430 Ident::with_empty_ctxt(kw::SelfUpper)
1436 TyKind::Array(ref ty, ref length) => {
1437 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1439 TyKind::Typeof(ref expr) => {
1440 hir::TyKind::Typeof(self.lower_anon_const(expr))
1442 TyKind::TraitObject(ref bounds, kind) => {
1443 let mut lifetime_bound = None;
1446 .filter_map(|bound| match *bound {
1447 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1448 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1450 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1451 GenericBound::Outlives(ref lifetime) => {
1452 if lifetime_bound.is_none() {
1453 lifetime_bound = Some(self.lower_lifetime(lifetime));
1459 let lifetime_bound =
1460 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1461 if kind != TraitObjectSyntax::Dyn {
1462 self.maybe_lint_bare_trait(t.span, t.id, false);
1464 hir::TyKind::TraitObject(bounds, lifetime_bound)
1466 TyKind::ImplTrait(def_node_id, ref bounds) => {
1469 ImplTraitContext::Existential(fn_def_id) => {
1470 self.lower_existential_impl_trait(
1471 span, fn_def_id, def_node_id,
1472 |this| this.lower_param_bounds(bounds, itctx),
1475 ImplTraitContext::Universal(in_band_ty_params) => {
1476 // Add a definition for the in-band `Param`.
1477 let def_index = self
1480 .opt_def_index(def_node_id)
1483 let hir_bounds = self.lower_param_bounds(
1485 ImplTraitContext::Universal(in_band_ty_params),
1487 // Set the name to `impl Bound1 + Bound2`.
1488 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1489 in_band_ty_params.push(hir::GenericParam {
1490 hir_id: self.lower_node_id(def_node_id),
1491 name: ParamName::Plain(ident),
1492 pure_wrt_drop: false,
1496 kind: hir::GenericParamKind::Type {
1498 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1502 hir::TyKind::Path(hir::QPath::Resolved(
1506 res: Res::Def(DefKind::TyParam, DefId::local(def_index)),
1507 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1511 ImplTraitContext::Disallowed(pos) => {
1512 let allowed_in = if self.sess.features_untracked()
1513 .impl_trait_in_bindings {
1514 "bindings or function and inherent method return types"
1516 "function and inherent method return types"
1518 let mut err = struct_span_err!(
1522 "`impl Trait` not allowed outside of {}",
1525 if pos == ImplTraitPosition::Binding &&
1526 nightly_options::is_nightly_build() {
1528 "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1536 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1537 TyKind::CVarArgs => {
1538 // Create the implicit lifetime of the "spoofed" `VaList`.
1539 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1540 let lt = self.new_implicit_lifetime(span);
1541 hir::TyKind::CVarArgs(lt)
1548 hir_id: self.lower_node_id(t.id),
1552 fn lower_existential_impl_trait(
1555 fn_def_id: Option<DefId>,
1556 exist_ty_node_id: NodeId,
1557 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1559 // Make sure we know that some funky desugaring has been going on here.
1560 // This is a first: there is code in other places like for loop
1561 // desugaring that explicitly states that we don't want to track that.
1562 // Not tracking it makes lints in rustc and clippy very fragile as
1563 // frequently opened issues show.
1564 let exist_ty_span = self.sess.source_map().mark_span_with_reason(
1565 CompilerDesugaringKind::ExistentialReturnType,
1570 let exist_ty_def_index = self
1573 .opt_def_index(exist_ty_node_id)
1576 self.allocate_hir_id_counter(exist_ty_node_id);
1578 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1580 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1586 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1587 let exist_ty_item = hir::ExistTy {
1588 generics: hir::Generics {
1589 params: lifetime_defs,
1590 where_clause: hir::WhereClause {
1591 hir_id: lctx.next_id(),
1592 predicates: hir_vec![],
1597 impl_trait_fn: fn_def_id,
1598 origin: hir::ExistTyOrigin::ReturnImplTrait,
1601 trace!("exist ty from impl trait def index: {:#?}", exist_ty_def_index);
1602 let exist_ty_id = lctx.generate_existential_type(
1609 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1610 hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, lifetimes)
1614 /// Registers a new existential type with the proper NodeIds and
1615 /// returns the lowered node ID for the existential type.
1616 fn generate_existential_type(
1618 exist_ty_node_id: NodeId,
1619 exist_ty_item: hir::ExistTy,
1621 exist_ty_span: Span,
1623 let exist_ty_item_kind = hir::ItemKind::Existential(exist_ty_item);
1624 let exist_ty_id = self.lower_node_id(exist_ty_node_id);
1625 // Generate an `existential type Foo: Trait;` declaration.
1626 trace!("registering existential type with id {:#?}", exist_ty_id);
1627 let exist_ty_item = hir::Item {
1628 hir_id: exist_ty_id,
1629 ident: Ident::invalid(),
1630 attrs: Default::default(),
1631 node: exist_ty_item_kind,
1632 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1633 span: exist_ty_span,
1636 // Insert the item into the global item list. This usually happens
1637 // automatically for all AST items. But this existential type item
1638 // does not actually exist in the AST.
1639 self.insert_item(exist_ty_item);
1643 fn lifetimes_from_impl_trait_bounds(
1645 exist_ty_id: NodeId,
1646 parent_index: DefIndex,
1647 bounds: &hir::GenericBounds,
1648 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1649 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1650 // appear in the bounds, excluding lifetimes that are created within the bounds.
1651 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1652 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1653 context: &'r mut LoweringContext<'a>,
1655 exist_ty_id: NodeId,
1656 collect_elided_lifetimes: bool,
1657 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1658 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1659 output_lifetimes: Vec<hir::GenericArg>,
1660 output_lifetime_params: Vec<hir::GenericParam>,
1663 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1664 fn nested_visit_map<'this>(
1666 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1667 hir::intravisit::NestedVisitorMap::None
1670 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1671 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1672 if parameters.parenthesized {
1673 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1674 self.collect_elided_lifetimes = false;
1675 hir::intravisit::walk_generic_args(self, span, parameters);
1676 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1678 hir::intravisit::walk_generic_args(self, span, parameters);
1682 fn visit_ty(&mut self, t: &'v hir::Ty) {
1683 // Don't collect elided lifetimes used inside of `fn()` syntax.
1684 if let hir::TyKind::BareFn(_) = t.node {
1685 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1686 self.collect_elided_lifetimes = false;
1688 // Record the "stack height" of `for<'a>` lifetime bindings
1689 // to be able to later fully undo their introduction.
1690 let old_len = self.currently_bound_lifetimes.len();
1691 hir::intravisit::walk_ty(self, t);
1692 self.currently_bound_lifetimes.truncate(old_len);
1694 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1696 hir::intravisit::walk_ty(self, t)
1700 fn visit_poly_trait_ref(
1702 trait_ref: &'v hir::PolyTraitRef,
1703 modifier: hir::TraitBoundModifier,
1705 // Record the "stack height" of `for<'a>` lifetime bindings
1706 // to be able to later fully undo their introduction.
1707 let old_len = self.currently_bound_lifetimes.len();
1708 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1709 self.currently_bound_lifetimes.truncate(old_len);
1712 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1713 // Record the introduction of 'a in `for<'a> ...`.
1714 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1715 // Introduce lifetimes one at a time so that we can handle
1716 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1717 let lt_name = hir::LifetimeName::Param(param.name);
1718 self.currently_bound_lifetimes.push(lt_name);
1721 hir::intravisit::walk_generic_param(self, param);
1724 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1725 let name = match lifetime.name {
1726 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1727 if self.collect_elided_lifetimes {
1728 // Use `'_` for both implicit and underscore lifetimes in
1729 // `abstract type Foo<'_>: SomeTrait<'_>;`.
1730 hir::LifetimeName::Underscore
1735 hir::LifetimeName::Param(_) => lifetime.name,
1736 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1739 if !self.currently_bound_lifetimes.contains(&name)
1740 && !self.already_defined_lifetimes.contains(&name) {
1741 self.already_defined_lifetimes.insert(name);
1743 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1744 hir_id: self.context.next_id(),
1745 span: lifetime.span,
1749 let def_node_id = self.context.sess.next_node_id();
1751 self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1752 self.context.resolver.definitions().create_def_with_parent(
1755 DefPathData::LifetimeNs(name.ident().as_interned_str()),
1760 let (name, kind) = match name {
1761 hir::LifetimeName::Underscore => (
1762 hir::ParamName::Plain(Ident::with_empty_ctxt(kw::UnderscoreLifetime)),
1763 hir::LifetimeParamKind::Elided,
1765 hir::LifetimeName::Param(param_name) => (
1767 hir::LifetimeParamKind::Explicit,
1769 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1772 self.output_lifetime_params.push(hir::GenericParam {
1775 span: lifetime.span,
1776 pure_wrt_drop: false,
1779 kind: hir::GenericParamKind::Lifetime { kind }
1785 let mut lifetime_collector = ImplTraitLifetimeCollector {
1787 parent: parent_index,
1789 collect_elided_lifetimes: true,
1790 currently_bound_lifetimes: Vec::new(),
1791 already_defined_lifetimes: FxHashSet::default(),
1792 output_lifetimes: Vec::new(),
1793 output_lifetime_params: Vec::new(),
1796 for bound in bounds {
1797 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1801 lifetime_collector.output_lifetimes.into(),
1802 lifetime_collector.output_lifetime_params.into(),
1806 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1811 .map(|x| self.lower_foreign_item(x))
1816 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1823 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1825 node: hir::VariantKind {
1826 ident: v.node.ident,
1827 id: self.lower_node_id(v.node.id),
1828 attrs: self.lower_attrs(&v.node.attrs),
1829 data: self.lower_variant_data(&v.node.data),
1830 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1839 qself: &Option<QSelf>,
1841 param_mode: ParamMode,
1842 mut itctx: ImplTraitContext<'_>,
1844 let qself_position = qself.as_ref().map(|q| q.position);
1845 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1847 let partial_res = self.resolver
1848 .get_partial_res(id)
1849 .unwrap_or_else(|| PartialRes::new(Res::Err));
1851 let proj_start = p.segments.len() - partial_res.unresolved_segments();
1852 let path = P(hir::Path {
1853 res: self.lower_res(partial_res.base_res()),
1854 segments: p.segments[..proj_start]
1857 .map(|(i, segment)| {
1858 let param_mode = match (qself_position, param_mode) {
1859 (Some(j), ParamMode::Optional) if i < j => {
1860 // This segment is part of the trait path in a
1861 // qualified path - one of `a`, `b` or `Trait`
1862 // in `<X as a::b::Trait>::T::U::method`.
1868 // Figure out if this is a type/trait segment,
1869 // which may need lifetime elision performed.
1870 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1871 krate: def_id.krate,
1872 index: this.def_key(def_id).parent.expect("missing parent"),
1874 let type_def_id = match partial_res.base_res() {
1875 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
1876 Some(parent_def_id(self, def_id))
1878 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
1879 Some(parent_def_id(self, def_id))
1881 Res::Def(DefKind::Struct, def_id)
1882 | Res::Def(DefKind::Union, def_id)
1883 | Res::Def(DefKind::Enum, def_id)
1884 | Res::Def(DefKind::TyAlias, def_id)
1885 | Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start =>
1891 let parenthesized_generic_args = match partial_res.base_res() {
1892 // `a::b::Trait(Args)`
1893 Res::Def(DefKind::Trait, _)
1894 if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1895 // `a::b::Trait(Args)::TraitItem`
1896 Res::Def(DefKind::Method, _)
1897 | Res::Def(DefKind::AssocConst, _)
1898 | Res::Def(DefKind::AssocTy, _)
1899 if i + 2 == proj_start =>
1901 ParenthesizedGenericArgs::Ok
1903 // Avoid duplicated errors.
1904 Res::Err => ParenthesizedGenericArgs::Ok,
1906 Res::Def(DefKind::Struct, _)
1907 | Res::Def(DefKind::Enum, _)
1908 | Res::Def(DefKind::Union, _)
1909 | Res::Def(DefKind::TyAlias, _)
1910 | Res::Def(DefKind::Variant, _) if i + 1 == proj_start =>
1912 ParenthesizedGenericArgs::Err
1914 // A warning for now, for compatibility reasons
1915 _ => ParenthesizedGenericArgs::Warn,
1918 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1919 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1922 assert!(!def_id.is_local());
1924 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1925 let n = item_generics.own_counts().lifetimes;
1926 self.type_def_lifetime_params.insert(def_id, n);
1929 self.lower_path_segment(
1934 parenthesized_generic_args,
1943 // Simple case, either no projections, or only fully-qualified.
1944 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
1945 if partial_res.unresolved_segments() == 0 {
1946 return hir::QPath::Resolved(qself, path);
1949 // Create the innermost type that we're projecting from.
1950 let mut ty = if path.segments.is_empty() {
1951 // If the base path is empty that means there exists a
1952 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
1953 qself.expect("missing QSelf for <T>::...")
1955 // Otherwise, the base path is an implicit `Self` type path,
1956 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1957 // `<I as Iterator>::Item::default`.
1958 let new_id = self.next_id();
1959 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1962 // Anything after the base path are associated "extensions",
1963 // out of which all but the last one are associated types,
1964 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1965 // * base path is `std::vec::Vec<T>`
1966 // * "extensions" are `IntoIter`, `Item` and `clone`
1967 // * type nodes are:
1968 // 1. `std::vec::Vec<T>` (created above)
1969 // 2. `<std::vec::Vec<T>>::IntoIter`
1970 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1971 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1972 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1973 let segment = P(self.lower_path_segment(
1978 ParenthesizedGenericArgs::Warn,
1982 let qpath = hir::QPath::TypeRelative(ty, segment);
1984 // It's finished, return the extension of the right node type.
1985 if i == p.segments.len() - 1 {
1989 // Wrap the associated extension in another type node.
1990 let new_id = self.next_id();
1991 ty = P(self.ty_path(new_id, p.span, qpath));
1994 // We should've returned in the for loop above.
1997 "lower_qpath: no final extension segment in {}..{}",
2003 fn lower_path_extra(
2007 param_mode: ParamMode,
2008 explicit_owner: Option<NodeId>,
2012 segments: p.segments
2015 self.lower_path_segment(
2020 ParenthesizedGenericArgs::Err,
2021 ImplTraitContext::disallowed(),
2030 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
2031 let res = self.expect_full_res(id);
2032 let res = self.lower_res(res);
2033 self.lower_path_extra(res, p, param_mode, None)
2036 fn lower_path_segment(
2039 segment: &PathSegment,
2040 param_mode: ParamMode,
2041 expected_lifetimes: usize,
2042 parenthesized_generic_args: ParenthesizedGenericArgs,
2043 itctx: ImplTraitContext<'_>,
2044 explicit_owner: Option<NodeId>,
2045 ) -> hir::PathSegment {
2046 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
2047 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
2048 match **generic_args {
2049 GenericArgs::AngleBracketed(ref data) => {
2050 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
2052 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
2053 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
2054 ParenthesizedGenericArgs::Warn => {
2055 self.sess.buffer_lint(
2056 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
2061 (hir::GenericArgs::none(), true)
2063 ParenthesizedGenericArgs::Err => {
2064 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
2065 err.span_label(data.span, "only `Fn` traits may use parentheses");
2066 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
2067 // Do not suggest going from `Trait()` to `Trait<>`
2068 if data.inputs.len() > 0 {
2069 err.span_suggestion(
2071 "use angle brackets instead",
2072 format!("<{}>", &snippet[1..snippet.len() - 1]),
2073 Applicability::MaybeIncorrect,
2078 (self.lower_angle_bracketed_parameter_data(
2079 &data.as_angle_bracketed_args(),
2087 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
2090 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
2091 GenericArg::Lifetime(_) => true,
2094 let first_generic_span = generic_args.args.iter().map(|a| a.span())
2095 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
2096 if !generic_args.parenthesized && !has_lifetimes {
2098 self.elided_path_lifetimes(path_span, expected_lifetimes)
2100 .map(|lt| GenericArg::Lifetime(lt))
2101 .chain(generic_args.args.into_iter())
2103 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
2104 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
2105 let no_ty_args = generic_args.args.len() == expected_lifetimes;
2106 let no_bindings = generic_args.bindings.is_empty();
2107 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
2108 // If there are no (non-implicit) generic args or associated-type
2109 // bindings, our suggestion includes the angle brackets.
2110 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
2112 // Otherwise—sorry, this is kind of gross—we need to infer the
2113 // place to splice in the `'_, ` from the generics that do exist.
2114 let first_generic_span = first_generic_span
2115 .expect("already checked that type args or bindings exist");
2116 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
2118 match self.anonymous_lifetime_mode {
2119 // In create-parameter mode we error here because we don't want to support
2120 // deprecated impl elision in new features like impl elision and `async fn`,
2121 // both of which work using the `CreateParameter` mode:
2123 // impl Foo for std::cell::Ref<u32> // note lack of '_
2124 // async fn foo(_: std::cell::Ref<u32>) { ... }
2125 AnonymousLifetimeMode::CreateParameter => {
2126 let mut err = struct_span_err!(
2130 "implicit elided lifetime not allowed here"
2132 crate::lint::builtin::add_elided_lifetime_in_path_suggestion(
2143 AnonymousLifetimeMode::PassThrough |
2144 AnonymousLifetimeMode::ReportError |
2145 AnonymousLifetimeMode::Replace(_) => {
2146 self.sess.buffer_lint_with_diagnostic(
2147 ELIDED_LIFETIMES_IN_PATHS,
2150 "hidden lifetime parameters in types are deprecated",
2151 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
2164 let res = self.expect_full_res(segment.id);
2165 let id = if let Some(owner) = explicit_owner {
2166 self.lower_node_id_with_owner(segment.id, owner)
2168 self.lower_node_id(segment.id)
2171 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
2172 segment.ident, segment.id, id,
2175 hir::PathSegment::new(
2178 Some(self.lower_res(res)),
2184 fn lower_angle_bracketed_parameter_data(
2186 data: &AngleBracketedArgs,
2187 param_mode: ParamMode,
2188 mut itctx: ImplTraitContext<'_>,
2189 ) -> (hir::GenericArgs, bool) {
2190 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
2191 let has_types = args.iter().any(|arg| match arg {
2192 ast::GenericArg::Type(_) => true,
2196 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
2197 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
2198 parenthesized: false,
2200 !has_types && param_mode == ParamMode::Optional)
2203 fn lower_parenthesized_parameter_data(
2205 data: &ParenthesizedArgs,
2206 ) -> (hir::GenericArgs, bool) {
2207 // Switch to `PassThrough` mode for anonymous lifetimes: this
2208 // means that we permit things like `&Ref<T>`, where `Ref` has
2209 // a hidden lifetime parameter. This is needed for backwards
2210 // compatibility, even in contexts like an impl header where
2211 // we generally don't permit such things (see #51008).
2212 self.with_anonymous_lifetime_mode(
2213 AnonymousLifetimeMode::PassThrough,
2215 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2218 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
2220 let mk_tup = |this: &mut Self, tys, span| {
2221 hir::Ty { node: hir::TyKind::Tup(tys), hir_id: this.next_id(), span }
2225 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
2228 hir_id: this.next_id(),
2229 ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
2232 .map(|ty| this.lower_ty(&ty, ImplTraitContext::disallowed()))
2233 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
2234 span: output.as_ref().map_or(span, |ty| ty.span),
2237 parenthesized: true,
2245 fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) {
2246 let mut ids = SmallVec::<[NodeId; 1]>::new();
2247 if self.sess.features_untracked().impl_trait_in_bindings {
2248 if let Some(ref ty) = l.ty {
2249 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2250 visitor.visit_ty(ty);
2253 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2255 hir_id: self.lower_node_id(l.id),
2258 .map(|t| self.lower_ty(t,
2259 if self.sess.features_untracked().impl_trait_in_bindings {
2260 ImplTraitContext::Existential(Some(parent_def_id))
2262 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2265 pat: self.lower_pat(&l.pat),
2266 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2268 attrs: l.attrs.clone(),
2269 source: self.lower_local_source(l.source),
2273 fn lower_local_source(&mut self, ls: LocalSource) -> hir::LocalSource {
2275 LocalSource::Normal => hir::LocalSource::Normal,
2276 LocalSource::AsyncFn => hir::LocalSource::AsyncFn,
2280 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
2282 Mutability::Mutable => hir::MutMutable,
2283 Mutability::Immutable => hir::MutImmutable,
2287 fn lower_args(&mut self, decl: Option<&FnDecl>) -> HirVec<hir::Arg> {
2288 decl.map_or(hir_vec![], |decl| decl.inputs.iter().map(|x| self.lower_arg(x)).collect())
2291 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
2293 hir_id: self.lower_node_id(arg.id),
2294 pat: self.lower_pat(&arg.pat),
2295 source: self.lower_arg_source(&arg.source),
2299 fn lower_arg_source(&mut self, source: &ArgSource) -> hir::ArgSource {
2301 ArgSource::Normal => hir::ArgSource::Normal,
2302 ArgSource::AsyncFn(pat) => hir::ArgSource::AsyncFn(self.lower_pat(pat)),
2306 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2309 .map(|arg| match arg.pat.node {
2310 PatKind::Ident(_, ident, _) => ident,
2311 _ => Ident::new(kw::Invalid, arg.pat.span),
2316 // Lowers a function declaration.
2318 // decl: the unlowered (ast) function declaration.
2319 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
2320 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2321 // make_ret_async is also `Some`.
2322 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
2323 // This guards against trait declarations and implementations where impl Trait is
2325 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2326 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
2327 // return type impl Trait item.
2331 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2332 impl_trait_return_allow: bool,
2333 make_ret_async: Option<NodeId>,
2334 ) -> P<hir::FnDecl> {
2335 let lt_mode = if make_ret_async.is_some() {
2336 // In `async fn`, argument-position elided lifetimes
2337 // must be transformed into fresh generic parameters so that
2338 // they can be applied to the existential return type.
2339 AnonymousLifetimeMode::CreateParameter
2341 self.anonymous_lifetime_mode
2344 // Remember how many lifetimes were already around so that we can
2345 // only look at the lifetime parameters introduced by the arguments.
2346 let lifetime_count_before_args = self.lifetimes_to_define.len();
2347 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2351 if let Some((_, ibty)) = &mut in_band_ty_params {
2352 this.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2354 this.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2357 .collect::<HirVec<_>>()
2360 let output = if let Some(ret_id) = make_ret_async {
2361 // Calculate the `LtReplacement` to use for any return-position elided
2362 // lifetimes based on the elided lifetime parameters introduced in the args.
2363 let lt_replacement = get_elided_lt_replacement(
2364 &self.lifetimes_to_define[lifetime_count_before_args..]
2366 self.lower_async_fn_ret_ty(
2368 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
2374 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2375 Some((def_id, _)) if impl_trait_return_allow => {
2376 hir::Return(self.lower_ty(ty,
2377 ImplTraitContext::Existential(Some(def_id))))
2380 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2383 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2390 c_variadic: decl.c_variadic,
2391 implicit_self: decl.inputs.get(0).map_or(
2392 hir::ImplicitSelfKind::None,
2394 let is_mutable_pat = match arg.pat.node {
2395 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2396 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2397 mt == Mutability::Mutable,
2402 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2403 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2404 // Given we are only considering `ImplicitSelf` types, we needn't consider
2405 // the case where we have a mutable pattern to a reference as that would
2406 // no longer be an `ImplicitSelf`.
2407 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2408 mt.mutbl == ast::Mutability::Mutable =>
2409 hir::ImplicitSelfKind::MutRef,
2410 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2411 hir::ImplicitSelfKind::ImmRef,
2412 _ => hir::ImplicitSelfKind::None,
2419 // Transform `-> T` for `async fn` into -> ExistTy { .. }
2420 // combined with the following definition of `ExistTy`:
2422 // existential type ExistTy<generics_from_parent_fn>: Future<Output = T>;
2424 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
2425 // output: unlowered output type (`T` in `-> T`)
2426 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
2427 // exist_ty_node_id: NodeId of the existential type that should be created.
2428 // elided_lt_replacement: replacement for elided lifetimes in the return type
2429 fn lower_async_fn_ret_ty(
2431 output: &FunctionRetTy,
2433 exist_ty_node_id: NodeId,
2434 elided_lt_replacement: LtReplacement,
2435 ) -> hir::FunctionRetTy {
2436 let span = output.span();
2438 let exist_ty_span = self.sess.source_map().mark_span_with_reason(
2439 CompilerDesugaringKind::Async,
2444 let exist_ty_def_index = self
2447 .opt_def_index(exist_ty_node_id)
2450 self.allocate_hir_id_counter(exist_ty_node_id);
2452 let (exist_ty_id, lifetime_params) = self.with_hir_id_owner(exist_ty_node_id, |this| {
2453 let future_bound = this.with_anonymous_lifetime_mode(
2454 AnonymousLifetimeMode::Replace(elided_lt_replacement),
2455 |this| this.lower_async_fn_output_type_to_future_bound(
2462 // Calculate all the lifetimes that should be captured
2463 // by the existential type. This should include all in-scope
2464 // lifetime parameters, including those defined in-band.
2466 // Note: this must be done after lowering the output type,
2467 // as the output type may introduce new in-band lifetimes.
2468 let lifetime_params: Vec<(Span, ParamName)> =
2469 this.in_scope_lifetimes
2471 .map(|ident| (ident.span, ParamName::Plain(ident)))
2472 .chain(this.lifetimes_to_define.iter().cloned())
2475 let generic_params =
2478 .map(|(span, hir_name)| {
2479 this.lifetime_to_generic_param(span, hir_name, exist_ty_def_index)
2483 let exist_ty_item = hir::ExistTy {
2484 generics: hir::Generics {
2485 params: generic_params,
2486 where_clause: hir::WhereClause {
2487 hir_id: this.next_id(),
2488 predicates: hir_vec![],
2492 bounds: hir_vec![future_bound],
2493 impl_trait_fn: Some(fn_def_id),
2494 origin: hir::ExistTyOrigin::AsyncFn,
2497 trace!("exist ty from async fn def index: {:#?}", exist_ty_def_index);
2498 let exist_ty_id = this.generate_existential_type(
2505 (exist_ty_id, lifetime_params)
2511 .map(|(span, hir_name)| {
2512 GenericArg::Lifetime(hir::Lifetime {
2513 hir_id: self.next_id(),
2515 name: hir::LifetimeName::Param(hir_name),
2520 let exist_ty_ref = hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, generic_args);
2522 hir::FunctionRetTy::Return(P(hir::Ty {
2525 hir_id: self.next_id(),
2529 /// Turns `-> T` into `Future<Output = T>`
2530 fn lower_async_fn_output_type_to_future_bound(
2532 output: &FunctionRetTy,
2535 ) -> hir::GenericBound {
2536 // Compute the `T` in `Future<Output = T>` from the return type.
2537 let output_ty = match output {
2538 FunctionRetTy::Ty(ty) => {
2539 self.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2541 FunctionRetTy::Default(ret_ty_span) => {
2543 hir_id: self.next_id(),
2544 node: hir::TyKind::Tup(hir_vec![]),
2551 let future_params = P(hir::GenericArgs {
2553 bindings: hir_vec![hir::TypeBinding {
2554 ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
2556 hir_id: self.next_id(),
2559 parenthesized: false,
2562 // ::std::future::Future<future_params>
2564 self.std_path(span, &[sym::future, sym::Future], Some(future_params), false);
2566 hir::GenericBound::Trait(
2568 trait_ref: hir::TraitRef {
2570 hir_ref_id: self.next_id(),
2572 bound_generic_params: hir_vec![],
2575 hir::TraitBoundModifier::None,
2579 fn lower_param_bound(
2582 itctx: ImplTraitContext<'_>,
2583 ) -> hir::GenericBound {
2585 GenericBound::Trait(ref ty, modifier) => {
2586 hir::GenericBound::Trait(
2587 self.lower_poly_trait_ref(ty, itctx),
2588 self.lower_trait_bound_modifier(modifier),
2591 GenericBound::Outlives(ref lifetime) => {
2592 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2597 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2598 let span = l.ident.span;
2600 ident if ident.name == kw::StaticLifetime =>
2601 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2602 ident if ident.name == kw::UnderscoreLifetime =>
2603 match self.anonymous_lifetime_mode {
2604 AnonymousLifetimeMode::CreateParameter => {
2605 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2606 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2609 AnonymousLifetimeMode::PassThrough => {
2610 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2613 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2615 AnonymousLifetimeMode::Replace(replacement) => {
2616 let hir_id = self.lower_node_id(l.id);
2617 self.replace_elided_lifetime(hir_id, span, replacement)
2621 self.maybe_collect_in_band_lifetime(ident);
2622 let param_name = ParamName::Plain(ident);
2623 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2628 fn new_named_lifetime(
2632 name: hir::LifetimeName,
2633 ) -> hir::Lifetime {
2635 hir_id: self.lower_node_id(id),
2641 /// Replace a return-position elided lifetime with the elided lifetime
2642 /// from the arguments.
2643 fn replace_elided_lifetime(
2647 replacement: LtReplacement,
2648 ) -> hir::Lifetime {
2649 let multiple_or_none = match replacement {
2650 LtReplacement::Some(name) => {
2651 return hir::Lifetime {
2654 name: hir::LifetimeName::Param(name),
2657 LtReplacement::MultipleLifetimes => "multiple",
2658 LtReplacement::NoLifetimes => "none",
2661 let mut err = crate::middle::resolve_lifetime::report_missing_lifetime_specifiers(
2667 "return-position elided lifetimes require exactly one \
2668 input-position elided lifetime, found {}.", multiple_or_none));
2671 hir::Lifetime { hir_id, span, name: hir::LifetimeName::Error }
2674 fn lower_generic_params(
2676 params: &[GenericParam],
2677 add_bounds: &NodeMap<Vec<GenericBound>>,
2678 mut itctx: ImplTraitContext<'_>,
2679 ) -> hir::HirVec<hir::GenericParam> {
2680 params.iter().map(|param| {
2681 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2685 fn lower_generic_param(&mut self,
2686 param: &GenericParam,
2687 add_bounds: &NodeMap<Vec<GenericBound>>,
2688 mut itctx: ImplTraitContext<'_>)
2689 -> hir::GenericParam {
2690 let mut bounds = self.with_anonymous_lifetime_mode(
2691 AnonymousLifetimeMode::ReportError,
2692 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2695 let (name, kind) = match param.kind {
2696 GenericParamKind::Lifetime => {
2697 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2698 self.is_collecting_in_band_lifetimes = false;
2700 let lt = self.with_anonymous_lifetime_mode(
2701 AnonymousLifetimeMode::ReportError,
2702 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2704 let param_name = match lt.name {
2705 hir::LifetimeName::Param(param_name) => param_name,
2706 hir::LifetimeName::Implicit
2707 | hir::LifetimeName::Underscore
2708 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2709 hir::LifetimeName::Error => ParamName::Error,
2712 let kind = hir::GenericParamKind::Lifetime {
2713 kind: hir::LifetimeParamKind::Explicit
2716 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2720 GenericParamKind::Type { ref default, .. } => {
2721 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2722 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2723 // Instead, use `gensym("Self")` to create a distinct name that looks the same.
2724 let ident = if param.ident.name == kw::SelfUpper {
2725 param.ident.gensym()
2730 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2731 if !add_bounds.is_empty() {
2732 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2733 bounds = bounds.into_iter()
2738 let kind = hir::GenericParamKind::Type {
2739 default: default.as_ref().map(|x| {
2740 self.lower_ty(x, ImplTraitContext::disallowed())
2742 synthetic: param.attrs.iter()
2743 .filter(|attr| attr.check_name(sym::rustc_synthetic))
2744 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2748 (hir::ParamName::Plain(ident), kind)
2750 GenericParamKind::Const { ref ty } => {
2751 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const {
2752 ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2758 hir_id: self.lower_node_id(param.id),
2760 span: param.ident.span,
2761 pure_wrt_drop: attr::contains_name(¶m.attrs, sym::may_dangle),
2762 attrs: self.lower_attrs(¶m.attrs),
2770 generics: &Generics,
2771 itctx: ImplTraitContext<'_>)
2774 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2775 // FIXME: this could probably be done with less rightward drift. Also looks like two control
2776 // paths where report_error is called are also the only paths that advance to after
2777 // the match statement, so the error reporting could probably just be moved there.
2778 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
2779 for pred in &generics.where_clause.predicates {
2780 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2781 'next_bound: for bound in &bound_pred.bounds {
2782 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2783 let report_error = |this: &mut Self| {
2784 this.diagnostic().span_err(
2785 bound_pred.bounded_ty.span,
2786 "`?Trait` bounds are only permitted at the \
2787 point where a type parameter is declared",
2790 // Check if the where clause type is a plain type parameter.
2791 match bound_pred.bounded_ty.node {
2792 TyKind::Path(None, ref path)
2793 if path.segments.len() == 1
2794 && bound_pred.bound_generic_params.is_empty() =>
2796 if let Some(Res::Def(DefKind::TyParam, def_id)) = self.resolver
2797 .get_partial_res(bound_pred.bounded_ty.id)
2798 .map(|d| d.base_res())
2800 if let Some(node_id) =
2801 self.resolver.definitions().as_local_node_id(def_id)
2803 for param in &generics.params {
2805 GenericParamKind::Type { .. } => {
2806 if node_id == param.id {
2807 add_bounds.entry(param.id)
2809 .push(bound.clone());
2810 continue 'next_bound;
2820 _ => report_error(self),
2828 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2829 where_clause: self.lower_where_clause(&generics.where_clause),
2830 span: generics.span,
2834 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2835 self.with_anonymous_lifetime_mode(
2836 AnonymousLifetimeMode::ReportError,
2839 hir_id: this.lower_node_id(wc.id),
2840 predicates: wc.predicates
2842 .map(|predicate| this.lower_where_predicate(predicate))
2849 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2851 WherePredicate::BoundPredicate(WhereBoundPredicate {
2852 ref bound_generic_params,
2857 self.with_in_scope_lifetime_defs(
2858 &bound_generic_params,
2860 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2861 bound_generic_params: this.lower_generic_params(
2862 bound_generic_params,
2863 &NodeMap::default(),
2864 ImplTraitContext::disallowed(),
2866 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
2869 .filter_map(|bound| match *bound {
2870 // Ignore `?Trait` bounds.
2871 // They were copied into type parameters already.
2872 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2873 _ => Some(this.lower_param_bound(
2875 ImplTraitContext::disallowed(),
2884 WherePredicate::RegionPredicate(WhereRegionPredicate {
2888 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2890 lifetime: self.lower_lifetime(lifetime),
2891 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2893 WherePredicate::EqPredicate(WhereEqPredicate {
2899 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2900 hir_id: self.lower_node_id(id),
2901 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
2902 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
2909 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2911 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
2912 fields.iter().enumerate().map(|f| self.lower_struct_field(f)).collect(),
2915 VariantData::Tuple(ref fields, id) => {
2916 hir::VariantData::Tuple(
2920 .map(|f| self.lower_struct_field(f))
2922 self.lower_node_id(id),
2925 VariantData::Unit(id) => {
2926 hir::VariantData::Unit(self.lower_node_id(id))
2931 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2932 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2933 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2934 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2938 hir_ref_id: self.lower_node_id(p.ref_id),
2942 fn lower_poly_trait_ref(
2945 mut itctx: ImplTraitContext<'_>,
2946 ) -> hir::PolyTraitRef {
2947 let bound_generic_params = self.lower_generic_params(
2948 &p.bound_generic_params,
2949 &NodeMap::default(),
2952 let trait_ref = self.with_parent_impl_lifetime_defs(
2953 &bound_generic_params,
2954 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2958 bound_generic_params,
2964 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2967 hir_id: self.lower_node_id(f.id),
2968 ident: match f.ident {
2969 Some(ident) => ident,
2970 // FIXME(jseyfried): positional field hygiene
2971 None => Ident::new(sym::integer(index), f.span),
2973 vis: self.lower_visibility(&f.vis, None),
2974 ty: self.lower_ty(&f.ty, ImplTraitContext::disallowed()),
2975 attrs: self.lower_attrs(&f.attrs),
2979 fn lower_field(&mut self, f: &Field) -> hir::Field {
2981 hir_id: self.next_id(),
2983 expr: P(self.lower_expr(&f.expr)),
2985 is_shorthand: f.is_shorthand,
2989 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2991 ty: self.lower_ty(&mt.ty, itctx),
2992 mutbl: self.lower_mutability(mt.mutbl),
2996 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2997 -> hir::GenericBounds {
2998 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
3001 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
3002 let mut expr = None;
3004 let mut stmts = vec![];
3006 for (index, stmt) in b.stmts.iter().enumerate() {
3007 if index == b.stmts.len() - 1 {
3008 if let StmtKind::Expr(ref e) = stmt.node {
3009 expr = Some(P(self.lower_expr(e)));
3011 stmts.extend(self.lower_stmt(stmt));
3014 stmts.extend(self.lower_stmt(stmt));
3019 hir_id: self.lower_node_id(b.id),
3020 stmts: stmts.into(),
3022 rules: self.lower_block_check_mode(&b.rules),
3028 fn lower_async_body(
3031 asyncness: &IsAsync,
3034 self.lower_body(Some(&decl), |this| {
3035 if let IsAsync::Async { closure_id, ref arguments, .. } = asyncness {
3036 let mut body = body.clone();
3038 // Async function arguments are lowered into the closure body so that they are
3039 // captured and so that the drop order matches the equivalent non-async functions.
3041 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
3047 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
3049 // let __arg2 = __arg2;
3050 // let <pattern> = __arg2;
3051 // let __arg1 = __arg1;
3052 // let <pattern> = __arg1;
3053 // let __arg0 = __arg0;
3054 // let <pattern> = __arg0;
3058 // If `<pattern>` is a simple ident, then it is lowered to a single
3059 // `let <pattern> = <pattern>;` statement as an optimization.
3060 for a in arguments.iter().rev() {
3061 if let Some(pat_stmt) = a.pat_stmt.clone() {
3062 body.stmts.insert(0, pat_stmt);
3064 body.stmts.insert(0, a.move_stmt.clone());
3067 let async_expr = this.make_async_expr(
3068 CaptureBy::Value, *closure_id, None, body.span,
3070 let body = this.lower_block(&body, false);
3071 this.expr_block(body, ThinVec::new())
3073 this.expr(body.span, async_expr, ThinVec::new())
3075 let body = this.lower_block(body, false);
3076 this.expr_block(body, ThinVec::new())
3085 attrs: &hir::HirVec<Attribute>,
3086 vis: &mut hir::Visibility,
3088 ) -> hir::ItemKind {
3090 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
3091 ItemKind::Use(ref use_tree) => {
3092 // Start with an empty prefix
3095 span: use_tree.span,
3098 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
3100 ItemKind::Static(ref t, m, ref e) => {
3101 let value = self.lower_body(None, |this| this.lower_expr(e));
3102 hir::ItemKind::Static(
3105 if self.sess.features_untracked().impl_trait_in_bindings {
3106 ImplTraitContext::Existential(None)
3108 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3111 self.lower_mutability(m),
3115 ItemKind::Const(ref t, ref e) => {
3116 let value = self.lower_body(None, |this| this.lower_expr(e));
3117 hir::ItemKind::Const(
3120 if self.sess.features_untracked().impl_trait_in_bindings {
3121 ImplTraitContext::Existential(None)
3123 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3129 ItemKind::Fn(ref decl, ref header, ref generics, ref body) => {
3130 let fn_def_id = self.resolver.definitions().local_def_id(id);
3131 self.with_new_scopes(|this| {
3132 this.current_item = Some(ident.span);
3133 let mut lower_fn = |decl: &FnDecl| {
3134 // Note: we don't need to change the return type from `T` to
3135 // `impl Future<Output = T>` here because lower_body
3136 // only cares about the input argument patterns in the function
3137 // declaration (decl), not the return types.
3138 let body_id = this.lower_async_body(&decl, &header.asyncness.node, body);
3140 let (generics, fn_decl) = this.add_in_band_defs(
3143 AnonymousLifetimeMode::PassThrough,
3144 |this, idty| this.lower_fn_decl(
3146 Some((fn_def_id, idty)),
3148 header.asyncness.node.opt_return_id()
3152 (body_id, generics, fn_decl)
3155 let (body_id, generics, fn_decl) = if let IsAsync::Async {
3157 } = &header.asyncness.node {
3158 let mut decl = decl.clone();
3159 // Replace the arguments of this async function with the generated
3160 // arguments that will be moved into the closure.
3161 for (i, a) in arguments.clone().drain(..).enumerate() {
3162 if let Some(arg) = a.arg {
3163 decl.inputs[i] = arg;
3173 this.lower_fn_header(header),
3179 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
3180 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
3181 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
3182 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
3183 self.lower_ty(t, ImplTraitContext::disallowed()),
3184 self.lower_generics(generics, ImplTraitContext::disallowed()),
3186 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
3187 generics: self.lower_generics(generics, ImplTraitContext::disallowed()),
3188 bounds: self.lower_param_bounds(b, ImplTraitContext::disallowed()),
3189 impl_trait_fn: None,
3190 origin: hir::ExistTyOrigin::ExistentialType,
3192 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
3194 variants: enum_definition
3197 .map(|x| self.lower_variant(x))
3200 self.lower_generics(generics, ImplTraitContext::disallowed()),
3202 ItemKind::Struct(ref struct_def, ref generics) => {
3203 let struct_def = self.lower_variant_data(struct_def);
3204 hir::ItemKind::Struct(
3206 self.lower_generics(generics, ImplTraitContext::disallowed()),
3209 ItemKind::Union(ref vdata, ref generics) => {
3210 let vdata = self.lower_variant_data(vdata);
3211 hir::ItemKind::Union(
3213 self.lower_generics(generics, ImplTraitContext::disallowed()),
3225 let def_id = self.resolver.definitions().local_def_id(id);
3227 // Lower the "impl header" first. This ordering is important
3228 // for in-band lifetimes! Consider `'a` here:
3230 // impl Foo<'a> for u32 {
3231 // fn method(&'a self) { .. }
3234 // Because we start by lowering the `Foo<'a> for u32`
3235 // part, we will add `'a` to the list of generics on
3236 // the impl. When we then encounter it later in the
3237 // method, it will not be considered an in-band
3238 // lifetime to be added, but rather a reference to a
3240 let lowered_trait_impl_id = self.lower_node_id(id);
3241 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
3244 AnonymousLifetimeMode::CreateParameter,
3246 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
3247 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
3250 if let Some(ref trait_ref) = trait_ref {
3251 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
3252 this.trait_impls.entry(def_id).or_default().push(
3253 lowered_trait_impl_id);
3257 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
3259 (trait_ref, lowered_ty)
3263 let new_impl_items = self.with_in_scope_lifetime_defs(
3264 &ast_generics.params,
3268 .map(|item| this.lower_impl_item_ref(item))
3273 hir::ItemKind::Impl(
3274 self.lower_unsafety(unsafety),
3275 self.lower_impl_polarity(polarity),
3276 self.lower_defaultness(defaultness, true /* [1] */),
3283 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
3284 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
3287 .map(|item| self.lower_trait_item_ref(item))
3289 hir::ItemKind::Trait(
3290 self.lower_is_auto(is_auto),
3291 self.lower_unsafety(unsafety),
3292 self.lower_generics(generics, ImplTraitContext::disallowed()),
3297 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
3298 self.lower_generics(generics, ImplTraitContext::disallowed()),
3299 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3301 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
3304 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
3305 // not cause an assertion failure inside the `lower_defaultness` function.
3313 vis: &mut hir::Visibility,
3315 attrs: &hir::HirVec<Attribute>,
3316 ) -> hir::ItemKind {
3317 debug!("lower_use_tree(tree={:?})", tree);
3318 debug!("lower_use_tree: vis = {:?}", vis);
3320 let path = &tree.prefix;
3321 let segments = prefix
3324 .chain(path.segments.iter())
3329 UseTreeKind::Simple(rename, id1, id2) => {
3330 *ident = tree.ident();
3332 // First, apply the prefix to the path.
3333 let mut path = Path {
3338 // Correctly resolve `self` imports.
3339 if path.segments.len() > 1
3340 && path.segments.last().unwrap().ident.name == kw::SelfLower
3342 let _ = path.segments.pop();
3343 if rename.is_none() {
3344 *ident = path.segments.last().unwrap().ident;
3348 let mut resolutions = self.expect_full_res_from_use(id);
3349 // We want to return *something* from this function, so hold onto the first item
3351 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
3353 // Here, we are looping over namespaces, if they exist for the definition
3354 // being imported. We only handle type and value namespaces because we
3355 // won't be dealing with macros in the rest of the compiler.
3356 // Essentially a single `use` which imports two names is desugared into
3358 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
3359 let vis = vis.clone();
3360 let ident = ident.clone();
3361 let mut path = path.clone();
3362 for seg in &mut path.segments {
3363 seg.id = self.sess.next_node_id();
3365 let span = path.span;
3367 self.with_hir_id_owner(new_node_id, |this| {
3368 let new_id = this.lower_node_id(new_node_id);
3369 let res = this.lower_res(res);
3371 this.lower_path_extra(res, &path, ParamMode::Explicit, None);
3372 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
3373 let vis_kind = match vis.node {
3374 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3375 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3376 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3377 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
3378 let path = this.renumber_segment_ids(path);
3379 hir::VisibilityKind::Restricted {
3381 hir_id: this.next_id(),
3385 let vis = respan(vis.span, vis_kind);
3391 attrs: attrs.clone(),
3401 P(self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None));
3402 hir::ItemKind::Use(path, hir::UseKind::Single)
3404 UseTreeKind::Glob => {
3405 let path = P(self.lower_path(
3411 ParamMode::Explicit,
3413 hir::ItemKind::Use(path, hir::UseKind::Glob)
3415 UseTreeKind::Nested(ref trees) => {
3416 // Nested imports are desugared into simple imports.
3417 // So, if we start with
3420 // pub(x) use foo::{a, b};
3423 // we will create three items:
3426 // pub(x) use foo::a;
3427 // pub(x) use foo::b;
3428 // pub(x) use foo::{}; // <-- this is called the `ListStem`
3431 // The first two are produced by recursively invoking
3432 // `lower_use_tree` (and indeed there may be things
3433 // like `use foo::{a::{b, c}}` and so forth). They
3434 // wind up being directly added to
3435 // `self.items`. However, the structure of this
3436 // function also requires us to return one item, and
3437 // for that we return the `{}` import (called the
3442 span: prefix.span.to(path.span),
3445 // Add all the nested `PathListItem`s to the HIR.
3446 for &(ref use_tree, id) in trees {
3447 let new_hir_id = self.lower_node_id(id);
3449 let mut vis = vis.clone();
3450 let mut ident = ident.clone();
3451 let mut prefix = prefix.clone();
3453 // Give the segments new node-ids since they are being cloned.
3454 for seg in &mut prefix.segments {
3455 seg.id = self.sess.next_node_id();
3458 // Each `use` import is an item and thus are owners of the
3459 // names in the path. Up to this point the nested import is
3460 // the current owner, since we want each desugared import to
3461 // own its own names, we have to adjust the owner before
3462 // lowering the rest of the import.
3463 self.with_hir_id_owner(id, |this| {
3464 let item = this.lower_use_tree(use_tree,
3471 let vis_kind = match vis.node {
3472 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3473 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3474 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3475 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
3476 let path = this.renumber_segment_ids(path);
3477 hir::VisibilityKind::Restricted {
3479 hir_id: this.next_id(),
3483 let vis = respan(vis.span, vis_kind);
3489 attrs: attrs.clone(),
3492 span: use_tree.span,
3498 // Subtle and a bit hacky: we lower the privacy level
3499 // of the list stem to "private" most of the time, but
3500 // not for "restricted" paths. The key thing is that
3501 // we don't want it to stay as `pub` (with no caveats)
3502 // because that affects rustdoc and also the lints
3503 // about `pub` items. But we can't *always* make it
3504 // private -- particularly not for restricted paths --
3505 // because it contains node-ids that would then be
3506 // unused, failing the check that HirIds are "densely
3509 hir::VisibilityKind::Public |
3510 hir::VisibilityKind::Crate(_) |
3511 hir::VisibilityKind::Inherited => {
3512 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3514 hir::VisibilityKind::Restricted { .. } => {
3515 // Do nothing here, as described in the comment on the match.
3519 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
3520 let res = self.lower_res(res);
3521 let path = P(self.lower_path_extra(res, &prefix, ParamMode::Explicit, None));
3522 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3527 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
3528 /// many times in the HIR tree; for each occurrence, we need to assign distinct
3529 /// `NodeId`s. (See, e.g., #56128.)
3530 fn renumber_segment_ids(&mut self, path: &P<hir::Path>) -> P<hir::Path> {
3531 debug!("renumber_segment_ids(path = {:?})", path);
3532 let mut path = path.clone();
3533 for seg in path.segments.iter_mut() {
3534 if seg.hir_id.is_some() {
3535 seg.hir_id = Some(self.next_id());
3541 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3542 let trait_item_def_id = self.resolver.definitions().local_def_id(i.id);
3544 let (generics, node) = match i.node {
3545 TraitItemKind::Const(ref ty, ref default) => (
3546 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3547 hir::TraitItemKind::Const(
3548 self.lower_ty(ty, ImplTraitContext::disallowed()),
3551 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
3554 TraitItemKind::Method(ref sig, None) => {
3555 let names = self.lower_fn_args_to_names(&sig.decl);
3556 let (generics, sig) = self.lower_method_sig(
3563 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3565 TraitItemKind::Method(ref sig, Some(ref body)) => {
3566 let body_id = self.lower_body(Some(&sig.decl), |this| {
3567 let body = this.lower_block(body, false);
3568 this.expr_block(body, ThinVec::new())
3570 let (generics, sig) = self.lower_method_sig(
3577 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3579 TraitItemKind::Type(ref bounds, ref default) => (
3580 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3581 hir::TraitItemKind::Type(
3582 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3585 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3588 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3592 hir_id: self.lower_node_id(i.id),
3594 attrs: self.lower_attrs(&i.attrs),
3601 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3602 let (kind, has_default) = match i.node {
3603 TraitItemKind::Const(_, ref default) => {
3604 (hir::AssocItemKind::Const, default.is_some())
3606 TraitItemKind::Type(_, ref default) => {
3607 (hir::AssocItemKind::Type, default.is_some())
3609 TraitItemKind::Method(ref sig, ref default) => (
3610 hir::AssocItemKind::Method {
3611 has_self: sig.decl.has_self(),
3615 TraitItemKind::Macro(..) => unimplemented!(),
3618 id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) },
3621 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3626 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3627 let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
3629 let (generics, node) = match i.node {
3630 ImplItemKind::Const(ref ty, ref expr) => {
3631 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3633 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3634 hir::ImplItemKind::Const(
3635 self.lower_ty(ty, ImplTraitContext::disallowed()),
3640 ImplItemKind::Method(ref sig, ref body) => {
3641 let mut lower_method = |sig: &MethodSig| {
3642 let body_id = self.lower_async_body(
3643 &sig.decl, &sig.header.asyncness.node, body
3645 let impl_trait_return_allow = !self.is_in_trait_impl;
3646 let (generics, sig) = self.lower_method_sig(
3650 impl_trait_return_allow,
3651 sig.header.asyncness.node.opt_return_id(),
3653 (body_id, generics, sig)
3656 let (body_id, generics, sig) = if let IsAsync::Async {
3658 } = sig.header.asyncness.node {
3659 let mut sig = sig.clone();
3660 // Replace the arguments of this async function with the generated
3661 // arguments that will be moved into the closure.
3662 for (i, a) in arguments.clone().drain(..).enumerate() {
3663 if let Some(arg) = a.arg {
3664 sig.decl.inputs[i] = arg;
3671 self.current_item = Some(i.span);
3673 (generics, hir::ImplItemKind::Method(sig, body_id))
3675 ImplItemKind::Type(ref ty) => (
3676 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3677 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3679 ImplItemKind::Existential(ref bounds) => (
3680 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3681 hir::ImplItemKind::Existential(
3682 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3685 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3689 hir_id: self.lower_node_id(i.id),
3691 attrs: self.lower_attrs(&i.attrs),
3693 vis: self.lower_visibility(&i.vis, None),
3694 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3699 // [1] since `default impl` is not yet implemented, this is always true in impls
3702 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3704 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
3707 vis: self.lower_visibility(&i.vis, Some(i.id)),
3708 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3709 kind: match i.node {
3710 ImplItemKind::Const(..) => hir::AssocItemKind::Const,
3711 ImplItemKind::Type(..) => hir::AssocItemKind::Type,
3712 ImplItemKind::Existential(..) => hir::AssocItemKind::Existential,
3713 ImplItemKind::Method(ref sig, _) => hir::AssocItemKind::Method {
3714 has_self: sig.decl.has_self(),
3716 ImplItemKind::Macro(..) => unimplemented!(),
3720 // [1] since `default impl` is not yet implemented, this is always true in impls
3723 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3726 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3730 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3731 let node_ids = match i.node {
3732 ItemKind::Use(ref use_tree) => {
3733 let mut vec = smallvec![i.id];
3734 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3737 ItemKind::MacroDef(..) => SmallVec::new(),
3739 ItemKind::Impl(.., None, _, _) => smallvec![i.id],
3740 ItemKind::Static(ref ty, ..) => {
3741 let mut ids = smallvec![i.id];
3742 if self.sess.features_untracked().impl_trait_in_bindings {
3743 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3744 visitor.visit_ty(ty);
3748 ItemKind::Const(ref ty, ..) => {
3749 let mut ids = smallvec![i.id];
3750 if self.sess.features_untracked().impl_trait_in_bindings {
3751 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3752 visitor.visit_ty(ty);
3756 _ => smallvec![i.id],
3759 node_ids.into_iter().map(|node_id| hir::ItemId {
3760 id: self.allocate_hir_id_counter(node_id)
3764 fn lower_item_id_use_tree(&mut self,
3767 vec: &mut SmallVec<[NodeId; 1]>)
3770 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3772 self.lower_item_id_use_tree(nested, id, vec);
3774 UseTreeKind::Glob => {}
3775 UseTreeKind::Simple(_, id1, id2) => {
3776 for (_, &id) in self.expect_full_res_from_use(base_id)
3778 .zip([id1, id2].iter())
3786 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3787 let mut ident = i.ident;
3788 let mut vis = self.lower_visibility(&i.vis, None);
3789 let attrs = self.lower_attrs(&i.attrs);
3790 if let ItemKind::MacroDef(ref def) = i.node {
3791 if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) ||
3792 attr::contains_name(&i.attrs, sym::rustc_doc_only_macro) {
3793 let body = self.lower_token_stream(def.stream());
3794 let hir_id = self.lower_node_id(i.id);
3795 self.exported_macros.push(hir::MacroDef {
3808 let node = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.node);
3811 hir_id: self.lower_node_id(i.id),
3820 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3821 let def_id = self.resolver.definitions().local_def_id(i.id);
3823 hir_id: self.lower_node_id(i.id),
3825 attrs: self.lower_attrs(&i.attrs),
3826 node: match i.node {
3827 ForeignItemKind::Fn(ref fdec, ref generics) => {
3828 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3831 AnonymousLifetimeMode::PassThrough,
3834 // Disallow impl Trait in foreign items
3835 this.lower_fn_decl(fdec, None, false, None),
3836 this.lower_fn_args_to_names(fdec),
3841 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3843 ForeignItemKind::Static(ref t, m) => {
3844 hir::ForeignItemKind::Static(
3845 self.lower_ty(t, ImplTraitContext::disallowed()), self.lower_mutability(m))
3847 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3848 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3850 vis: self.lower_visibility(&i.vis, None),
3855 fn lower_method_sig(
3857 generics: &Generics,
3860 impl_trait_return_allow: bool,
3861 is_async: Option<NodeId>,
3862 ) -> (hir::Generics, hir::MethodSig) {
3863 let header = self.lower_fn_header(&sig.header);
3864 let (generics, decl) = self.add_in_band_defs(
3867 AnonymousLifetimeMode::PassThrough,
3868 |this, idty| this.lower_fn_decl(
3870 Some((fn_def_id, idty)),
3871 impl_trait_return_allow,
3875 (generics, hir::MethodSig { header, decl })
3878 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3880 IsAuto::Yes => hir::IsAuto::Yes,
3881 IsAuto::No => hir::IsAuto::No,
3885 fn lower_fn_header(&mut self, h: &FnHeader) -> hir::FnHeader {
3887 unsafety: self.lower_unsafety(h.unsafety),
3888 asyncness: self.lower_asyncness(&h.asyncness.node),
3889 constness: self.lower_constness(h.constness),
3894 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3896 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3897 Unsafety::Normal => hir::Unsafety::Normal,
3901 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3903 Constness::Const => hir::Constness::Const,
3904 Constness::NotConst => hir::Constness::NotConst,
3908 fn lower_asyncness(&mut self, a: &IsAsync) -> hir::IsAsync {
3910 IsAsync::Async { .. } => hir::IsAsync::Async,
3911 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3915 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3917 UnOp::Deref => hir::UnDeref,
3918 UnOp::Not => hir::UnNot,
3919 UnOp::Neg => hir::UnNeg,
3923 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3925 node: match b.node {
3926 BinOpKind::Add => hir::BinOpKind::Add,
3927 BinOpKind::Sub => hir::BinOpKind::Sub,
3928 BinOpKind::Mul => hir::BinOpKind::Mul,
3929 BinOpKind::Div => hir::BinOpKind::Div,
3930 BinOpKind::Rem => hir::BinOpKind::Rem,
3931 BinOpKind::And => hir::BinOpKind::And,
3932 BinOpKind::Or => hir::BinOpKind::Or,
3933 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3934 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3935 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3936 BinOpKind::Shl => hir::BinOpKind::Shl,
3937 BinOpKind::Shr => hir::BinOpKind::Shr,
3938 BinOpKind::Eq => hir::BinOpKind::Eq,
3939 BinOpKind::Lt => hir::BinOpKind::Lt,
3940 BinOpKind::Le => hir::BinOpKind::Le,
3941 BinOpKind::Ne => hir::BinOpKind::Ne,
3942 BinOpKind::Ge => hir::BinOpKind::Ge,
3943 BinOpKind::Gt => hir::BinOpKind::Gt,
3949 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3950 let node = match p.node {
3951 PatKind::Wild => hir::PatKind::Wild,
3952 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3953 match self.resolver.get_partial_res(p.id).map(|d| d.base_res()) {
3954 // `None` can occur in body-less function signatures
3955 res @ None | res @ Some(Res::Local(_)) => {
3956 let canonical_id = match res {
3957 Some(Res::Local(id)) => id,
3961 hir::PatKind::Binding(
3962 self.lower_binding_mode(binding_mode),
3963 self.lower_node_id(canonical_id),
3965 sub.as_ref().map(|x| self.lower_pat(x)),
3968 Some(res) => hir::PatKind::Path(hir::QPath::Resolved(
3972 res: self.lower_res(res),
3973 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3978 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3979 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3980 let qpath = self.lower_qpath(
3984 ParamMode::Optional,
3985 ImplTraitContext::disallowed(),
3987 hir::PatKind::TupleStruct(
3989 pats.iter().map(|x| self.lower_pat(x)).collect(),
3993 PatKind::Path(ref qself, ref path) => {
3994 let qpath = self.lower_qpath(
3998 ParamMode::Optional,
3999 ImplTraitContext::disallowed(),
4001 hir::PatKind::Path(qpath)
4003 PatKind::Struct(ref path, ref fields, etc) => {
4004 let qpath = self.lower_qpath(
4008 ParamMode::Optional,
4009 ImplTraitContext::disallowed(),
4017 node: hir::FieldPat {
4018 hir_id: self.next_id(),
4019 ident: f.node.ident,
4020 pat: self.lower_pat(&f.node.pat),
4021 is_shorthand: f.node.is_shorthand,
4026 hir::PatKind::Struct(qpath, fs, etc)
4028 PatKind::Tuple(ref elts, ddpos) => {
4029 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
4031 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
4032 PatKind::Ref(ref inner, mutbl) => {
4033 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
4035 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
4036 P(self.lower_expr(e1)),
4037 P(self.lower_expr(e2)),
4038 self.lower_range_end(end),
4040 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
4041 before.iter().map(|x| self.lower_pat(x)).collect(),
4042 slice.as_ref().map(|x| self.lower_pat(x)),
4043 after.iter().map(|x| self.lower_pat(x)).collect(),
4045 PatKind::Paren(ref inner) => return self.lower_pat(inner),
4046 PatKind::Mac(_) => panic!("Shouldn't exist here"),
4050 hir_id: self.lower_node_id(p.id),
4056 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
4058 RangeEnd::Included(_) => hir::RangeEnd::Included,
4059 RangeEnd::Excluded => hir::RangeEnd::Excluded,
4063 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
4064 self.with_new_scopes(|this| {
4066 hir_id: this.lower_node_id(c.id),
4067 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
4072 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
4073 let kind = match e.node {
4074 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
4075 ExprKind::Array(ref exprs) => {
4076 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
4078 ExprKind::Repeat(ref expr, ref count) => {
4079 let expr = P(self.lower_expr(expr));
4080 let count = self.lower_anon_const(count);
4081 hir::ExprKind::Repeat(expr, count)
4083 ExprKind::Tup(ref elts) => {
4084 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
4086 ExprKind::Call(ref f, ref args) => {
4087 let f = P(self.lower_expr(f));
4088 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
4090 ExprKind::MethodCall(ref seg, ref args) => {
4091 let hir_seg = P(self.lower_path_segment(
4094 ParamMode::Optional,
4096 ParenthesizedGenericArgs::Err,
4097 ImplTraitContext::disallowed(),
4100 let args = args.iter().map(|x| self.lower_expr(x)).collect();
4101 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
4103 ExprKind::Binary(binop, ref lhs, ref rhs) => {
4104 let binop = self.lower_binop(binop);
4105 let lhs = P(self.lower_expr(lhs));
4106 let rhs = P(self.lower_expr(rhs));
4107 hir::ExprKind::Binary(binop, lhs, rhs)
4109 ExprKind::Unary(op, ref ohs) => {
4110 let op = self.lower_unop(op);
4111 let ohs = P(self.lower_expr(ohs));
4112 hir::ExprKind::Unary(op, ohs)
4114 ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.node.clone())),
4115 ExprKind::Cast(ref expr, ref ty) => {
4116 let expr = P(self.lower_expr(expr));
4117 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4119 ExprKind::Type(ref expr, ref ty) => {
4120 let expr = P(self.lower_expr(expr));
4121 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4123 ExprKind::AddrOf(m, ref ohs) => {
4124 let m = self.lower_mutability(m);
4125 let ohs = P(self.lower_expr(ohs));
4126 hir::ExprKind::AddrOf(m, ohs)
4128 // More complicated than you might expect because the else branch
4129 // might be `if let`.
4130 ExprKind::If(ref cond, ref then, ref else_opt) => {
4132 let then_pat = self.pat_bool(e.span, true);
4133 let then_blk = self.lower_block(then, false);
4134 let then_expr = self.expr_block(then_blk, ThinVec::new());
4135 let then_arm = self.arm(hir_vec![then_pat], P(then_expr));
4137 // `_ => else_block` where `else_block` is `{}` if there's `None`:
4138 let else_pat = self.pat_wild(e.span);
4139 let else_expr = match else_opt {
4140 None => self.expr_block_empty(e.span),
4141 Some(els) => match els.node {
4142 ExprKind::IfLet(..) => {
4143 // Wrap the `if let` expr in a block.
4144 let els = self.lower_expr(els);
4145 let blk = self.block_all(els.span, hir_vec![], Some(P(els)));
4146 self.expr_block(P(blk), ThinVec::new())
4148 _ => self.lower_expr(els),
4151 let else_arm = self.arm(hir_vec![else_pat], P(else_expr));
4154 let span_block = self
4157 .mark_span_with_reason(IfTemporary, cond.span, None);
4158 let cond = self.lower_expr(cond);
4159 // Wrap in a construct equivalent to `{ let _t = $cond; _t }` to preserve drop
4160 // semantics since `if cond { ... }` don't let temporaries live outside of `cond`.
4161 let cond = self.expr_drop_temps(span_block, P(cond), ThinVec::new());
4163 hir::ExprKind::Match(
4165 vec![then_arm, else_arm].into(),
4166 hir::MatchSource::IfDesugar {
4167 contains_else_clause: else_opt.is_some()
4171 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4172 hir::ExprKind::While(
4173 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
4174 this.lower_block(body, false),
4175 this.lower_label(opt_label),
4178 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4179 hir::ExprKind::Loop(
4180 this.lower_block(body, false),
4181 this.lower_label(opt_label),
4182 hir::LoopSource::Loop,
4185 ExprKind::TryBlock(ref body) => {
4186 self.with_catch_scope(body.id, |this| {
4187 let unstable_span = this.sess.source_map().mark_span_with_reason(
4188 CompilerDesugaringKind::TryBlock,
4190 Some(vec![sym::try_trait].into()),
4192 let mut block = this.lower_block(body, true).into_inner();
4193 let tail = block.expr.take().map_or_else(
4195 let span = this.sess.source_map().end_point(unstable_span);
4198 node: hir::ExprKind::Tup(hir_vec![]),
4199 attrs: ThinVec::new(),
4200 hir_id: this.next_id(),
4203 |x: P<hir::Expr>| x.into_inner(),
4205 block.expr = Some(this.wrap_in_try_constructor(
4206 sym::from_ok, tail, unstable_span));
4207 hir::ExprKind::Block(P(block), None)
4210 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
4211 P(self.lower_expr(expr)),
4212 arms.iter().map(|x| self.lower_arm(x)).collect(),
4213 hir::MatchSource::Normal,
4215 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
4216 self.make_async_expr(capture_clause, closure_node_id, None, block.span, |this| {
4217 this.with_new_scopes(|this| {
4218 let block = this.lower_block(block, false);
4219 this.expr_block(block, ThinVec::new())
4223 ExprKind::Await(_origin, ref expr) => self.lower_await(e.span, expr),
4225 capture_clause, ref asyncness, movability, ref decl, ref body, fn_decl_span
4227 if let IsAsync::Async { closure_id, .. } = asyncness {
4228 let outer_decl = FnDecl {
4229 inputs: decl.inputs.clone(),
4230 output: FunctionRetTy::Default(fn_decl_span),
4233 // We need to lower the declaration outside the new scope, because we
4234 // have to conserve the state of being inside a loop condition for the
4235 // closure argument types.
4236 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
4238 self.with_new_scopes(|this| {
4239 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
4240 if capture_clause == CaptureBy::Ref &&
4241 !decl.inputs.is_empty()
4247 "`async` non-`move` closures with arguments \
4248 are not currently supported",
4250 .help("consider using `let` statements to manually capture \
4251 variables by reference before entering an \
4252 `async move` closure")
4256 // Transform `async |x: u8| -> X { ... }` into
4257 // `|x: u8| future_from_generator(|| -> X { ... })`.
4258 let body_id = this.lower_body(Some(&outer_decl), |this| {
4259 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
4262 let async_body = this.make_async_expr(
4263 capture_clause, *closure_id, async_ret_ty, body.span,
4265 this.with_new_scopes(|this| this.lower_expr(body))
4267 this.expr(fn_decl_span, async_body, ThinVec::new())
4269 hir::ExprKind::Closure(
4270 this.lower_capture_clause(capture_clause),
4278 // Lower outside new scope to preserve `is_in_loop_condition`.
4279 let fn_decl = self.lower_fn_decl(decl, None, false, None);
4281 self.with_new_scopes(|this| {
4282 this.current_item = Some(fn_decl_span);
4283 let mut is_generator = false;
4284 let body_id = this.lower_body(Some(decl), |this| {
4285 let e = this.lower_expr(body);
4286 is_generator = this.is_generator;
4289 let generator_option = if is_generator {
4290 if !decl.inputs.is_empty() {
4295 "generators cannot have explicit arguments"
4297 this.sess.abort_if_errors();
4299 Some(match movability {
4300 Movability::Movable => hir::GeneratorMovability::Movable,
4301 Movability::Static => hir::GeneratorMovability::Static,
4304 if movability == Movability::Static {
4309 "closures cannot be static"
4314 hir::ExprKind::Closure(
4315 this.lower_capture_clause(capture_clause),
4324 ExprKind::Block(ref blk, opt_label) => {
4325 hir::ExprKind::Block(self.lower_block(blk,
4326 opt_label.is_some()),
4327 self.lower_label(opt_label))
4329 ExprKind::Assign(ref el, ref er) => {
4330 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
4332 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
4333 self.lower_binop(op),
4334 P(self.lower_expr(el)),
4335 P(self.lower_expr(er)),
4337 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
4338 ExprKind::Index(ref el, ref er) => {
4339 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
4341 // Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
4342 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
4343 let id = self.next_id();
4344 let e1 = self.lower_expr(e1);
4345 let e2 = self.lower_expr(e2);
4346 self.expr_call_std_assoc_fn(
4349 &[sym::ops, sym::RangeInclusive],
4354 ExprKind::Range(ref e1, ref e2, lims) => {
4355 use syntax::ast::RangeLimits::*;
4357 let path = match (e1, e2, lims) {
4358 (&None, &None, HalfOpen) => sym::RangeFull,
4359 (&Some(..), &None, HalfOpen) => sym::RangeFrom,
4360 (&None, &Some(..), HalfOpen) => sym::RangeTo,
4361 (&Some(..), &Some(..), HalfOpen) => sym::Range,
4362 (&None, &Some(..), Closed) => sym::RangeToInclusive,
4363 (&Some(..), &Some(..), Closed) => unreachable!(),
4364 (_, &None, Closed) => self.diagnostic()
4365 .span_fatal(e.span, "inclusive range with no end")
4369 let fields = e1.iter()
4370 .map(|e| ("start", e))
4371 .chain(e2.iter().map(|e| ("end", e)))
4373 let expr = P(self.lower_expr(&e));
4374 let ident = Ident::new(Symbol::intern(s), e.span);
4375 self.field(ident, expr, e.span)
4377 .collect::<P<[hir::Field]>>();
4379 let is_unit = fields.is_empty();
4380 let struct_path = [sym::ops, path];
4381 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
4382 let struct_path = hir::QPath::Resolved(None, P(struct_path));
4385 hir_id: self.lower_node_id(e.id),
4387 hir::ExprKind::Path(struct_path)
4389 hir::ExprKind::Struct(P(struct_path), fields, None)
4392 attrs: e.attrs.clone(),
4395 ExprKind::Path(ref qself, ref path) => {
4396 let qpath = self.lower_qpath(
4400 ParamMode::Optional,
4401 ImplTraitContext::disallowed(),
4403 hir::ExprKind::Path(qpath)
4405 ExprKind::Break(opt_label, ref opt_expr) => {
4406 let destination = if self.is_in_loop_condition && opt_label.is_none() {
4409 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4412 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4414 hir::ExprKind::Break(
4416 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
4419 ExprKind::Continue(opt_label) => {
4420 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
4423 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4426 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4429 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
4430 ExprKind::InlineAsm(ref asm) => {
4431 let hir_asm = hir::InlineAsm {
4432 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
4433 outputs: asm.outputs
4435 .map(|out| hir::InlineAsmOutput {
4436 constraint: out.constraint.clone(),
4438 is_indirect: out.is_indirect,
4439 span: out.expr.span,
4442 asm: asm.asm.clone(),
4443 asm_str_style: asm.asm_str_style,
4444 clobbers: asm.clobbers.clone().into(),
4445 volatile: asm.volatile,
4446 alignstack: asm.alignstack,
4447 dialect: asm.dialect,
4450 let outputs = asm.outputs
4452 .map(|out| self.lower_expr(&out.expr))
4454 let inputs = asm.inputs
4456 .map(|&(_, ref input)| self.lower_expr(input))
4458 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
4460 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4465 ParamMode::Optional,
4466 ImplTraitContext::disallowed(),
4468 fields.iter().map(|x| self.lower_field(x)).collect(),
4469 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4471 ExprKind::Paren(ref ex) => {
4472 let mut ex = self.lower_expr(ex);
4473 // Include parens in span, but only if it is a super-span.
4474 if e.span.contains(ex.span) {
4477 // Merge attributes into the inner expression.
4478 let mut attrs = e.attrs.clone();
4479 attrs.extend::<Vec<_>>(ex.attrs.into());
4484 ExprKind::Yield(ref opt_expr) => {
4485 self.is_generator = true;
4488 .map(|x| self.lower_expr(x))
4489 .unwrap_or_else(|| self.expr_unit(e.span));
4490 hir::ExprKind::Yield(P(expr))
4493 ExprKind::Err => hir::ExprKind::Err,
4495 // Desugar `ExprIfLet`
4496 // from: `if let <pat> = <sub_expr> <body> [<else_opt>]`
4497 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4500 // match <sub_expr> {
4502 // _ => [<else_opt> | ()]
4505 let mut arms = vec![];
4507 // `<pat> => <body>`
4509 let body = self.lower_block(body, false);
4510 let body_expr = P(self.expr_block(body, ThinVec::new()));
4511 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4512 arms.push(self.arm(pats, body_expr));
4515 // _ => [<else_opt>|{}]
4517 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4518 let wildcard_pattern = self.pat_wild(e.span);
4519 let body = if let Some(else_expr) = wildcard_arm {
4520 self.lower_expr(else_expr)
4522 self.expr_block_empty(e.span)
4524 arms.push(self.arm(hir_vec![wildcard_pattern], P(body)));
4527 let contains_else_clause = else_opt.is_some();
4529 let sub_expr = P(self.lower_expr(sub_expr));
4531 hir::ExprKind::Match(
4534 hir::MatchSource::IfLetDesugar {
4535 contains_else_clause,
4540 // Desugar `ExprWhileLet`
4541 // from: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4542 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4545 // [opt_ident]: loop {
4546 // match <sub_expr> {
4552 // Note that the block AND the condition are evaluated in the loop scope.
4553 // This is done to allow `break` from inside the condition of the loop.
4554 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4556 this.lower_block(body, false),
4557 this.expr_break(e.span, ThinVec::new()),
4558 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4562 // `<pat> => <body>`
4564 let body_expr = P(self.expr_block(body, ThinVec::new()));
4565 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4566 self.arm(pats, body_expr)
4571 let pat_under = self.pat_wild(e.span);
4572 self.arm(hir_vec![pat_under], break_expr)
4575 // `match <sub_expr> { ... }`
4576 let arms = hir_vec![pat_arm, break_arm];
4577 let match_expr = self.expr(
4579 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4583 // `[opt_ident]: loop { ... }`
4584 let loop_block = P(self.block_expr(P(match_expr)));
4585 let loop_expr = hir::ExprKind::Loop(
4587 self.lower_label(opt_label),
4588 hir::LoopSource::WhileLet,
4590 // Add attributes to the outer returned expr node.
4594 // Desugar `ExprForLoop`
4595 // from: `[opt_ident]: for <pat> in <head> <body>`
4596 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4600 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4602 // [opt_ident]: loop {
4604 // match ::std::iter::Iterator::next(&mut iter) {
4605 // ::std::option::Option::Some(val) => __next = val,
4606 // ::std::option::Option::None => break
4608 // let <pat> = __next;
4609 // StmtKind::Expr(<body>);
4617 let mut head = self.lower_expr(head);
4618 let head_sp = head.span;
4619 let desugared_span = self.sess.source_map().mark_span_with_reason(
4620 CompilerDesugaringKind::ForLoop,
4624 head.span = desugared_span;
4626 let iter = Ident::with_empty_ctxt(sym::iter);
4628 let next_ident = Ident::with_empty_ctxt(sym::__next);
4629 let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
4632 hir::BindingAnnotation::Mutable,
4635 // `::std::option::Option::Some(val) => __next = val`
4637 let val_ident = Ident::with_empty_ctxt(sym::val);
4638 let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
4639 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat_hid));
4640 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat_hid));
4641 let assign = P(self.expr(
4643 hir::ExprKind::Assign(next_expr, val_expr),
4646 let some_pat = self.pat_some(pat.span, val_pat);
4647 self.arm(hir_vec![some_pat], assign)
4650 // `::std::option::Option::None => break`
4653 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4654 let pat = self.pat_none(e.span);
4655 self.arm(hir_vec![pat], break_expr)
4659 let (iter_pat, iter_pat_nid) = self.pat_ident_binding_mode(
4662 hir::BindingAnnotation::Mutable
4665 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4667 let iter = P(self.expr_ident(head_sp, iter, iter_pat_nid));
4668 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4669 let next_path = &[sym::iter, sym::Iterator, sym::next];
4670 let next_expr = P(self.expr_call_std_path(
4673 hir_vec![ref_mut_iter],
4675 let arms = hir_vec![pat_arm, break_arm];
4679 hir::ExprKind::Match(
4682 hir::MatchSource::ForLoopDesugar
4687 let match_stmt = self.stmt(head_sp, hir::StmtKind::Expr(match_expr));
4689 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat_hid));
4692 let next_let = self.stmt_let_pat(
4696 hir::LocalSource::ForLoopDesugar,
4699 // `let <pat> = __next`
4700 let pat = self.lower_pat(pat);
4701 let pat_let = self.stmt_let_pat(
4705 hir::LocalSource::ForLoopDesugar,
4708 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4709 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4710 let body_stmt = self.stmt(body.span, hir::StmtKind::Expr(body_expr));
4712 let loop_block = P(self.block_all(
4714 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4718 // `[opt_ident]: loop { ... }`
4719 let loop_expr = hir::ExprKind::Loop(
4721 self.lower_label(opt_label),
4722 hir::LoopSource::ForLoop,
4724 let loop_expr = P(hir::Expr {
4725 hir_id: self.lower_node_id(e.id),
4728 attrs: ThinVec::new(),
4731 // `mut iter => { ... }`
4732 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4734 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4735 let into_iter_expr = {
4736 let into_iter_path =
4737 &[sym::iter, sym::IntoIterator, sym::into_iter];
4738 P(self.expr_call_std_path(
4745 let match_expr = P(self.expr_match(
4749 hir::MatchSource::ForLoopDesugar,
4752 // This is effectively `{ let _result = ...; _result }`.
4753 // The construct was introduced in #21984.
4754 // FIXME(60253): Is this still necessary?
4755 // Also, add the attributes to the outer returned expr node.
4756 return self.expr_drop_temps(head_sp, match_expr, e.attrs.clone())
4759 // Desugar `ExprKind::Try`
4761 ExprKind::Try(ref sub_expr) => {
4764 // match Try::into_result(<expr>) {
4765 // Ok(val) => #[allow(unreachable_code)] val,
4766 // Err(err) => #[allow(unreachable_code)]
4767 // // If there is an enclosing `catch {...}`
4768 // break 'catch_target Try::from_error(From::from(err)),
4770 // return Try::from_error(From::from(err)),
4773 let unstable_span = self.sess.source_map().mark_span_with_reason(
4774 CompilerDesugaringKind::QuestionMark,
4776 Some(vec![sym::try_trait].into()),
4778 let try_span = self.sess.source_map().end_point(e.span);
4779 let try_span = self.sess.source_map().mark_span_with_reason(
4780 CompilerDesugaringKind::QuestionMark,
4782 Some(vec![sym::try_trait].into()),
4785 // `Try::into_result(<expr>)`
4788 let sub_expr = self.lower_expr(sub_expr);
4790 let path = &[sym::ops, sym::Try, sym::into_result];
4791 P(self.expr_call_std_path(
4798 // `#[allow(unreachable_code)]`
4800 // `allow(unreachable_code)`
4802 let allow_ident = Ident::with_empty_ctxt(sym::allow).with_span_pos(e.span);
4803 let uc_ident = Ident::with_empty_ctxt(sym::unreachable_code)
4804 .with_span_pos(e.span);
4805 let uc_nested = attr::mk_nested_word_item(uc_ident);
4806 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4808 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4810 let attrs = vec![attr];
4812 // `Ok(val) => #[allow(unreachable_code)] val,`
4814 let val_ident = Ident::with_empty_ctxt(sym::val);
4815 let (val_pat, val_pat_nid) = self.pat_ident(e.span, val_ident);
4816 let val_expr = P(self.expr_ident_with_attrs(
4820 ThinVec::from(attrs.clone()),
4822 let ok_pat = self.pat_ok(e.span, val_pat);
4824 self.arm(hir_vec![ok_pat], val_expr)
4827 // `Err(err) => #[allow(unreachable_code)]
4828 // return Try::from_error(From::from(err)),`
4830 let err_ident = Ident::with_empty_ctxt(sym::err);
4831 let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
4833 let from_path = &[sym::convert, sym::From, sym::from];
4834 let err_expr = self.expr_ident(try_span, err_ident, err_local_nid);
4835 self.expr_call_std_path(try_span, from_path, hir_vec![err_expr])
4838 self.wrap_in_try_constructor(sym::from_error, from_expr, unstable_span);
4839 let thin_attrs = ThinVec::from(attrs);
4840 let catch_scope = self.catch_scopes.last().map(|x| *x);
4841 let ret_expr = if let Some(catch_node) = catch_scope {
4842 let target_id = Ok(self.lower_node_id(catch_node));
4845 hir::ExprKind::Break(
4850 Some(from_err_expr),
4855 P(self.expr(try_span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4858 let err_pat = self.pat_err(try_span, err_local);
4859 self.arm(hir_vec![err_pat], ret_expr)
4862 hir::ExprKind::Match(
4864 hir_vec![err_arm, ok_arm],
4865 hir::MatchSource::TryDesugar,
4869 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4873 hir_id: self.lower_node_id(e.id),
4876 attrs: e.attrs.clone(),
4880 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
4881 smallvec![match s.node {
4882 StmtKind::Local(ref l) => {
4883 let (l, item_ids) = self.lower_local(l);
4884 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
4887 let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
4888 self.stmt(s.span, hir::StmtKind::Item(item_id))
4893 hir_id: self.lower_node_id(s.id),
4894 node: hir::StmtKind::Local(P(l)),
4900 StmtKind::Item(ref it) => {
4901 // Can only use the ID once.
4902 let mut id = Some(s.id);
4903 return self.lower_item_id(it)
4906 let hir_id = id.take()
4907 .map(|id| self.lower_node_id(id))
4908 .unwrap_or_else(|| self.next_id());
4912 node: hir::StmtKind::Item(item_id),
4918 StmtKind::Expr(ref e) => {
4920 hir_id: self.lower_node_id(s.id),
4921 node: hir::StmtKind::Expr(P(self.lower_expr(e))),
4925 StmtKind::Semi(ref e) => {
4927 hir_id: self.lower_node_id(s.id),
4928 node: hir::StmtKind::Semi(P(self.lower_expr(e))),
4932 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4936 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4938 CaptureBy::Value => hir::CaptureByValue,
4939 CaptureBy::Ref => hir::CaptureByRef,
4943 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4944 /// the address space of that item instead of the item currently being
4945 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4946 /// lower a `Visibility` value although we haven't lowered the owning
4947 /// `ImplItem` in question yet.
4948 fn lower_visibility(
4951 explicit_owner: Option<NodeId>,
4952 ) -> hir::Visibility {
4953 let node = match v.node {
4954 VisibilityKind::Public => hir::VisibilityKind::Public,
4955 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4956 VisibilityKind::Restricted { ref path, id } => {
4957 debug!("lower_visibility: restricted path id = {:?}", id);
4958 let lowered_id = if let Some(owner) = explicit_owner {
4959 self.lower_node_id_with_owner(id, owner)
4961 self.lower_node_id(id)
4963 let res = self.expect_full_res(id);
4964 let res = self.lower_res(res);
4965 hir::VisibilityKind::Restricted {
4966 path: P(self.lower_path_extra(
4969 ParamMode::Explicit,
4975 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4977 respan(v.span, node)
4980 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4982 Defaultness::Default => hir::Defaultness::Default {
4983 has_value: has_value,
4985 Defaultness::Final => {
4987 hir::Defaultness::Final
4992 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4994 BlockCheckMode::Default => hir::DefaultBlock,
4995 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4999 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
5001 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
5002 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
5003 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
5004 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
5008 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
5010 CompilerGenerated => hir::CompilerGenerated,
5011 UserProvided => hir::UserProvided,
5015 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
5017 ImplPolarity::Positive => hir::ImplPolarity::Positive,
5018 ImplPolarity::Negative => hir::ImplPolarity::Negative,
5022 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
5024 TraitBoundModifier::None => hir::TraitBoundModifier::None,
5025 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
5029 // Helper methods for building HIR.
5031 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
5033 hir_id: self.next_id(),
5042 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
5044 hir_id: self.next_id(),
5048 is_shorthand: false,
5052 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
5053 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
5054 P(self.expr(span, expr_break, attrs))
5061 args: hir::HirVec<hir::Expr>,
5063 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
5066 // Note: associated functions must use `expr_call_std_path`.
5067 fn expr_call_std_path(
5070 path_components: &[Symbol],
5071 args: hir::HirVec<hir::Expr>,
5073 let path = P(self.expr_std_path(span, path_components, None, ThinVec::new()));
5074 self.expr_call(span, path, args)
5077 // Create an expression calling an associated function of an std type.
5079 // Associated functions cannot be resolved through the normal `std_path` function,
5080 // as they are resolved differently and so cannot use `expr_call_std_path`.
5082 // This function accepts the path component (`ty_path_components`) separately from
5083 // the name of the associated function (`assoc_fn_name`) in order to facilitate
5084 // separate resolution of the type and creation of a path referring to its associated
5086 fn expr_call_std_assoc_fn(
5088 ty_path_id: hir::HirId,
5090 ty_path_components: &[Symbol],
5091 assoc_fn_name: &str,
5092 args: hir::HirVec<hir::Expr>,
5093 ) -> hir::ExprKind {
5094 let ty_path = P(self.std_path(span, ty_path_components, None, false));
5095 let ty = P(self.ty_path(ty_path_id, span, hir::QPath::Resolved(None, ty_path)));
5096 let fn_seg = P(hir::PathSegment::from_ident(Ident::from_str(assoc_fn_name)));
5097 let fn_path = hir::QPath::TypeRelative(ty, fn_seg);
5098 let fn_expr = P(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
5099 hir::ExprKind::Call(fn_expr, args)
5102 fn expr_ident(&mut self, span: Span, ident: Ident, binding: hir::HirId) -> hir::Expr {
5103 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
5106 fn expr_ident_with_attrs(
5110 binding: hir::HirId,
5111 attrs: ThinVec<Attribute>,
5113 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
5117 res: Res::Local(binding),
5118 segments: hir_vec![hir::PathSegment::from_ident(ident)],
5122 self.expr(span, expr_path, attrs)
5125 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
5126 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
5132 components: &[Symbol],
5133 params: Option<P<hir::GenericArgs>>,
5134 attrs: ThinVec<Attribute>,
5136 let path = self.std_path(span, components, params, true);
5139 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
5144 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
5146 /// In terms of drop order, it has the same effect as wrapping `expr` in
5147 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
5149 /// The drop order can be important in e.g. `if expr { .. }`.
5154 attrs: ThinVec<Attribute>
5156 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
5163 arms: hir::HirVec<hir::Arm>,
5164 source: hir::MatchSource,
5166 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
5169 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
5170 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
5173 fn expr_unit(&mut self, sp: Span) -> hir::Expr {
5174 self.expr_tuple(sp, hir_vec![])
5177 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> hir::Expr {
5178 self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new())
5181 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
5183 hir_id: self.next_id(),
5190 fn stmt(&mut self, span: Span, node: hir::StmtKind) -> hir::Stmt {
5191 hir::Stmt { span, node, hir_id: self.next_id() }
5197 init: Option<P<hir::Expr>>,
5199 source: hir::LocalSource,
5201 let local = hir::Local {
5205 hir_id: self.next_id(),
5208 attrs: ThinVec::new()
5210 self.stmt(span, hir::StmtKind::Local(P(local)))
5213 fn expr_block_empty(&mut self, span: Span) -> hir::Expr {
5214 let blk = self.block_all(span, hir_vec![], None);
5215 self.expr_block(P(blk), ThinVec::new())
5218 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
5219 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
5225 stmts: hir::HirVec<hir::Stmt>,
5226 expr: Option<P<hir::Expr>>,
5231 hir_id: self.next_id(),
5232 rules: hir::DefaultBlock,
5234 targeted_by_break: false,
5238 fn expr_unsafe(&mut self, expr: P<hir::Expr>) -> hir::Expr {
5239 let hir_id = self.next_id();
5240 let span = expr.span;
5243 hir::ExprKind::Block(P(hir::Block {
5247 rules: hir::UnsafeBlock(hir::CompilerGenerated),
5249 targeted_by_break: false,
5255 /// Constructs a `true` or `false` literal pattern.
5256 fn pat_bool(&mut self, span: Span, val: bool) -> P<hir::Pat> {
5257 let lit = Spanned { span, node: LitKind::Bool(val) };
5258 let expr = self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new());
5259 self.pat(span, hir::PatKind::Lit(P(expr)))
5262 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5263 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![pat])
5266 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5267 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![pat])
5270 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5271 self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![pat])
5274 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
5275 self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], hir_vec![])
5281 components: &[Symbol],
5282 subpats: hir::HirVec<P<hir::Pat>>,
5284 let path = self.std_path(span, components, None, true);
5285 let qpath = hir::QPath::Resolved(None, P(path));
5286 let pt = if subpats.is_empty() {
5287 hir::PatKind::Path(qpath)
5289 hir::PatKind::TupleStruct(qpath, subpats, None)
5294 fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<hir::Pat>, hir::HirId) {
5295 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
5298 fn pat_ident_binding_mode(
5302 bm: hir::BindingAnnotation,
5303 ) -> (P<hir::Pat>, hir::HirId) {
5304 let hir_id = self.next_id();
5309 node: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
5316 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
5317 self.pat(span, hir::PatKind::Wild)
5320 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
5322 hir_id: self.next_id(),
5328 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
5329 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
5330 /// The path is also resolved according to `is_value`.
5334 components: &[Symbol],
5335 params: Option<P<hir::GenericArgs>>,
5338 let mut path = self.resolver
5339 .resolve_str_path(span, self.crate_root, components, is_value);
5340 path.segments.last_mut().unwrap().args = params;
5342 for seg in path.segments.iter_mut() {
5343 if seg.hir_id.is_some() {
5344 seg.hir_id = Some(self.next_id());
5350 fn ty_path(&mut self, mut hir_id: hir::HirId, span: Span, qpath: hir::QPath) -> hir::Ty {
5351 let node = match qpath {
5352 hir::QPath::Resolved(None, path) => {
5353 // Turn trait object paths into `TyKind::TraitObject` instead.
5355 Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
5356 let principal = hir::PolyTraitRef {
5357 bound_generic_params: hir::HirVec::new(),
5358 trait_ref: hir::TraitRef {
5359 path: path.and_then(|path| path),
5365 // The original ID is taken by the `PolyTraitRef`,
5366 // so the `Ty` itself needs a different one.
5367 hir_id = self.next_id();
5368 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
5370 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
5373 _ => hir::TyKind::Path(qpath),
5382 /// Invoked to create the lifetime argument for a type `&T`
5383 /// with no explicit lifetime.
5384 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
5385 match self.anonymous_lifetime_mode {
5386 // Intercept when we are in an impl header or async fn and introduce an in-band
5388 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
5390 AnonymousLifetimeMode::CreateParameter => {
5391 let fresh_name = self.collect_fresh_in_band_lifetime(span);
5393 hir_id: self.next_id(),
5395 name: hir::LifetimeName::Param(fresh_name),
5399 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5401 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5403 AnonymousLifetimeMode::Replace(replacement) => {
5404 self.new_replacement_lifetime(replacement, span)
5409 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
5410 /// return a "error lifetime".
5411 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
5412 let (id, msg, label) = match id {
5413 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
5416 self.sess.next_node_id(),
5417 "`&` without an explicit lifetime name cannot be used here",
5418 "explicit lifetime name needed here",
5422 let mut err = struct_span_err!(
5429 err.span_label(span, label);
5432 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5435 /// Invoked to create the lifetime argument(s) for a path like
5436 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
5437 /// sorts of cases are deprecated. This may therefore report a warning or an
5438 /// error, depending on the mode.
5439 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
5441 .map(|_| self.elided_path_lifetime(span))
5445 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
5446 match self.anonymous_lifetime_mode {
5447 AnonymousLifetimeMode::CreateParameter => {
5448 // We should have emitted E0726 when processing this path above
5449 self.sess.delay_span_bug(
5451 "expected 'implicit elided lifetime not allowed' error",
5453 let id = self.sess.next_node_id();
5454 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5456 // This is the normal case.
5457 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5459 AnonymousLifetimeMode::Replace(replacement) => {
5460 self.new_replacement_lifetime(replacement, span)
5463 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5467 /// Invoked to create the lifetime argument(s) for an elided trait object
5468 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
5469 /// when the bound is written, even if it is written with `'_` like in
5470 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
5471 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
5472 match self.anonymous_lifetime_mode {
5473 // NB. We intentionally ignore the create-parameter mode here.
5474 // and instead "pass through" to resolve-lifetimes, which will apply
5475 // the object-lifetime-defaulting rules. Elided object lifetime defaults
5476 // do not act like other elided lifetimes. In other words, given this:
5478 // impl Foo for Box<dyn Debug>
5480 // we do not introduce a fresh `'_` to serve as the bound, but instead
5481 // ultimately translate to the equivalent of:
5483 // impl Foo for Box<dyn Debug + 'static>
5485 // `resolve_lifetime` has the code to make that happen.
5486 AnonymousLifetimeMode::CreateParameter => {}
5488 AnonymousLifetimeMode::ReportError => {
5489 // ReportError applies to explicit use of `'_`.
5492 // This is the normal case.
5493 AnonymousLifetimeMode::PassThrough => {}
5495 // We don't need to do any replacement here as this lifetime
5496 // doesn't refer to an elided lifetime elsewhere in the function
5498 AnonymousLifetimeMode::Replace(_) => {}
5501 self.new_implicit_lifetime(span)
5504 fn new_replacement_lifetime(
5506 replacement: LtReplacement,
5508 ) -> hir::Lifetime {
5509 let hir_id = self.next_id();
5510 self.replace_elided_lifetime(hir_id, span, replacement)
5513 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
5515 hir_id: self.next_id(),
5517 name: hir::LifetimeName::Implicit,
5521 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
5522 self.sess.buffer_lint_with_diagnostic(
5523 builtin::BARE_TRAIT_OBJECTS,
5526 "trait objects without an explicit `dyn` are deprecated",
5527 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
5531 fn wrap_in_try_constructor(
5535 unstable_span: Span,
5537 let path = &[sym::ops, sym::Try, method];
5538 let from_err = P(self.expr_std_path(unstable_span, path, None,
5540 P(self.expr_call(e.span, from_err, hir_vec![e]))
5547 ) -> hir::ExprKind {
5551 // let mut pinned = <expr>;
5553 // match ::std::future::poll_with_tls_context(unsafe {
5554 // ::std::pin::Pin::new_unchecked(&mut pinned)
5556 // ::std::task::Poll::Ready(result) => break result,
5557 // ::std::task::Poll::Pending => {},
5562 if !self.is_async_body {
5563 let mut err = struct_span_err!(
5567 "`await` is only allowed inside `async` functions and blocks"
5569 err.span_label(await_span, "only allowed inside `async` functions and blocks");
5570 if let Some(item_sp) = self.current_item {
5571 err.span_label(item_sp, "this is not `async`");
5574 return hir::ExprKind::Err;
5576 let span = self.sess.source_map().mark_span_with_reason(
5577 CompilerDesugaringKind::Await,
5581 let gen_future_span = self.sess.source_map().mark_span_with_reason(
5582 CompilerDesugaringKind::Await,
5584 Some(vec![sym::gen_future].into()),
5587 // let mut pinned = <expr>;
5588 let expr = P(self.lower_expr(expr));
5589 let pinned_ident = Ident::with_empty_ctxt(sym::pinned);
5590 let (pinned_pat, pinned_pat_hid) = self.pat_ident_binding_mode(
5593 hir::BindingAnnotation::Mutable,
5595 let pinned_let = self.stmt_let_pat(
5599 hir::LocalSource::AwaitDesugar,
5602 // ::std::future::poll_with_tls_context(unsafe {
5603 // ::std::pin::Pin::new_unchecked(&mut pinned)
5606 let pinned = P(self.expr_ident(span, pinned_ident, pinned_pat_hid));
5607 let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
5608 let pin_ty_id = self.next_id();
5609 let new_unchecked_expr_kind = self.expr_call_std_assoc_fn(
5612 &[sym::pin, sym::Pin],
5614 hir_vec![ref_mut_pinned],
5616 let new_unchecked = P(self.expr(span, new_unchecked_expr_kind, ThinVec::new()));
5617 let unsafe_expr = self.expr_unsafe(new_unchecked);
5618 P(self.expr_call_std_path(
5620 &[sym::future, sym::poll_with_tls_context],
5621 hir_vec![unsafe_expr],
5625 // `::std::task::Poll::Ready(result) => break result`
5626 let loop_node_id = self.sess.next_node_id();
5627 let loop_hir_id = self.lower_node_id(loop_node_id);
5629 let x_ident = Ident::with_empty_ctxt(sym::result);
5630 let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
5631 let x_expr = P(self.expr_ident(span, x_ident, x_pat_hid));
5632 let ready_pat = self.pat_std_enum(
5634 &[sym::task, sym::Poll, sym::Ready],
5637 let break_x = self.with_loop_scope(loop_node_id, |this| {
5638 let expr_break = hir::ExprKind::Break(
5639 this.lower_loop_destination(None),
5642 P(this.expr(await_span, expr_break, ThinVec::new()))
5644 self.arm(hir_vec![ready_pat], break_x)
5647 // `::std::task::Poll::Pending => {}`
5649 let pending_pat = self.pat_std_enum(
5651 &[sym::task, sym::Poll, sym::Pending],
5654 let empty_block = P(self.expr_block_empty(span));
5655 self.arm(hir_vec![pending_pat], empty_block)
5659 let match_expr = P(self.expr_match(
5662 hir_vec![ready_arm, pending_arm],
5663 hir::MatchSource::AwaitDesugar,
5665 self.stmt(span, hir::StmtKind::Expr(match_expr))
5669 let unit = self.expr_unit(span);
5670 let yield_expr = P(self.expr(
5672 hir::ExprKind::Yield(P(unit)),
5675 self.stmt(span, hir::StmtKind::Expr(yield_expr))
5678 let loop_block = P(self.block_all(
5680 hir_vec![match_stmt, yield_stmt],
5684 let loop_expr = P(hir::Expr {
5685 hir_id: loop_hir_id,
5686 node: hir::ExprKind::Loop(
5689 hir::LoopSource::Loop,
5692 attrs: ThinVec::new(),
5695 hir::ExprKind::Block(
5696 P(self.block_all(span, hir_vec![pinned_let], Some(loop_expr))),
5702 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5703 // Sorting by span ensures that we get things in order within a
5704 // file, and also puts the files in a sensible order.
5705 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5706 body_ids.sort_by_key(|b| bodies[b].value.span);
5710 /// Checks if the specified expression is a built-in range literal.
5711 /// (See: `LoweringContext::lower_expr()`).
5712 pub fn is_range_literal(sess: &Session, expr: &hir::Expr) -> bool {
5713 use hir::{Path, QPath, ExprKind, TyKind};
5715 // Returns whether the given path represents a (desugared) range,
5716 // either in std or core, i.e. has either a `::std::ops::Range` or
5717 // `::core::ops::Range` prefix.
5718 fn is_range_path(path: &Path) -> bool {
5719 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.as_str().to_string()).collect();
5720 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
5722 // "{{root}}" is the equivalent of `::` prefix in `Path`.
5723 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
5724 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
5730 // Check whether a span corresponding to a range expression is a
5731 // range literal, rather than an explicit struct or `new()` call.
5732 fn is_lit(sess: &Session, span: &Span) -> bool {
5733 let source_map = sess.source_map();
5734 let end_point = source_map.end_point(*span);
5736 if let Ok(end_string) = source_map.span_to_snippet(end_point) {
5737 !(end_string.ends_with("}") || end_string.ends_with(")"))
5744 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
5745 ExprKind::Struct(ref qpath, _, _) => {
5746 if let QPath::Resolved(None, ref path) = **qpath {
5747 return is_range_path(&path) && is_lit(sess, &expr.span);
5751 // `..` desugars to its struct path.
5752 ExprKind::Path(QPath::Resolved(None, ref path)) => {
5753 return is_range_path(&path) && is_lit(sess, &expr.span);
5756 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
5757 ExprKind::Call(ref func, _) => {
5758 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.node {
5759 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.node {
5760 let new_call = segment.ident.as_str() == "new";
5761 return is_range_path(&path) && is_lit(sess, &expr.span) && new_call;