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, DefIndexAddressSpace, CRATE_DEF_INDEX};
40 use crate::hir::def::{Def, PathResolution, PerNS};
41 use crate::hir::{GenericArg, ConstArg};
42 use crate::lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
43 ELIDED_LIFETIMES_IN_PATHS};
44 use crate::middle::cstore::CrateStore;
45 use crate::session::Session;
46 use crate::session::config::nightly_options;
47 use crate::util::common::FN_OUTPUT_NAME;
48 use crate::util::nodemap::{DefIdMap, NodeMap};
49 use errors::Applicability;
50 use rustc_data_structures::fx::FxHashSet;
51 use rustc_data_structures::indexed_vec::IndexVec;
52 use rustc_data_structures::thin_vec::ThinVec;
53 use rustc_data_structures::sync::Lrc;
55 use std::collections::{BTreeSet, BTreeMap};
57 use smallvec::SmallVec;
62 use syntax::ext::hygiene::{Mark, SyntaxContext};
63 use syntax::print::pprust;
65 use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned};
66 use syntax::std_inject;
67 use syntax::symbol::{keywords, 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<&'static str>,
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>,
99 catch_scopes: Vec<NodeId>,
100 loop_scopes: Vec<NodeId>,
101 is_in_loop_condition: bool,
102 is_in_trait_impl: bool,
104 /// What to do when we encounter either an "anonymous lifetime
105 /// reference". The term "anonymous" is meant to encompass both
106 /// `'_` lifetimes as well as fully elided cases where nothing is
107 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
108 anonymous_lifetime_mode: AnonymousLifetimeMode,
110 /// Used to create lifetime definitions from in-band lifetime usages.
111 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
112 /// When a named lifetime is encountered in a function or impl header and
113 /// has not been defined
114 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
115 /// to this list. The results of this list are then added to the list of
116 /// lifetime definitions in the corresponding impl or function generics.
117 lifetimes_to_define: Vec<(Span, ParamName)>,
119 /// Whether or not in-band lifetimes are being collected. This is used to
120 /// indicate whether or not we're in a place where new lifetimes will result
121 /// in in-band lifetime definitions, such a function or an impl header,
122 /// including implicit lifetimes from `impl_header_lifetime_elision`.
123 is_collecting_in_band_lifetimes: bool,
125 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
126 /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
127 /// against this list to see if it is already in-scope, or if a definition
128 /// needs to be created for it.
129 in_scope_lifetimes: Vec<Ident>,
131 current_module: NodeId,
133 type_def_lifetime_params: DefIdMap<usize>,
135 current_hir_id_owner: Vec<(DefIndex, u32)>,
136 item_local_id_counters: NodeMap<u32>,
137 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
141 /// Resolve a path generated by the lowerer when expanding `for`, `if let`, etc.
148 /// Obtain the resolution for a `NodeId`.
149 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
151 /// Obtain the possible resolutions for the given `use` statement.
152 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
154 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
155 /// This should only return `None` during testing.
156 fn definitions(&mut self) -> &mut Definitions;
158 /// Given suffix `["b", "c", "d"]`, creates a HIR path for `[::crate_root]::b::c::d` and
159 /// resolves it based on `is_value`.
163 crate_root: Option<&str>,
170 enum ImplTraitContext<'a> {
171 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
172 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
173 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
175 /// Newly generated parameters should be inserted into the given `Vec`.
176 Universal(&'a mut Vec<hir::GenericParam>),
178 /// Treat `impl Trait` as shorthand for a new existential parameter.
179 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
180 /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
182 /// We optionally store a `DefId` for the parent item here so we can look up necessary
183 /// information later. It is `None` when no information about the context should be stored,
184 /// e.g., for consts and statics.
185 Existential(Option<DefId>),
187 /// `impl Trait` is not accepted in this position.
188 Disallowed(ImplTraitPosition),
191 /// Position in which `impl Trait` is disallowed. Used for error reporting.
192 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
193 enum ImplTraitPosition {
198 impl<'a> ImplTraitContext<'a> {
200 fn disallowed() -> Self {
201 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
204 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
205 use self::ImplTraitContext::*;
207 Universal(params) => Universal(params),
208 Existential(did) => Existential(*did),
209 Disallowed(pos) => Disallowed(*pos),
216 cstore: &dyn CrateStore,
217 dep_graph: &DepGraph,
219 resolver: &mut dyn Resolver,
221 // We're constructing the HIR here; we don't care what we will
222 // read, since we haven't even constructed the *input* to
224 dep_graph.assert_ignored();
227 crate_root: std_inject::injected_crate_name(),
231 items: BTreeMap::new(),
232 trait_items: BTreeMap::new(),
233 impl_items: BTreeMap::new(),
234 bodies: BTreeMap::new(),
235 trait_impls: BTreeMap::new(),
236 modules: BTreeMap::new(),
237 exported_macros: Vec::new(),
238 catch_scopes: Vec::new(),
239 loop_scopes: Vec::new(),
240 is_in_loop_condition: false,
241 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
242 type_def_lifetime_params: Default::default(),
243 current_module: CRATE_NODE_ID,
244 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
245 item_local_id_counters: Default::default(),
246 node_id_to_hir_id: IndexVec::new(),
248 is_in_trait_impl: false,
249 lifetimes_to_define: Vec::new(),
250 is_collecting_in_band_lifetimes: false,
251 in_scope_lifetimes: Vec::new(),
255 #[derive(Copy, Clone, PartialEq)]
257 /// Any path in a type context.
259 /// The `module::Type` in `module::Type::method` in an expression.
263 enum ParenthesizedGenericArgs {
269 /// What to do when we encounter an **anonymous** lifetime
270 /// reference. Anonymous lifetime references come in two flavors. You
271 /// have implicit, or fully elided, references to lifetimes, like the
272 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
273 /// or `Ref<'_, T>`. These often behave the same, but not always:
275 /// - certain usages of implicit references are deprecated, like
276 /// `Ref<T>`, and we sometimes just give hard errors in those cases
278 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
279 /// the same as `Box<dyn Foo + '_>`.
281 /// We describe the effects of the various modes in terms of three cases:
283 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
284 /// of a `&` (e.g., the missing lifetime in something like `&T`)
285 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
286 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
287 /// elided bounds follow special rules. Note that this only covers
288 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
289 /// '_>` is a case of "modern" elision.
290 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
291 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
292 /// non-deprecated equivalent.
294 /// Currently, the handling of lifetime elision is somewhat spread out
295 /// between HIR lowering and -- as described below -- the
296 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
297 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
298 /// everything into HIR lowering.
299 #[derive(Copy, Clone)]
300 enum AnonymousLifetimeMode {
301 /// For **Modern** cases, create a new anonymous region parameter
302 /// and reference that.
304 /// For **Dyn Bound** cases, pass responsibility to
305 /// `resolve_lifetime` code.
307 /// For **Deprecated** cases, report an error.
310 /// Give a hard error when either `&` or `'_` is written. Used to
311 /// rule out things like `where T: Foo<'_>`. Does not imply an
312 /// error on default object bounds (e.g., `Box<dyn Foo>`).
315 /// Pass responsibility to `resolve_lifetime` code for all cases.
318 /// Used in the return types of `async fn` where there exists
319 /// exactly one argument-position elided lifetime.
321 /// In `async fn`, we lower the arguments types using the `CreateParameter`
322 /// mode, meaning that non-`dyn` elided lifetimes are assigned a fresh name.
323 /// If any corresponding elided lifetimes appear in the output, we need to
324 /// replace them with references to the fresh name assigned to the corresponding
325 /// elided lifetime in the arguments.
327 /// For **Modern cases**, replace the anonymous parameter with a
328 /// reference to a specific freshly-named lifetime that was
329 /// introduced in argument
331 /// For **Dyn Bound** cases, pass responsibility to
332 /// `resole_lifetime` code.
333 Replace(LtReplacement),
336 /// The type of elided lifetime replacement to perform on `async fn` return types.
337 #[derive(Copy, Clone)]
339 /// Fresh name introduced by the single non-dyn elided lifetime
340 /// in the arguments of the async fn.
343 /// There is no single non-dyn elided lifetime because no lifetimes
344 /// appeared in the arguments.
347 /// There is no single non-dyn elided lifetime because multiple
348 /// lifetimes appeared in the arguments.
352 /// Calculates the `LtReplacement` to use for elided lifetimes in the return
353 /// type based on the fresh elided lifetimes introduced in argument position.
354 fn get_elided_lt_replacement(arg_position_lifetimes: &[(Span, ParamName)]) -> LtReplacement {
355 match arg_position_lifetimes {
356 [] => LtReplacement::NoLifetimes,
357 [(_span, param)] => LtReplacement::Some(*param),
358 _ => LtReplacement::MultipleLifetimes,
362 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[NodeId; 1]> }
364 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
365 fn visit_ty(&mut self, ty: &'a Ty) {
371 TyKind::ImplTrait(id, _) => self.ids.push(id),
374 visit::walk_ty(self, ty);
377 fn visit_path_segment(
380 path_segment: &'v PathSegment,
382 if let Some(ref p) = path_segment.args {
383 if let GenericArgs::Parenthesized(_) = **p {
387 visit::walk_path_segment(self, path_span, path_segment)
391 impl<'a> LoweringContext<'a> {
392 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
393 /// Full-crate AST visitor that inserts into a fresh
394 /// `LoweringContext` any information that may be
395 /// needed from arbitrary locations in the crate,
396 /// e.g., the number of lifetime generic parameters
397 /// declared for every type and trait definition.
398 struct MiscCollector<'lcx, 'interner: 'lcx> {
399 lctx: &'lcx mut LoweringContext<'interner>,
400 hir_id_owner: Option<NodeId>,
403 impl MiscCollector<'_, '_> {
404 fn allocate_use_tree_hir_id_counters(
410 UseTreeKind::Simple(_, id1, id2) => {
411 for &id in &[id1, id2] {
412 self.lctx.resolver.definitions().create_def_with_parent(
416 DefIndexAddressSpace::High,
420 self.lctx.allocate_hir_id_counter(id);
423 UseTreeKind::Glob => (),
424 UseTreeKind::Nested(ref trees) => {
425 for &(ref use_tree, id) in trees {
426 let hir_id = self.lctx.allocate_hir_id_counter(id);
427 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
433 fn with_hir_id_owner<F, T>(&mut self, owner: Option<NodeId>, f: F) -> T
435 F: FnOnce(&mut Self) -> T,
437 let old = mem::replace(&mut self.hir_id_owner, owner);
439 self.hir_id_owner = old;
444 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
445 fn visit_pat(&mut self, p: &'lcx Pat) {
447 // Doesn't generate a HIR node
448 PatKind::Paren(..) => {},
450 if let Some(owner) = self.hir_id_owner {
451 self.lctx.lower_node_id_with_owner(p.id, owner);
456 visit::walk_pat(self, p)
459 fn visit_fn(&mut self, fk: visit::FnKind<'lcx>, fd: &'lcx FnDecl, s: Span, _: NodeId) {
460 if fk.header().map(|h| h.asyncness.node.is_async()).unwrap_or(false) {
461 // Don't visit the original pattern for async functions as it will be
463 for arg in &fd.inputs {
464 if let ArgSource::AsyncFn(pat) = &arg.source { self.visit_pat(pat); }
465 self.visit_ty(&arg.ty)
467 self.visit_fn_ret_ty(&fd.output);
470 visit::FnKind::ItemFn(_, decl, _, body) => {
471 self.visit_fn_header(decl);
472 self.visit_block(body)
474 visit::FnKind::Method(_, sig, _, body) => {
475 self.visit_fn_header(&sig.header);
476 self.visit_block(body)
478 visit::FnKind::Closure(body) => self.visit_expr(body),
481 visit::walk_fn(self, fk, fd, s)
485 fn visit_item(&mut self, item: &'lcx Item) {
486 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
489 ItemKind::Struct(_, ref generics)
490 | ItemKind::Union(_, ref generics)
491 | ItemKind::Enum(_, ref generics)
492 | ItemKind::Ty(_, ref generics)
493 | ItemKind::Existential(_, ref generics)
494 | ItemKind::Trait(_, _, ref generics, ..) => {
495 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
499 .filter(|param| match param.kind {
500 ast::GenericParamKind::Lifetime { .. } => true,
504 self.lctx.type_def_lifetime_params.insert(def_id, count);
506 ItemKind::Use(ref use_tree) => {
507 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
512 self.with_hir_id_owner(Some(item.id), |this| {
513 visit::walk_item(this, item);
517 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
518 self.lctx.allocate_hir_id_counter(item.id);
521 TraitItemKind::Method(_, None) => {
522 // Ignore patterns in trait methods without bodies
523 self.with_hir_id_owner(None, |this| {
524 visit::walk_trait_item(this, item)
527 _ => self.with_hir_id_owner(Some(item.id), |this| {
528 visit::walk_trait_item(this, item);
533 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
534 self.lctx.allocate_hir_id_counter(item.id);
535 self.with_hir_id_owner(Some(item.id), |this| {
536 visit::walk_impl_item(this, item);
540 fn visit_foreign_item(&mut self, i: &'lcx ForeignItem) {
541 // Ignore patterns in foreign items
542 self.with_hir_id_owner(None, |this| {
543 visit::walk_foreign_item(this, i)
547 fn visit_ty(&mut self, t: &'lcx Ty) {
549 // Mirrors the case in visit::walk_ty
550 TyKind::BareFn(ref f) => {
556 // Mirrors visit::walk_fn_decl
557 for argument in &f.decl.inputs {
558 // We don't lower the ids of argument patterns
559 self.with_hir_id_owner(None, |this| {
560 this.visit_pat(&argument.pat);
562 self.visit_ty(&argument.ty)
564 self.visit_fn_ret_ty(&f.decl.output)
566 _ => visit::walk_ty(self, t),
571 struct ItemLowerer<'lcx, 'interner: 'lcx> {
572 lctx: &'lcx mut LoweringContext<'interner>,
575 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
576 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
578 F: FnOnce(&mut Self),
580 let old = self.lctx.is_in_trait_impl;
581 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
587 self.lctx.is_in_trait_impl = old;
591 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
592 fn visit_mod(&mut self, m: &'lcx Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
593 self.lctx.modules.insert(n, hir::ModuleItems {
594 items: BTreeSet::new(),
595 trait_items: BTreeSet::new(),
596 impl_items: BTreeSet::new(),
599 let old = self.lctx.current_module;
600 self.lctx.current_module = n;
601 visit::walk_mod(self, m);
602 self.lctx.current_module = old;
605 fn visit_item(&mut self, item: &'lcx Item) {
606 let mut item_hir_id = None;
607 self.lctx.with_hir_id_owner(item.id, |lctx| {
608 if let Some(hir_item) = lctx.lower_item(item) {
609 item_hir_id = Some(hir_item.hir_id);
610 lctx.insert_item(hir_item);
614 if let Some(hir_id) = item_hir_id {
615 let item_generics = match self.lctx.items.get(&hir_id).unwrap().node {
616 hir::ItemKind::Impl(_, _, _, ref generics, ..)
617 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
618 generics.params.clone()
623 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
624 let this = &mut ItemLowerer { lctx: this };
625 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
626 this.with_trait_impl_ref(opt_trait_ref, |this| {
627 visit::walk_item(this, item)
630 visit::walk_item(this, item);
636 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
637 self.lctx.with_hir_id_owner(item.id, |lctx| {
638 let hir_item = lctx.lower_trait_item(item);
639 let id = hir::TraitItemId { hir_id: hir_item.hir_id };
640 lctx.trait_items.insert(id, hir_item);
641 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
644 visit::walk_trait_item(self, item);
647 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
648 self.lctx.with_hir_id_owner(item.id, |lctx| {
649 let hir_item = lctx.lower_impl_item(item);
650 let id = hir::ImplItemId { hir_id: hir_item.hir_id };
651 lctx.impl_items.insert(id, hir_item);
652 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
654 visit::walk_impl_item(self, item);
658 self.lower_node_id(CRATE_NODE_ID);
659 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
661 visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
662 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
664 let module = self.lower_mod(&c.module);
665 let attrs = self.lower_attrs(&c.attrs);
666 let body_ids = body_ids(&self.bodies);
670 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
676 exported_macros: hir::HirVec::from(self.exported_macros),
678 trait_items: self.trait_items,
679 impl_items: self.impl_items,
682 trait_impls: self.trait_impls,
683 modules: self.modules,
687 fn insert_item(&mut self, item: hir::Item) {
688 let id = item.hir_id;
689 // FIXME: Use debug_asset-rt
690 assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
691 self.items.insert(id, item);
692 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
695 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
696 // Setup the counter if needed
697 self.item_local_id_counters.entry(owner).or_insert(0);
698 // Always allocate the first `HirId` for the owner itself.
699 let lowered = self.lower_node_id_with_owner(owner, owner);
700 debug_assert_eq!(lowered.local_id.as_u32(), 0);
704 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> hir::HirId
706 F: FnOnce(&mut Self) -> hir::HirId,
708 if ast_node_id == DUMMY_NODE_ID {
709 return hir::DUMMY_HIR_ID;
712 let min_size = ast_node_id.as_usize() + 1;
714 if min_size > self.node_id_to_hir_id.len() {
715 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
718 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
720 if existing_hir_id == hir::DUMMY_HIR_ID {
721 // Generate a new `HirId`.
722 let hir_id = alloc_hir_id(self);
723 self.node_id_to_hir_id[ast_node_id] = hir_id;
731 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
733 F: FnOnce(&mut Self) -> T,
735 let counter = self.item_local_id_counters
736 .insert(owner, HIR_ID_COUNTER_LOCKED)
737 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
738 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
739 self.current_hir_id_owner.push((def_index, counter));
741 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
743 debug_assert!(def_index == new_def_index);
744 debug_assert!(new_counter >= counter);
746 let prev = self.item_local_id_counters
747 .insert(owner, new_counter)
749 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
753 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
754 /// the `LoweringContext`'s `NodeId => HirId` map.
755 /// Take care not to call this method if the resulting `HirId` is then not
756 /// actually used in the HIR, as that would trigger an assertion in the
757 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
758 /// properly. Calling the method twice with the same `NodeId` is fine though.
759 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
760 self.lower_node_id_generic(ast_node_id, |this| {
761 let &mut (def_index, ref mut local_id_counter) =
762 this.current_hir_id_owner.last_mut().unwrap();
763 let local_id = *local_id_counter;
764 *local_id_counter += 1;
767 local_id: hir::ItemLocalId::from_u32(local_id),
772 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
773 self.lower_node_id_generic(ast_node_id, |this| {
774 let local_id_counter = this
775 .item_local_id_counters
777 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
778 let local_id = *local_id_counter;
780 // We want to be sure not to modify the counter in the map while it
781 // is also on the stack. Otherwise we'll get lost updates when writing
782 // back from the stack to the map.
783 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
785 *local_id_counter += 1;
789 .opt_def_index(owner)
790 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
791 that do not belong to the current owner");
795 local_id: hir::ItemLocalId::from_u32(local_id),
800 fn record_body(&mut self, value: hir::Expr, arguments: HirVec<hir::Arg>) -> hir::BodyId {
801 let body = hir::Body {
802 is_generator: self.is_generator,
807 self.bodies.insert(id, body);
811 fn next_id(&mut self) -> hir::HirId {
812 self.lower_node_id(self.sess.next_node_id())
815 fn lower_def(&mut self, def: Def<NodeId>) -> Def {
817 self.lower_node_id_generic(id, |_| {
818 panic!("expected node_id to be lowered already for def {:#?}", def)
823 fn expect_full_def(&mut self, id: NodeId) -> Def<NodeId> {
824 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
825 if pr.unresolved_segments() != 0 {
826 bug!("path not fully resolved: {:?}", pr);
832 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Def<NodeId>> {
833 self.resolver.get_import(id).present_items().map(|pr| {
834 if pr.unresolved_segments() != 0 {
835 bug!("path not fully resolved: {:?}", pr);
841 fn diagnostic(&self) -> &errors::Handler {
842 self.sess.diagnostic()
845 fn str_to_ident(&self, s: &'static str) -> Ident {
846 Ident::with_empty_ctxt(Symbol::gensym(s))
849 /// Reuses the span but adds information like the kind of the desugaring and features that are
850 /// allowed inside this span.
851 fn mark_span_with_reason(
853 reason: CompilerDesugaringKind,
855 allow_internal_unstable: Option<Lrc<[Symbol]>>,
857 let mark = Mark::fresh(Mark::root());
858 mark.set_expn_info(source_map::ExpnInfo {
860 def_site: Some(span),
861 format: source_map::CompilerDesugaring(reason),
862 allow_internal_unstable,
863 allow_internal_unsafe: false,
864 local_inner_macros: false,
865 edition: source_map::hygiene::default_edition(),
867 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
870 fn with_anonymous_lifetime_mode<R>(
872 anonymous_lifetime_mode: AnonymousLifetimeMode,
873 op: impl FnOnce(&mut Self) -> R,
875 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
876 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
877 let result = op(self);
878 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
882 /// Creates a new hir::GenericParam for every new lifetime and
883 /// type parameter encountered while evaluating `f`. Definitions
884 /// are created with the parent provided. If no `parent_id` is
885 /// provided, no definitions will be returned.
887 /// Presuming that in-band lifetimes are enabled, then
888 /// `self.anonymous_lifetime_mode` will be updated to match the
889 /// argument while `f` is running (and restored afterwards).
890 fn collect_in_band_defs<T, F>(
893 anonymous_lifetime_mode: AnonymousLifetimeMode,
895 ) -> (Vec<hir::GenericParam>, T)
897 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
899 assert!(!self.is_collecting_in_band_lifetimes);
900 assert!(self.lifetimes_to_define.is_empty());
901 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
903 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
904 self.is_collecting_in_band_lifetimes = true;
906 let (in_band_ty_params, res) = f(self);
908 self.is_collecting_in_band_lifetimes = false;
909 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
911 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
913 let params = lifetimes_to_define
915 .map(|(span, hir_name)| self.lifetime_to_generic_param(
916 span, hir_name, parent_id.index,
918 .chain(in_band_ty_params.into_iter())
924 /// Converts a lifetime into a new generic parameter.
925 fn lifetime_to_generic_param(
929 parent_index: DefIndex,
930 ) -> hir::GenericParam {
931 let node_id = self.sess.next_node_id();
933 // Get the name we'll use to make the def-path. Note
934 // that collisions are ok here and this shouldn't
935 // really show up for end-user.
936 let (str_name, kind) = match hir_name {
937 ParamName::Plain(ident) => (
938 ident.as_interned_str(),
939 hir::LifetimeParamKind::InBand,
941 ParamName::Fresh(_) => (
942 keywords::UnderscoreLifetime.name().as_interned_str(),
943 hir::LifetimeParamKind::Elided,
945 ParamName::Error => (
946 keywords::UnderscoreLifetime.name().as_interned_str(),
947 hir::LifetimeParamKind::Error,
951 // Add a definition for the in-band lifetime def.
952 self.resolver.definitions().create_def_with_parent(
955 DefPathData::LifetimeParam(str_name),
956 DefIndexAddressSpace::High,
962 hir_id: self.lower_node_id(node_id),
967 pure_wrt_drop: false,
968 kind: hir::GenericParamKind::Lifetime { kind }
972 /// When there is a reference to some lifetime `'a`, and in-band
973 /// lifetimes are enabled, then we want to push that lifetime into
974 /// the vector of names to define later. In that case, it will get
975 /// added to the appropriate generics.
976 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
977 if !self.is_collecting_in_band_lifetimes {
981 if !self.sess.features_untracked().in_band_lifetimes {
985 if self.in_scope_lifetimes.contains(&ident.modern()) {
989 let hir_name = ParamName::Plain(ident);
991 if self.lifetimes_to_define.iter()
992 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
996 self.lifetimes_to_define.push((ident.span, hir_name));
999 /// When we have either an elided or `'_` lifetime in an impl
1000 /// header, we convert it to an in-band lifetime.
1001 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
1002 assert!(self.is_collecting_in_band_lifetimes);
1003 let index = self.lifetimes_to_define.len();
1004 let hir_name = ParamName::Fresh(index);
1005 self.lifetimes_to_define.push((span, hir_name));
1009 // Evaluates `f` with the lifetimes in `params` in-scope.
1010 // This is used to track which lifetimes have already been defined, and
1011 // which are new in-band lifetimes that need to have a definition created
1013 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
1015 F: FnOnce(&mut LoweringContext<'_>) -> T,
1017 let old_len = self.in_scope_lifetimes.len();
1018 let lt_def_names = params.iter().filter_map(|param| match param.kind {
1019 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
1022 self.in_scope_lifetimes.extend(lt_def_names);
1026 self.in_scope_lifetimes.truncate(old_len);
1030 // Same as the method above, but accepts `hir::GenericParam`s
1031 // instead of `ast::GenericParam`s.
1032 // This should only be used with generics that have already had their
1033 // in-band lifetimes added. In practice, this means that this function is
1034 // only used when lowering a child item of a trait or impl.
1035 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
1036 params: &HirVec<hir::GenericParam>,
1039 F: FnOnce(&mut LoweringContext<'_>) -> T,
1041 let old_len = self.in_scope_lifetimes.len();
1042 let lt_def_names = params.iter().filter_map(|param| match param.kind {
1043 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
1046 self.in_scope_lifetimes.extend(lt_def_names);
1050 self.in_scope_lifetimes.truncate(old_len);
1054 /// Appends in-band lifetime defs and argument-position `impl
1055 /// Trait` defs to the existing set of generics.
1057 /// Presuming that in-band lifetimes are enabled, then
1058 /// `self.anonymous_lifetime_mode` will be updated to match the
1059 /// argument while `f` is running (and restored afterwards).
1060 fn add_in_band_defs<F, T>(
1062 generics: &Generics,
1064 anonymous_lifetime_mode: AnonymousLifetimeMode,
1066 ) -> (hir::Generics, T)
1068 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
1070 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
1073 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
1074 let mut params = Vec::new();
1075 // Note: it is necessary to lower generics *before* calling `f`.
1076 // When lowering `async fn`, there's a final step when lowering
1077 // the return type that assumes that all in-scope lifetimes have
1078 // already been added to either `in_scope_lifetimes` or
1079 // `lifetimes_to_define`. If we swapped the order of these two,
1080 // in-band-lifetimes introduced by generics or where-clauses
1081 // wouldn't have been added yet.
1082 let generics = this.lower_generics(
1084 ImplTraitContext::Universal(&mut params),
1086 let res = f(this, &mut params);
1087 (params, (generics, res))
1092 lowered_generics.params = lowered_generics
1096 .chain(in_band_defs)
1099 (lowered_generics, res)
1102 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
1104 F: FnOnce(&mut LoweringContext<'_>) -> T,
1106 let len = self.catch_scopes.len();
1107 self.catch_scopes.push(catch_id);
1109 let result = f(self);
1112 self.catch_scopes.len(),
1113 "catch scopes should be added and removed in stack order"
1116 self.catch_scopes.pop().unwrap();
1123 capture_clause: CaptureBy,
1124 closure_node_id: NodeId,
1125 ret_ty: Option<&Ty>,
1127 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1128 ) -> hir::ExprKind {
1129 let prev_is_generator = mem::replace(&mut self.is_generator, 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_def` 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;
1146 let capture_clause = self.lower_capture_clause(capture_clause);
1147 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
1148 let generator = hir::Expr {
1149 hir_id: self.lower_node_id(closure_node_id),
1150 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
1151 Some(hir::GeneratorMovability::Static)),
1153 attrs: ThinVec::new(),
1156 let unstable_span = self.mark_span_with_reason(
1157 CompilerDesugaringKind::Async,
1160 Symbol::intern("gen_future"),
1163 let gen_future = self.expr_std_path(
1164 unstable_span, &["future", "from_generator"], None, ThinVec::new());
1165 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
1168 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
1170 F: FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1172 let prev = mem::replace(&mut self.is_generator, 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;
1180 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
1182 F: FnOnce(&mut LoweringContext<'_>) -> T,
1184 // We're no longer in the base loop's condition; we're in another loop.
1185 let was_in_loop_condition = self.is_in_loop_condition;
1186 self.is_in_loop_condition = false;
1188 let len = self.loop_scopes.len();
1189 self.loop_scopes.push(loop_id);
1191 let result = f(self);
1194 self.loop_scopes.len(),
1195 "Loop scopes should be added and removed in stack order"
1198 self.loop_scopes.pop().unwrap();
1200 self.is_in_loop_condition = was_in_loop_condition;
1205 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
1207 F: FnOnce(&mut LoweringContext<'_>) -> T,
1209 let was_in_loop_condition = self.is_in_loop_condition;
1210 self.is_in_loop_condition = true;
1212 let result = f(self);
1214 self.is_in_loop_condition = was_in_loop_condition;
1219 fn with_new_scopes<T, F>(&mut self, f: F) -> T
1221 F: FnOnce(&mut LoweringContext<'_>) -> T,
1223 let was_in_loop_condition = self.is_in_loop_condition;
1224 self.is_in_loop_condition = false;
1226 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
1227 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
1229 self.catch_scopes = catch_scopes;
1230 self.loop_scopes = loop_scopes;
1232 self.is_in_loop_condition = was_in_loop_condition;
1237 fn def_key(&mut self, id: DefId) -> DefKey {
1239 self.resolver.definitions().def_key(id.index)
1241 self.cstore.def_key(id)
1245 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1246 label.map(|label| hir::Label {
1251 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1252 let target_id = match destination {
1254 if let Def::Label(loop_id) = self.expect_full_def(id) {
1255 Ok(self.lower_node_id(loop_id))
1257 Err(hir::LoopIdError::UnresolvedLabel)
1264 .map(|id| Ok(self.lower_node_id(id)))
1265 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1270 label: self.lower_label(destination.map(|(_, label)| label)),
1275 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1278 .map(|a| self.lower_attr(a))
1282 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1283 // Note that we explicitly do not walk the path. Since we don't really
1284 // lower attributes (we use the AST version) there is nowhere to keep
1285 // the `HirId`s. We don't actually need HIR version of attributes anyway.
1289 path: attr.path.clone(),
1290 tokens: self.lower_token_stream(attr.tokens.clone()),
1291 is_sugared_doc: attr.is_sugared_doc,
1296 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1299 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1303 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1305 TokenTree::Token(span, token) => self.lower_token(token, span),
1306 TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1309 self.lower_token_stream(tts),
1314 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1316 Token::Interpolated(nt) => {
1317 let tts = nt.to_tokenstream(&self.sess.parse_sess, span);
1318 self.lower_token_stream(tts)
1320 other => TokenTree::Token(span, other).into(),
1324 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1326 attrs: self.lower_attrs(&arm.attrs),
1327 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1328 guard: match arm.guard {
1329 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1332 body: P(self.lower_expr(&arm.body)),
1336 fn lower_ty_binding(&mut self, b: &TypeBinding,
1337 itctx: ImplTraitContext<'_>) -> hir::TypeBinding {
1339 hir_id: self.lower_node_id(b.id),
1341 ty: self.lower_ty(&b.ty, itctx),
1346 fn lower_generic_arg(&mut self,
1347 arg: &ast::GenericArg,
1348 itctx: ImplTraitContext<'_>)
1349 -> hir::GenericArg {
1351 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1352 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1353 ast::GenericArg::Const(ct) => {
1354 GenericArg::Const(ConstArg {
1355 value: self.lower_anon_const(&ct),
1356 span: ct.value.span,
1362 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1363 P(self.lower_ty_direct(t, itctx))
1366 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1367 let kind = match t.node {
1368 TyKind::Infer => hir::TyKind::Infer,
1369 TyKind::Err => hir::TyKind::Err,
1370 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1371 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1372 TyKind::Rptr(ref region, ref mt) => {
1373 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1374 let lifetime = match *region {
1375 Some(ref lt) => self.lower_lifetime(lt),
1376 None => self.elided_ref_lifetime(span),
1378 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1380 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1383 this.with_anonymous_lifetime_mode(
1384 AnonymousLifetimeMode::PassThrough,
1386 hir::TyKind::BareFn(P(hir::BareFnTy {
1387 generic_params: this.lower_generic_params(
1389 &NodeMap::default(),
1390 ImplTraitContext::disallowed(),
1392 unsafety: this.lower_unsafety(f.unsafety),
1394 decl: this.lower_fn_decl(&f.decl, None, false, None),
1395 arg_names: this.lower_fn_args_to_names(&f.decl),
1401 TyKind::Never => hir::TyKind::Never,
1402 TyKind::Tup(ref tys) => {
1403 hir::TyKind::Tup(tys.iter().map(|ty| {
1404 self.lower_ty_direct(ty, itctx.reborrow())
1407 TyKind::Paren(ref ty) => {
1408 return self.lower_ty_direct(ty, itctx);
1410 TyKind::Path(ref qself, ref path) => {
1411 let id = self.lower_node_id(t.id);
1412 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1413 let ty = self.ty_path(id, t.span, qpath);
1414 if let hir::TyKind::TraitObject(..) = ty.node {
1415 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1419 TyKind::ImplicitSelf => {
1420 let def = self.expect_full_def(t.id);
1421 let def = self.lower_def(def);
1422 hir::TyKind::Path(hir::QPath::Resolved(
1426 segments: hir_vec![hir::PathSegment::from_ident(
1427 keywords::SelfUpper.ident()
1433 TyKind::Array(ref ty, ref length) => {
1434 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1436 TyKind::Typeof(ref expr) => {
1437 hir::TyKind::Typeof(self.lower_anon_const(expr))
1439 TyKind::TraitObject(ref bounds, kind) => {
1440 let mut lifetime_bound = None;
1443 .filter_map(|bound| match *bound {
1444 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1445 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1447 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1448 GenericBound::Outlives(ref lifetime) => {
1449 if lifetime_bound.is_none() {
1450 lifetime_bound = Some(self.lower_lifetime(lifetime));
1456 let lifetime_bound =
1457 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1458 if kind != TraitObjectSyntax::Dyn {
1459 self.maybe_lint_bare_trait(t.span, t.id, false);
1461 hir::TyKind::TraitObject(bounds, lifetime_bound)
1463 TyKind::ImplTrait(def_node_id, ref bounds) => {
1466 ImplTraitContext::Existential(fn_def_id) => {
1467 self.lower_existential_impl_trait(
1468 span, fn_def_id, def_node_id,
1469 |this| this.lower_param_bounds(bounds, itctx),
1472 ImplTraitContext::Universal(in_band_ty_params) => {
1473 // Add a definition for the in-band `Param`.
1474 let def_index = self
1477 .opt_def_index(def_node_id)
1480 let hir_bounds = self.lower_param_bounds(
1482 ImplTraitContext::Universal(in_band_ty_params),
1484 // Set the name to `impl Bound1 + Bound2`.
1485 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1486 in_band_ty_params.push(hir::GenericParam {
1487 hir_id: self.lower_node_id(def_node_id),
1488 name: ParamName::Plain(ident),
1489 pure_wrt_drop: false,
1493 kind: hir::GenericParamKind::Type {
1495 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1499 hir::TyKind::Path(hir::QPath::Resolved(
1503 def: Def::TyParam(DefId::local(def_index)),
1504 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1508 ImplTraitContext::Disallowed(pos) => {
1509 let allowed_in = if self.sess.features_untracked()
1510 .impl_trait_in_bindings {
1511 "bindings or function and inherent method return types"
1513 "function and inherent method return types"
1515 let mut err = struct_span_err!(
1519 "`impl Trait` not allowed outside of {}",
1522 if pos == ImplTraitPosition::Binding &&
1523 nightly_options::is_nightly_build() {
1525 "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1533 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1534 TyKind::CVarArgs => {
1535 // Create the implicit lifetime of the "spoofed" `VaList`.
1536 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1537 let lt = self.new_implicit_lifetime(span);
1538 hir::TyKind::CVarArgs(lt)
1545 hir_id: self.lower_node_id(t.id),
1549 fn lower_existential_impl_trait(
1552 fn_def_id: Option<DefId>,
1553 exist_ty_node_id: NodeId,
1554 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1556 // Make sure we know that some funky desugaring has been going on here.
1557 // This is a first: there is code in other places like for loop
1558 // desugaring that explicitly states that we don't want to track that.
1559 // Not tracking it makes lints in rustc and clippy very fragile as
1560 // frequently opened issues show.
1561 let exist_ty_span = self.mark_span_with_reason(
1562 CompilerDesugaringKind::ExistentialReturnType,
1567 let exist_ty_def_index = self
1570 .opt_def_index(exist_ty_node_id)
1573 self.allocate_hir_id_counter(exist_ty_node_id);
1575 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1577 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1583 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1584 let exist_ty_item = hir::ExistTy {
1585 generics: hir::Generics {
1586 params: lifetime_defs,
1587 where_clause: hir::WhereClause {
1588 hir_id: lctx.next_id(),
1589 predicates: hir_vec![],
1594 impl_trait_fn: fn_def_id,
1595 origin: hir::ExistTyOrigin::ReturnImplTrait,
1598 trace!("exist ty from impl trait def index: {:#?}", exist_ty_def_index);
1599 let exist_ty_id = lctx.generate_existential_type(
1606 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1607 hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, lifetimes)
1611 /// Registers a new existential type with the proper NodeIds and
1612 /// returns the lowered node ID for the existential type.
1613 fn generate_existential_type(
1615 exist_ty_node_id: NodeId,
1616 exist_ty_item: hir::ExistTy,
1618 exist_ty_span: Span,
1620 let exist_ty_item_kind = hir::ItemKind::Existential(exist_ty_item);
1621 let exist_ty_id = self.lower_node_id(exist_ty_node_id);
1622 // Generate an `existential type Foo: Trait;` declaration.
1623 trace!("registering existential type with id {:#?}", exist_ty_id);
1624 let exist_ty_item = hir::Item {
1625 hir_id: exist_ty_id,
1626 ident: keywords::Invalid.ident(),
1627 attrs: Default::default(),
1628 node: exist_ty_item_kind,
1629 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1630 span: exist_ty_span,
1633 // Insert the item into the global item list. This usually happens
1634 // automatically for all AST items. But this existential type item
1635 // does not actually exist in the AST.
1636 self.insert_item(exist_ty_item);
1640 fn lifetimes_from_impl_trait_bounds(
1642 exist_ty_id: NodeId,
1643 parent_index: DefIndex,
1644 bounds: &hir::GenericBounds,
1645 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1646 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1647 // appear in the bounds, excluding lifetimes that are created within the bounds.
1648 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1649 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1650 context: &'r mut LoweringContext<'a>,
1652 exist_ty_id: NodeId,
1653 collect_elided_lifetimes: bool,
1654 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1655 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1656 output_lifetimes: Vec<hir::GenericArg>,
1657 output_lifetime_params: Vec<hir::GenericParam>,
1660 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1661 fn nested_visit_map<'this>(
1663 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1664 hir::intravisit::NestedVisitorMap::None
1667 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1668 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1669 if parameters.parenthesized {
1670 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1671 self.collect_elided_lifetimes = false;
1672 hir::intravisit::walk_generic_args(self, span, parameters);
1673 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1675 hir::intravisit::walk_generic_args(self, span, parameters);
1679 fn visit_ty(&mut self, t: &'v hir::Ty) {
1680 // Don't collect elided lifetimes used inside of `fn()` syntax.
1681 if let hir::TyKind::BareFn(_) = t.node {
1682 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1683 self.collect_elided_lifetimes = false;
1685 // Record the "stack height" of `for<'a>` lifetime bindings
1686 // to be able to later fully undo their introduction.
1687 let old_len = self.currently_bound_lifetimes.len();
1688 hir::intravisit::walk_ty(self, t);
1689 self.currently_bound_lifetimes.truncate(old_len);
1691 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1693 hir::intravisit::walk_ty(self, t)
1697 fn visit_poly_trait_ref(
1699 trait_ref: &'v hir::PolyTraitRef,
1700 modifier: hir::TraitBoundModifier,
1702 // Record the "stack height" of `for<'a>` lifetime bindings
1703 // to be able to later fully undo their introduction.
1704 let old_len = self.currently_bound_lifetimes.len();
1705 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1706 self.currently_bound_lifetimes.truncate(old_len);
1709 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1710 // Record the introduction of 'a in `for<'a> ...`.
1711 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1712 // Introduce lifetimes one at a time so that we can handle
1713 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1714 let lt_name = hir::LifetimeName::Param(param.name);
1715 self.currently_bound_lifetimes.push(lt_name);
1718 hir::intravisit::walk_generic_param(self, param);
1721 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1722 let name = match lifetime.name {
1723 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1724 if self.collect_elided_lifetimes {
1725 // Use `'_` for both implicit and underscore lifetimes in
1726 // `abstract type Foo<'_>: SomeTrait<'_>;`.
1727 hir::LifetimeName::Underscore
1732 hir::LifetimeName::Param(_) => lifetime.name,
1733 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1736 if !self.currently_bound_lifetimes.contains(&name)
1737 && !self.already_defined_lifetimes.contains(&name) {
1738 self.already_defined_lifetimes.insert(name);
1740 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1741 hir_id: self.context.next_id(),
1742 span: lifetime.span,
1746 let def_node_id = self.context.sess.next_node_id();
1748 self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1749 self.context.resolver.definitions().create_def_with_parent(
1752 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1753 DefIndexAddressSpace::High,
1758 let (name, kind) = match name {
1759 hir::LifetimeName::Underscore => (
1760 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident()),
1761 hir::LifetimeParamKind::Elided,
1763 hir::LifetimeName::Param(param_name) => (
1765 hir::LifetimeParamKind::Explicit,
1767 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1770 self.output_lifetime_params.push(hir::GenericParam {
1773 span: lifetime.span,
1774 pure_wrt_drop: false,
1777 kind: hir::GenericParamKind::Lifetime { kind }
1783 let mut lifetime_collector = ImplTraitLifetimeCollector {
1785 parent: parent_index,
1787 collect_elided_lifetimes: true,
1788 currently_bound_lifetimes: Vec::new(),
1789 already_defined_lifetimes: FxHashSet::default(),
1790 output_lifetimes: Vec::new(),
1791 output_lifetime_params: Vec::new(),
1794 for bound in bounds {
1795 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1799 lifetime_collector.output_lifetimes.into(),
1800 lifetime_collector.output_lifetime_params.into(),
1804 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1809 .map(|x| self.lower_foreign_item(x))
1814 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1821 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1823 node: hir::VariantKind {
1824 ident: v.node.ident,
1825 id: self.lower_node_id(v.node.id),
1826 attrs: self.lower_attrs(&v.node.attrs),
1827 data: self.lower_variant_data(&v.node.data),
1828 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1837 qself: &Option<QSelf>,
1839 param_mode: ParamMode,
1840 mut itctx: ImplTraitContext<'_>,
1842 let qself_position = qself.as_ref().map(|q| q.position);
1843 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1845 let resolution = self.resolver
1847 .unwrap_or_else(|| PathResolution::new(Def::Err));
1849 let proj_start = p.segments.len() - resolution.unresolved_segments();
1850 let path = P(hir::Path {
1851 def: self.lower_def(resolution.base_def()),
1852 segments: p.segments[..proj_start]
1855 .map(|(i, segment)| {
1856 let param_mode = match (qself_position, param_mode) {
1857 (Some(j), ParamMode::Optional) if i < j => {
1858 // This segment is part of the trait path in a
1859 // qualified path - one of `a`, `b` or `Trait`
1860 // in `<X as a::b::Trait>::T::U::method`.
1866 // Figure out if this is a type/trait segment,
1867 // which may need lifetime elision performed.
1868 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1869 krate: def_id.krate,
1870 index: this.def_key(def_id).parent.expect("missing parent"),
1872 let type_def_id = match resolution.base_def() {
1873 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1874 Some(parent_def_id(self, def_id))
1876 Def::Variant(def_id) if i + 1 == proj_start => {
1877 Some(parent_def_id(self, def_id))
1880 | Def::Union(def_id)
1882 | Def::TyAlias(def_id)
1883 | Def::Trait(def_id) if i + 1 == proj_start =>
1889 let parenthesized_generic_args = match resolution.base_def() {
1890 // `a::b::Trait(Args)`
1891 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1892 // `a::b::Trait(Args)::TraitItem`
1893 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1894 if i + 2 == proj_start =>
1896 ParenthesizedGenericArgs::Ok
1898 // Avoid duplicated errors.
1899 Def::Err => ParenthesizedGenericArgs::Ok,
1905 | Def::Variant(..) if i + 1 == proj_start =>
1907 ParenthesizedGenericArgs::Err
1909 // A warning for now, for compatibility reasons
1910 _ => ParenthesizedGenericArgs::Warn,
1913 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1914 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1917 assert!(!def_id.is_local());
1919 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1920 let n = item_generics.own_counts().lifetimes;
1921 self.type_def_lifetime_params.insert(def_id, n);
1924 self.lower_path_segment(
1929 parenthesized_generic_args,
1938 // Simple case, either no projections, or only fully-qualified.
1939 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
1940 if resolution.unresolved_segments() == 0 {
1941 return hir::QPath::Resolved(qself, path);
1944 // Create the innermost type that we're projecting from.
1945 let mut ty = if path.segments.is_empty() {
1946 // If the base path is empty that means there exists a
1947 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
1948 qself.expect("missing QSelf for <T>::...")
1950 // Otherwise, the base path is an implicit `Self` type path,
1951 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1952 // `<I as Iterator>::Item::default`.
1953 let new_id = self.next_id();
1954 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1957 // Anything after the base path are associated "extensions",
1958 // out of which all but the last one are associated types,
1959 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1960 // * base path is `std::vec::Vec<T>`
1961 // * "extensions" are `IntoIter`, `Item` and `clone`
1962 // * type nodes are:
1963 // 1. `std::vec::Vec<T>` (created above)
1964 // 2. `<std::vec::Vec<T>>::IntoIter`
1965 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1966 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1967 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1968 let segment = P(self.lower_path_segment(
1973 ParenthesizedGenericArgs::Warn,
1977 let qpath = hir::QPath::TypeRelative(ty, segment);
1979 // It's finished, return the extension of the right node type.
1980 if i == p.segments.len() - 1 {
1984 // Wrap the associated extension in another type node.
1985 let new_id = self.next_id();
1986 ty = P(self.ty_path(new_id, p.span, qpath));
1989 // We should've returned in the for loop above.
1992 "lower_qpath: no final extension segment in {}..{}",
1998 fn lower_path_extra(
2002 param_mode: ParamMode,
2003 explicit_owner: Option<NodeId>,
2007 segments: p.segments
2010 self.lower_path_segment(
2015 ParenthesizedGenericArgs::Err,
2016 ImplTraitContext::disallowed(),
2025 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
2026 let def = self.expect_full_def(id);
2027 let def = self.lower_def(def);
2028 self.lower_path_extra(def, p, param_mode, None)
2031 fn lower_path_segment(
2034 segment: &PathSegment,
2035 param_mode: ParamMode,
2036 expected_lifetimes: usize,
2037 parenthesized_generic_args: ParenthesizedGenericArgs,
2038 itctx: ImplTraitContext<'_>,
2039 explicit_owner: Option<NodeId>,
2040 ) -> hir::PathSegment {
2041 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
2042 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
2043 match **generic_args {
2044 GenericArgs::AngleBracketed(ref data) => {
2045 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
2047 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
2048 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
2049 ParenthesizedGenericArgs::Warn => {
2050 self.sess.buffer_lint(
2051 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
2056 (hir::GenericArgs::none(), true)
2058 ParenthesizedGenericArgs::Err => {
2059 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
2060 err.span_label(data.span, "only `Fn` traits may use parentheses");
2061 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
2062 // Do not suggest going from `Trait()` to `Trait<>`
2063 if data.inputs.len() > 0 {
2064 err.span_suggestion(
2066 "use angle brackets instead",
2067 format!("<{}>", &snippet[1..snippet.len() - 1]),
2068 Applicability::MaybeIncorrect,
2073 (self.lower_angle_bracketed_parameter_data(
2074 &data.as_angle_bracketed_args(),
2082 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
2085 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
2086 GenericArg::Lifetime(_) => true,
2089 let first_generic_span = generic_args.args.iter().map(|a| a.span())
2090 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
2091 if !generic_args.parenthesized && !has_lifetimes {
2093 self.elided_path_lifetimes(path_span, expected_lifetimes)
2095 .map(|lt| GenericArg::Lifetime(lt))
2096 .chain(generic_args.args.into_iter())
2098 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
2099 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
2100 let no_ty_args = generic_args.args.len() == expected_lifetimes;
2101 let no_bindings = generic_args.bindings.is_empty();
2102 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
2103 // If there are no (non-implicit) generic args or associated-type
2104 // bindings, our suggestion includes the angle brackets.
2105 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
2107 // Otherwise—sorry, this is kind of gross—we need to infer the
2108 // place to splice in the `'_, ` from the generics that do exist.
2109 let first_generic_span = first_generic_span
2110 .expect("already checked that type args or bindings exist");
2111 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
2113 self.sess.buffer_lint_with_diagnostic(
2114 ELIDED_LIFETIMES_IN_PATHS,
2117 "hidden lifetime parameters in types are deprecated",
2118 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
2119 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
2125 let def = self.expect_full_def(segment.id);
2126 let id = if let Some(owner) = explicit_owner {
2127 self.lower_node_id_with_owner(segment.id, owner)
2129 self.lower_node_id(segment.id)
2132 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
2133 segment.ident, segment.id, id,
2136 hir::PathSegment::new(
2139 Some(self.lower_def(def)),
2145 fn lower_angle_bracketed_parameter_data(
2147 data: &AngleBracketedArgs,
2148 param_mode: ParamMode,
2149 mut itctx: ImplTraitContext<'_>,
2150 ) -> (hir::GenericArgs, bool) {
2151 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
2152 let has_types = args.iter().any(|arg| match arg {
2153 ast::GenericArg::Type(_) => true,
2157 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
2158 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
2159 parenthesized: false,
2161 !has_types && param_mode == ParamMode::Optional)
2164 fn lower_parenthesized_parameter_data(
2166 data: &ParenthesizedArgs,
2167 ) -> (hir::GenericArgs, bool) {
2168 // Switch to `PassThrough` mode for anonymous lifetimes: this
2169 // means that we permit things like `&Ref<T>`, where `Ref` has
2170 // a hidden lifetime parameter. This is needed for backwards
2171 // compatibility, even in contexts like an impl header where
2172 // we generally don't permit such things (see #51008).
2173 self.with_anonymous_lifetime_mode(
2174 AnonymousLifetimeMode::PassThrough,
2176 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2179 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
2181 let mk_tup = |this: &mut Self, tys, span| {
2182 hir::Ty { node: hir::TyKind::Tup(tys), hir_id: this.next_id(), span }
2186 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
2189 hir_id: this.next_id(),
2190 ident: Ident::from_str(FN_OUTPUT_NAME),
2193 .map(|ty| this.lower_ty(&ty, ImplTraitContext::disallowed()))
2194 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
2195 span: output.as_ref().map_or(span, |ty| ty.span),
2198 parenthesized: true,
2206 fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) {
2207 let mut ids = SmallVec::<[NodeId; 1]>::new();
2208 if self.sess.features_untracked().impl_trait_in_bindings {
2209 if let Some(ref ty) = l.ty {
2210 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2211 visitor.visit_ty(ty);
2214 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2216 hir_id: self.lower_node_id(l.id),
2219 .map(|t| self.lower_ty(t,
2220 if self.sess.features_untracked().impl_trait_in_bindings {
2221 ImplTraitContext::Existential(Some(parent_def_id))
2223 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2226 pat: self.lower_pat(&l.pat),
2227 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2229 attrs: l.attrs.clone(),
2230 source: self.lower_local_source(l.source),
2234 fn lower_local_source(&mut self, ls: LocalSource) -> hir::LocalSource {
2236 LocalSource::Normal => hir::LocalSource::Normal,
2237 LocalSource::AsyncFn => hir::LocalSource::AsyncFn,
2241 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
2243 Mutability::Mutable => hir::MutMutable,
2244 Mutability::Immutable => hir::MutImmutable,
2248 fn lower_args(&mut self, decl: Option<&FnDecl>) -> HirVec<hir::Arg> {
2249 decl.map_or(hir_vec![], |decl| decl.inputs.iter().map(|x| self.lower_arg(x)).collect())
2252 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
2254 hir_id: self.lower_node_id(arg.id),
2255 pat: self.lower_pat(&arg.pat),
2256 source: self.lower_arg_source(&arg.source),
2260 fn lower_arg_source(&mut self, source: &ArgSource) -> hir::ArgSource {
2262 ArgSource::Normal => hir::ArgSource::Normal,
2263 ArgSource::AsyncFn(pat) => hir::ArgSource::AsyncFn(self.lower_pat(pat)),
2267 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2270 .map(|arg| match arg.pat.node {
2271 PatKind::Ident(_, ident, _) => ident,
2272 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
2277 // Lowers a function declaration.
2279 // decl: the unlowered (ast) function declaration.
2280 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
2281 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2282 // make_ret_async is also `Some`.
2283 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
2284 // This guards against trait declarations and implementations where impl Trait is
2286 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2287 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
2288 // return type impl Trait item.
2292 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2293 impl_trait_return_allow: bool,
2294 make_ret_async: Option<NodeId>,
2295 ) -> P<hir::FnDecl> {
2296 let lt_mode = if make_ret_async.is_some() {
2297 // In `async fn`, argument-position elided lifetimes
2298 // must be transformed into fresh generic parameters so that
2299 // they can be applied to the existential return type.
2300 AnonymousLifetimeMode::CreateParameter
2302 self.anonymous_lifetime_mode
2305 // Remember how many lifetimes were already around so that we can
2306 // only look at the lifetime parameters introduced by the arguments.
2307 let lifetime_count_before_args = self.lifetimes_to_define.len();
2308 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2312 if let Some((_, ibty)) = &mut in_band_ty_params {
2313 this.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2315 this.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2318 .collect::<HirVec<_>>()
2321 let output = if let Some(ret_id) = make_ret_async {
2322 // Calculate the `LtReplacement` to use for any return-position elided
2323 // lifetimes based on the elided lifetime parameters introduced in the args.
2324 let lt_replacement = get_elided_lt_replacement(
2325 &self.lifetimes_to_define[lifetime_count_before_args..]
2327 self.lower_async_fn_ret_ty(
2329 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
2335 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2336 Some((def_id, _)) if impl_trait_return_allow => {
2337 hir::Return(self.lower_ty(ty,
2338 ImplTraitContext::Existential(Some(def_id))))
2341 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2344 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2351 c_variadic: decl.c_variadic,
2352 implicit_self: decl.inputs.get(0).map_or(
2353 hir::ImplicitSelfKind::None,
2355 let is_mutable_pat = match arg.pat.node {
2356 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2357 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2358 mt == Mutability::Mutable,
2363 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2364 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2365 // Given we are only considering `ImplicitSelf` types, we needn't consider
2366 // the case where we have a mutable pattern to a reference as that would
2367 // no longer be an `ImplicitSelf`.
2368 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2369 mt.mutbl == ast::Mutability::Mutable =>
2370 hir::ImplicitSelfKind::MutRef,
2371 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2372 hir::ImplicitSelfKind::ImmRef,
2373 _ => hir::ImplicitSelfKind::None,
2380 // Transform `-> T` for `async fn` into -> ExistTy { .. }
2381 // combined with the following definition of `ExistTy`:
2383 // existential type ExistTy<generics_from_parent_fn>: Future<Output = T>;
2385 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
2386 // output: unlowered output type (`T` in `-> T`)
2387 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
2388 // exist_ty_node_id: NodeId of the existential type that should be created.
2389 // elided_lt_replacement: replacement for elided lifetimes in the return type
2390 fn lower_async_fn_ret_ty(
2392 output: &FunctionRetTy,
2394 exist_ty_node_id: NodeId,
2395 elided_lt_replacement: LtReplacement,
2396 ) -> hir::FunctionRetTy {
2397 let span = output.span();
2399 let exist_ty_span = self.mark_span_with_reason(
2400 CompilerDesugaringKind::Async,
2405 let exist_ty_def_index = self
2408 .opt_def_index(exist_ty_node_id)
2411 self.allocate_hir_id_counter(exist_ty_node_id);
2413 let (exist_ty_id, lifetime_params) = self.with_hir_id_owner(exist_ty_node_id, |this| {
2414 let future_bound = this.with_anonymous_lifetime_mode(
2415 AnonymousLifetimeMode::Replace(elided_lt_replacement),
2416 |this| this.lower_async_fn_output_type_to_future_bound(
2423 // Calculate all the lifetimes that should be captured
2424 // by the existential type. This should include all in-scope
2425 // lifetime parameters, including those defined in-band.
2427 // Note: this must be done after lowering the output type,
2428 // as the output type may introduce new in-band lifetimes.
2429 let lifetime_params: Vec<(Span, ParamName)> =
2430 this.in_scope_lifetimes
2432 .map(|ident| (ident.span, ParamName::Plain(ident)))
2433 .chain(this.lifetimes_to_define.iter().cloned())
2436 let generic_params =
2439 .map(|(span, hir_name)| {
2440 this.lifetime_to_generic_param(span, hir_name, exist_ty_def_index)
2444 let exist_ty_item = hir::ExistTy {
2445 generics: hir::Generics {
2446 params: generic_params,
2447 where_clause: hir::WhereClause {
2448 hir_id: this.next_id(),
2449 predicates: hir_vec![],
2453 bounds: hir_vec![future_bound],
2454 impl_trait_fn: Some(fn_def_id),
2455 origin: hir::ExistTyOrigin::AsyncFn,
2458 trace!("exist ty from async fn def index: {:#?}", exist_ty_def_index);
2459 let exist_ty_id = this.generate_existential_type(
2466 (exist_ty_id, lifetime_params)
2472 .map(|(span, hir_name)| {
2473 GenericArg::Lifetime(hir::Lifetime {
2474 hir_id: self.next_id(),
2476 name: hir::LifetimeName::Param(hir_name),
2481 let exist_ty_ref = hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, generic_args);
2483 hir::FunctionRetTy::Return(P(hir::Ty {
2486 hir_id: self.next_id(),
2490 /// Turns `-> T` into `Future<Output = T>`
2491 fn lower_async_fn_output_type_to_future_bound(
2493 output: &FunctionRetTy,
2496 ) -> hir::GenericBound {
2497 // Compute the `T` in `Future<Output = T>` from the return type.
2498 let output_ty = match output {
2499 FunctionRetTy::Ty(ty) => {
2500 self.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2502 FunctionRetTy::Default(ret_ty_span) => {
2504 hir_id: self.next_id(),
2505 node: hir::TyKind::Tup(hir_vec![]),
2512 let future_params = P(hir::GenericArgs {
2514 bindings: hir_vec![hir::TypeBinding {
2515 ident: Ident::from_str(FN_OUTPUT_NAME),
2517 hir_id: self.next_id(),
2520 parenthesized: false,
2523 // ::std::future::Future<future_params>
2525 self.std_path(span, &["future", "Future"], Some(future_params), false);
2527 hir::GenericBound::Trait(
2529 trait_ref: hir::TraitRef {
2531 hir_ref_id: self.next_id(),
2533 bound_generic_params: hir_vec![],
2536 hir::TraitBoundModifier::None,
2540 fn lower_param_bound(
2543 itctx: ImplTraitContext<'_>,
2544 ) -> hir::GenericBound {
2546 GenericBound::Trait(ref ty, modifier) => {
2547 hir::GenericBound::Trait(
2548 self.lower_poly_trait_ref(ty, itctx),
2549 self.lower_trait_bound_modifier(modifier),
2552 GenericBound::Outlives(ref lifetime) => {
2553 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2558 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2559 let span = l.ident.span;
2561 ident if ident.name == keywords::StaticLifetime.name() =>
2562 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2563 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2564 match self.anonymous_lifetime_mode {
2565 AnonymousLifetimeMode::CreateParameter => {
2566 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2567 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2570 AnonymousLifetimeMode::PassThrough => {
2571 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2574 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2576 AnonymousLifetimeMode::Replace(replacement) => {
2577 let hir_id = self.lower_node_id(l.id);
2578 self.replace_elided_lifetime(hir_id, span, replacement)
2582 self.maybe_collect_in_band_lifetime(ident);
2583 let param_name = ParamName::Plain(ident);
2584 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2589 fn new_named_lifetime(
2593 name: hir::LifetimeName,
2594 ) -> hir::Lifetime {
2596 hir_id: self.lower_node_id(id),
2602 /// Replace a return-position elided lifetime with the elided lifetime
2603 /// from the arguments.
2604 fn replace_elided_lifetime(
2608 replacement: LtReplacement,
2609 ) -> hir::Lifetime {
2610 let multiple_or_none = match replacement {
2611 LtReplacement::Some(name) => {
2612 return hir::Lifetime {
2615 name: hir::LifetimeName::Param(name),
2618 LtReplacement::MultipleLifetimes => "multiple",
2619 LtReplacement::NoLifetimes => "none",
2622 let mut err = crate::middle::resolve_lifetime::report_missing_lifetime_specifiers(
2628 "return-position elided lifetimes require exactly one \
2629 input-position elided lifetime, found {}.", multiple_or_none));
2632 hir::Lifetime { hir_id, span, name: hir::LifetimeName::Error }
2635 fn lower_generic_params(
2637 params: &[GenericParam],
2638 add_bounds: &NodeMap<Vec<GenericBound>>,
2639 mut itctx: ImplTraitContext<'_>,
2640 ) -> hir::HirVec<hir::GenericParam> {
2641 params.iter().map(|param| {
2642 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2646 fn lower_generic_param(&mut self,
2647 param: &GenericParam,
2648 add_bounds: &NodeMap<Vec<GenericBound>>,
2649 mut itctx: ImplTraitContext<'_>)
2650 -> hir::GenericParam {
2651 let mut bounds = self.with_anonymous_lifetime_mode(
2652 AnonymousLifetimeMode::ReportError,
2653 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2656 let (name, kind) = match param.kind {
2657 GenericParamKind::Lifetime => {
2658 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2659 self.is_collecting_in_band_lifetimes = false;
2661 let lt = self.with_anonymous_lifetime_mode(
2662 AnonymousLifetimeMode::ReportError,
2663 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2665 let param_name = match lt.name {
2666 hir::LifetimeName::Param(param_name) => param_name,
2667 hir::LifetimeName::Implicit
2668 | hir::LifetimeName::Underscore
2669 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2670 hir::LifetimeName::Error => ParamName::Error,
2673 let kind = hir::GenericParamKind::Lifetime {
2674 kind: hir::LifetimeParamKind::Explicit
2677 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2681 GenericParamKind::Type { ref default, .. } => {
2682 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2683 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2684 // Instead, use `gensym("Self")` to create a distinct name that looks the same.
2685 let ident = if param.ident.name == keywords::SelfUpper.name() {
2686 param.ident.gensym()
2691 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2692 if !add_bounds.is_empty() {
2693 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2694 bounds = bounds.into_iter()
2699 let kind = hir::GenericParamKind::Type {
2700 default: default.as_ref().map(|x| {
2701 self.lower_ty(x, ImplTraitContext::disallowed())
2703 synthetic: param.attrs.iter()
2704 .filter(|attr| attr.check_name("rustc_synthetic"))
2705 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2709 (hir::ParamName::Plain(ident), kind)
2711 GenericParamKind::Const { ref ty } => {
2712 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const {
2713 ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2719 hir_id: self.lower_node_id(param.id),
2721 span: param.ident.span,
2722 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2723 attrs: self.lower_attrs(¶m.attrs),
2731 generics: &Generics,
2732 itctx: ImplTraitContext<'_>)
2735 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2736 // FIXME: this could probably be done with less rightward drift. Also looks like two control
2737 // paths where report_error is called are also the only paths that advance to after
2738 // the match statement, so the error reporting could probably just be moved there.
2739 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
2740 for pred in &generics.where_clause.predicates {
2741 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2742 'next_bound: for bound in &bound_pred.bounds {
2743 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2744 let report_error = |this: &mut Self| {
2745 this.diagnostic().span_err(
2746 bound_pred.bounded_ty.span,
2747 "`?Trait` bounds are only permitted at the \
2748 point where a type parameter is declared",
2751 // Check if the where clause type is a plain type parameter.
2752 match bound_pred.bounded_ty.node {
2753 TyKind::Path(None, ref path)
2754 if path.segments.len() == 1
2755 && bound_pred.bound_generic_params.is_empty() =>
2757 if let Some(Def::TyParam(def_id)) = self.resolver
2758 .get_resolution(bound_pred.bounded_ty.id)
2759 .map(|d| d.base_def())
2761 if let Some(node_id) =
2762 self.resolver.definitions().as_local_node_id(def_id)
2764 for param in &generics.params {
2766 GenericParamKind::Type { .. } => {
2767 if node_id == param.id {
2768 add_bounds.entry(param.id)
2770 .push(bound.clone());
2771 continue 'next_bound;
2781 _ => report_error(self),
2789 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2790 where_clause: self.lower_where_clause(&generics.where_clause),
2791 span: generics.span,
2795 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2796 self.with_anonymous_lifetime_mode(
2797 AnonymousLifetimeMode::ReportError,
2800 hir_id: this.lower_node_id(wc.id),
2801 predicates: wc.predicates
2803 .map(|predicate| this.lower_where_predicate(predicate))
2810 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2812 WherePredicate::BoundPredicate(WhereBoundPredicate {
2813 ref bound_generic_params,
2818 self.with_in_scope_lifetime_defs(
2819 &bound_generic_params,
2821 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2822 bound_generic_params: this.lower_generic_params(
2823 bound_generic_params,
2824 &NodeMap::default(),
2825 ImplTraitContext::disallowed(),
2827 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
2830 .filter_map(|bound| match *bound {
2831 // Ignore `?Trait` bounds.
2832 // They were copied into type parameters already.
2833 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2834 _ => Some(this.lower_param_bound(
2836 ImplTraitContext::disallowed(),
2845 WherePredicate::RegionPredicate(WhereRegionPredicate {
2849 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2851 lifetime: self.lower_lifetime(lifetime),
2852 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2854 WherePredicate::EqPredicate(WhereEqPredicate {
2860 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2861 hir_id: self.lower_node_id(id),
2862 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
2863 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
2870 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2872 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
2873 fields.iter().enumerate().map(|f| self.lower_struct_field(f)).collect(),
2876 VariantData::Tuple(ref fields, id) => {
2877 hir::VariantData::Tuple(
2881 .map(|f| self.lower_struct_field(f))
2883 self.lower_node_id(id),
2886 VariantData::Unit(id) => {
2887 hir::VariantData::Unit(self.lower_node_id(id))
2892 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2893 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2894 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2895 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2899 hir_ref_id: self.lower_node_id(p.ref_id),
2903 fn lower_poly_trait_ref(
2906 mut itctx: ImplTraitContext<'_>,
2907 ) -> hir::PolyTraitRef {
2908 let bound_generic_params = self.lower_generic_params(
2909 &p.bound_generic_params,
2910 &NodeMap::default(),
2913 let trait_ref = self.with_parent_impl_lifetime_defs(
2914 &bound_generic_params,
2915 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2919 bound_generic_params,
2925 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2928 hir_id: self.lower_node_id(f.id),
2929 ident: match f.ident {
2930 Some(ident) => ident,
2931 // FIXME(jseyfried): positional field hygiene
2932 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2934 vis: self.lower_visibility(&f.vis, None),
2935 ty: self.lower_ty(&f.ty, ImplTraitContext::disallowed()),
2936 attrs: self.lower_attrs(&f.attrs),
2940 fn lower_field(&mut self, f: &Field) -> hir::Field {
2942 hir_id: self.next_id(),
2944 expr: P(self.lower_expr(&f.expr)),
2946 is_shorthand: f.is_shorthand,
2950 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2952 ty: self.lower_ty(&mt.ty, itctx),
2953 mutbl: self.lower_mutability(mt.mutbl),
2957 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2958 -> hir::GenericBounds {
2959 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2962 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2963 let mut expr = None;
2965 let mut stmts = vec![];
2967 for (index, stmt) in b.stmts.iter().enumerate() {
2968 if index == b.stmts.len() - 1 {
2969 if let StmtKind::Expr(ref e) = stmt.node {
2970 expr = Some(P(self.lower_expr(e)));
2972 stmts.extend(self.lower_stmt(stmt));
2975 stmts.extend(self.lower_stmt(stmt));
2980 hir_id: self.lower_node_id(b.id),
2981 stmts: stmts.into(),
2983 rules: self.lower_block_check_mode(&b.rules),
2989 fn lower_async_body(
2992 asyncness: &IsAsync,
2995 self.lower_body(Some(&decl), |this| {
2996 if let IsAsync::Async { closure_id, ref arguments, .. } = asyncness {
2997 let mut body = body.clone();
2999 for a in arguments.iter().rev() {
3000 body.stmts.insert(0, a.stmt.clone());
3003 let async_expr = this.make_async_expr(
3004 CaptureBy::Value, *closure_id, None, body.span,
3006 let body = this.lower_block(&body, false);
3007 this.expr_block(body, ThinVec::new())
3009 this.expr(body.span, async_expr, ThinVec::new())
3011 let body = this.lower_block(body, false);
3012 this.expr_block(body, ThinVec::new())
3021 attrs: &hir::HirVec<Attribute>,
3022 vis: &mut hir::Visibility,
3024 ) -> hir::ItemKind {
3026 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
3027 ItemKind::Use(ref use_tree) => {
3028 // Start with an empty prefix
3031 span: use_tree.span,
3034 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
3036 ItemKind::Static(ref t, m, ref e) => {
3037 let value = self.lower_body(None, |this| this.lower_expr(e));
3038 hir::ItemKind::Static(
3041 if self.sess.features_untracked().impl_trait_in_bindings {
3042 ImplTraitContext::Existential(None)
3044 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3047 self.lower_mutability(m),
3051 ItemKind::Const(ref t, ref e) => {
3052 let value = self.lower_body(None, |this| this.lower_expr(e));
3053 hir::ItemKind::Const(
3056 if self.sess.features_untracked().impl_trait_in_bindings {
3057 ImplTraitContext::Existential(None)
3059 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3065 ItemKind::Fn(ref decl, ref header, ref generics, ref body) => {
3066 let fn_def_id = self.resolver.definitions().local_def_id(id);
3067 self.with_new_scopes(|this| {
3068 let mut lower_fn = |decl: &FnDecl| {
3069 // Note: we don't need to change the return type from `T` to
3070 // `impl Future<Output = T>` here because lower_body
3071 // only cares about the input argument patterns in the function
3072 // declaration (decl), not the return types.
3073 let body_id = this.lower_async_body(&decl, &header.asyncness.node, body);
3075 let (generics, fn_decl) = this.add_in_band_defs(
3078 AnonymousLifetimeMode::PassThrough,
3079 |this, idty| this.lower_fn_decl(
3081 Some((fn_def_id, idty)),
3083 header.asyncness.node.opt_return_id()
3087 (body_id, generics, fn_decl)
3090 let (body_id, generics, fn_decl) = if let IsAsync::Async {
3092 } = &header.asyncness.node {
3093 let mut decl = decl.clone();
3094 // Replace the arguments of this async function with the generated
3095 // arguments that will be moved into the closure.
3096 decl.inputs = arguments.clone().drain(..).map(|a| a.arg).collect();
3104 this.lower_fn_header(header),
3110 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
3111 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
3112 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
3113 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
3114 self.lower_ty(t, ImplTraitContext::disallowed()),
3115 self.lower_generics(generics, ImplTraitContext::disallowed()),
3117 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
3118 generics: self.lower_generics(generics, ImplTraitContext::disallowed()),
3119 bounds: self.lower_param_bounds(b, ImplTraitContext::disallowed()),
3120 impl_trait_fn: None,
3121 origin: hir::ExistTyOrigin::ExistentialType,
3123 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
3125 variants: enum_definition
3128 .map(|x| self.lower_variant(x))
3131 self.lower_generics(generics, ImplTraitContext::disallowed()),
3133 ItemKind::Struct(ref struct_def, ref generics) => {
3134 let struct_def = self.lower_variant_data(struct_def);
3135 hir::ItemKind::Struct(
3137 self.lower_generics(generics, ImplTraitContext::disallowed()),
3140 ItemKind::Union(ref vdata, ref generics) => {
3141 let vdata = self.lower_variant_data(vdata);
3142 hir::ItemKind::Union(
3144 self.lower_generics(generics, ImplTraitContext::disallowed()),
3156 let def_id = self.resolver.definitions().local_def_id(id);
3158 // Lower the "impl header" first. This ordering is important
3159 // for in-band lifetimes! Consider `'a` here:
3161 // impl Foo<'a> for u32 {
3162 // fn method(&'a self) { .. }
3165 // Because we start by lowering the `Foo<'a> for u32`
3166 // part, we will add `'a` to the list of generics on
3167 // the impl. When we then encounter it later in the
3168 // method, it will not be considered an in-band
3169 // lifetime to be added, but rather a reference to a
3171 let lowered_trait_impl_id = self.lower_node_id(id);
3172 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
3175 AnonymousLifetimeMode::CreateParameter,
3177 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
3178 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
3181 if let Some(ref trait_ref) = trait_ref {
3182 if let Def::Trait(def_id) = trait_ref.path.def {
3183 this.trait_impls.entry(def_id).or_default().push(
3184 lowered_trait_impl_id);
3188 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
3190 (trait_ref, lowered_ty)
3194 let new_impl_items = self.with_in_scope_lifetime_defs(
3195 &ast_generics.params,
3199 .map(|item| this.lower_impl_item_ref(item))
3204 hir::ItemKind::Impl(
3205 self.lower_unsafety(unsafety),
3206 self.lower_impl_polarity(polarity),
3207 self.lower_defaultness(defaultness, true /* [1] */),
3214 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
3215 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
3218 .map(|item| self.lower_trait_item_ref(item))
3220 hir::ItemKind::Trait(
3221 self.lower_is_auto(is_auto),
3222 self.lower_unsafety(unsafety),
3223 self.lower_generics(generics, ImplTraitContext::disallowed()),
3228 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
3229 self.lower_generics(generics, ImplTraitContext::disallowed()),
3230 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3232 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
3235 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
3236 // not cause an assertion failure inside the `lower_defaultness` function.
3244 vis: &mut hir::Visibility,
3246 attrs: &hir::HirVec<Attribute>,
3247 ) -> hir::ItemKind {
3248 debug!("lower_use_tree(tree={:?})", tree);
3249 debug!("lower_use_tree: vis = {:?}", vis);
3251 let path = &tree.prefix;
3252 let segments = prefix
3255 .chain(path.segments.iter())
3260 UseTreeKind::Simple(rename, id1, id2) => {
3261 *ident = tree.ident();
3263 // First, apply the prefix to the path.
3264 let mut path = Path {
3269 // Correctly resolve `self` imports.
3270 if path.segments.len() > 1
3271 && path.segments.last().unwrap().ident.name == keywords::SelfLower.name()
3273 let _ = path.segments.pop();
3274 if rename.is_none() {
3275 *ident = path.segments.last().unwrap().ident;
3279 let mut defs = self.expect_full_def_from_use(id);
3280 // We want to return *something* from this function, so hold onto the first item
3282 let ret_def = self.lower_def(defs.next().unwrap_or(Def::Err));
3284 // Here, we are looping over namespaces, if they exist for the definition
3285 // being imported. We only handle type and value namespaces because we
3286 // won't be dealing with macros in the rest of the compiler.
3287 // Essentially a single `use` which imports two names is desugared into
3289 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
3290 let vis = vis.clone();
3291 let ident = ident.clone();
3292 let mut path = path.clone();
3293 for seg in &mut path.segments {
3294 seg.id = self.sess.next_node_id();
3296 let span = path.span;
3298 self.with_hir_id_owner(new_node_id, |this| {
3299 let new_id = this.lower_node_id(new_node_id);
3300 let def = this.lower_def(def);
3302 this.lower_path_extra(def, &path, ParamMode::Explicit, None);
3303 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
3304 let vis_kind = match vis.node {
3305 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3306 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3307 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3308 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
3309 let path = this.renumber_segment_ids(path);
3310 hir::VisibilityKind::Restricted {
3312 hir_id: this.next_id(),
3316 let vis = respan(vis.span, vis_kind);
3322 attrs: attrs.clone(),
3332 P(self.lower_path_extra(ret_def, &path, ParamMode::Explicit, None));
3333 hir::ItemKind::Use(path, hir::UseKind::Single)
3335 UseTreeKind::Glob => {
3336 let path = P(self.lower_path(
3342 ParamMode::Explicit,
3344 hir::ItemKind::Use(path, hir::UseKind::Glob)
3346 UseTreeKind::Nested(ref trees) => {
3347 // Nested imports are desugared into simple imports.
3348 // So, if we start with
3351 // pub(x) use foo::{a, b};
3354 // we will create three items:
3357 // pub(x) use foo::a;
3358 // pub(x) use foo::b;
3359 // pub(x) use foo::{}; // <-- this is called the `ListStem`
3362 // The first two are produced by recursively invoking
3363 // `lower_use_tree` (and indeed there may be things
3364 // like `use foo::{a::{b, c}}` and so forth). They
3365 // wind up being directly added to
3366 // `self.items`. However, the structure of this
3367 // function also requires us to return one item, and
3368 // for that we return the `{}` import (called the
3373 span: prefix.span.to(path.span),
3376 // Add all the nested `PathListItem`s to the HIR.
3377 for &(ref use_tree, id) in trees {
3378 let new_hir_id = self.lower_node_id(id);
3380 let mut vis = vis.clone();
3381 let mut ident = ident.clone();
3382 let mut prefix = prefix.clone();
3384 // Give the segments new node-ids since they are being cloned.
3385 for seg in &mut prefix.segments {
3386 seg.id = self.sess.next_node_id();
3389 // Each `use` import is an item and thus are owners of the
3390 // names in the path. Up to this point the nested import is
3391 // the current owner, since we want each desugared import to
3392 // own its own names, we have to adjust the owner before
3393 // lowering the rest of the import.
3394 self.with_hir_id_owner(id, |this| {
3395 let item = this.lower_use_tree(use_tree,
3402 let vis_kind = match vis.node {
3403 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3404 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3405 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3406 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
3407 let path = this.renumber_segment_ids(path);
3408 hir::VisibilityKind::Restricted {
3410 hir_id: this.next_id(),
3414 let vis = respan(vis.span, vis_kind);
3420 attrs: attrs.clone(),
3423 span: use_tree.span,
3429 // Subtle and a bit hacky: we lower the privacy level
3430 // of the list stem to "private" most of the time, but
3431 // not for "restricted" paths. The key thing is that
3432 // we don't want it to stay as `pub` (with no caveats)
3433 // because that affects rustdoc and also the lints
3434 // about `pub` items. But we can't *always* make it
3435 // private -- particularly not for restricted paths --
3436 // because it contains node-ids that would then be
3437 // unused, failing the check that HirIds are "densely
3440 hir::VisibilityKind::Public |
3441 hir::VisibilityKind::Crate(_) |
3442 hir::VisibilityKind::Inherited => {
3443 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3445 hir::VisibilityKind::Restricted { .. } => {
3446 // Do nothing here, as described in the comment on the match.
3450 let def = self.expect_full_def_from_use(id).next().unwrap_or(Def::Err);
3451 let def = self.lower_def(def);
3452 let path = P(self.lower_path_extra(def, &prefix, ParamMode::Explicit, None));
3453 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3458 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
3459 /// many times in the HIR tree; for each occurrence, we need to assign distinct
3460 /// `NodeId`s. (See, e.g., #56128.)
3461 fn renumber_segment_ids(&mut self, path: &P<hir::Path>) -> P<hir::Path> {
3462 debug!("renumber_segment_ids(path = {:?})", path);
3463 let mut path = path.clone();
3464 for seg in path.segments.iter_mut() {
3465 if seg.hir_id.is_some() {
3466 seg.hir_id = Some(self.next_id());
3472 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3473 let trait_item_def_id = self.resolver.definitions().local_def_id(i.id);
3475 let (generics, node) = match i.node {
3476 TraitItemKind::Const(ref ty, ref default) => (
3477 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3478 hir::TraitItemKind::Const(
3479 self.lower_ty(ty, ImplTraitContext::disallowed()),
3482 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
3485 TraitItemKind::Method(ref sig, None) => {
3486 let names = self.lower_fn_args_to_names(&sig.decl);
3487 let (generics, sig) = self.lower_method_sig(
3494 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3496 TraitItemKind::Method(ref sig, Some(ref body)) => {
3497 let body_id = self.lower_body(Some(&sig.decl), |this| {
3498 let body = this.lower_block(body, false);
3499 this.expr_block(body, ThinVec::new())
3501 let (generics, sig) = self.lower_method_sig(
3508 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3510 TraitItemKind::Type(ref bounds, ref default) => (
3511 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3512 hir::TraitItemKind::Type(
3513 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3516 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3519 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3523 hir_id: self.lower_node_id(i.id),
3525 attrs: self.lower_attrs(&i.attrs),
3532 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3533 let (kind, has_default) = match i.node {
3534 TraitItemKind::Const(_, ref default) => {
3535 (hir::AssociatedItemKind::Const, default.is_some())
3537 TraitItemKind::Type(_, ref default) => {
3538 (hir::AssociatedItemKind::Type, default.is_some())
3540 TraitItemKind::Method(ref sig, ref default) => (
3541 hir::AssociatedItemKind::Method {
3542 has_self: sig.decl.has_self(),
3546 TraitItemKind::Macro(..) => unimplemented!(),
3549 id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) },
3552 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3557 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3558 let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
3560 let (generics, node) = match i.node {
3561 ImplItemKind::Const(ref ty, ref expr) => {
3562 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3564 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3565 hir::ImplItemKind::Const(
3566 self.lower_ty(ty, ImplTraitContext::disallowed()),
3571 ImplItemKind::Method(ref sig, ref body) => {
3572 let mut lower_method = |sig: &MethodSig| {
3573 let body_id = self.lower_async_body(
3574 &sig.decl, &sig.header.asyncness.node, body
3576 let impl_trait_return_allow = !self.is_in_trait_impl;
3577 let (generics, sig) = self.lower_method_sig(
3581 impl_trait_return_allow,
3582 sig.header.asyncness.node.opt_return_id(),
3584 (body_id, generics, sig)
3587 let (body_id, generics, sig) = if let IsAsync::Async {
3589 } = sig.header.asyncness.node {
3590 let mut sig = sig.clone();
3591 // Replace the arguments of this async function with the generated
3592 // arguments that will be moved into the closure.
3593 sig.decl.inputs = arguments.clone().drain(..).map(|a| a.arg).collect();
3599 (generics, hir::ImplItemKind::Method(sig, body_id))
3601 ImplItemKind::Type(ref ty) => (
3602 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3603 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3605 ImplItemKind::Existential(ref bounds) => (
3606 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3607 hir::ImplItemKind::Existential(
3608 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3611 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3615 hir_id: self.lower_node_id(i.id),
3617 attrs: self.lower_attrs(&i.attrs),
3619 vis: self.lower_visibility(&i.vis, None),
3620 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3625 // [1] since `default impl` is not yet implemented, this is always true in impls
3628 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3630 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
3633 vis: self.lower_visibility(&i.vis, Some(i.id)),
3634 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3635 kind: match i.node {
3636 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3637 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3638 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3639 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3640 has_self: sig.decl.has_self(),
3642 ImplItemKind::Macro(..) => unimplemented!(),
3646 // [1] since `default impl` is not yet implemented, this is always true in impls
3649 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3652 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3656 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3657 let node_ids = match i.node {
3658 ItemKind::Use(ref use_tree) => {
3659 let mut vec = smallvec![i.id];
3660 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3663 ItemKind::MacroDef(..) => SmallVec::new(),
3665 ItemKind::Impl(.., None, _, _) => smallvec![i.id],
3666 ItemKind::Static(ref ty, ..) => {
3667 let mut ids = smallvec![i.id];
3668 if self.sess.features_untracked().impl_trait_in_bindings {
3669 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3670 visitor.visit_ty(ty);
3674 ItemKind::Const(ref ty, ..) => {
3675 let mut ids = smallvec![i.id];
3676 if self.sess.features_untracked().impl_trait_in_bindings {
3677 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3678 visitor.visit_ty(ty);
3682 _ => smallvec![i.id],
3685 node_ids.into_iter().map(|node_id| hir::ItemId {
3686 id: self.allocate_hir_id_counter(node_id)
3690 fn lower_item_id_use_tree(&mut self,
3693 vec: &mut SmallVec<[NodeId; 1]>)
3696 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3698 self.lower_item_id_use_tree(nested, id, vec);
3700 UseTreeKind::Glob => {}
3701 UseTreeKind::Simple(_, id1, id2) => {
3702 for (_, &id) in self.expect_full_def_from_use(base_id)
3704 .zip([id1, id2].iter())
3712 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3713 let mut ident = i.ident;
3714 let mut vis = self.lower_visibility(&i.vis, None);
3715 let attrs = self.lower_attrs(&i.attrs);
3716 if let ItemKind::MacroDef(ref def) = i.node {
3717 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3718 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3719 let body = self.lower_token_stream(def.stream());
3720 let hir_id = self.lower_node_id(i.id);
3721 self.exported_macros.push(hir::MacroDef {
3734 let node = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.node);
3737 hir_id: self.lower_node_id(i.id),
3746 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3747 let def_id = self.resolver.definitions().local_def_id(i.id);
3749 hir_id: self.lower_node_id(i.id),
3751 attrs: self.lower_attrs(&i.attrs),
3752 node: match i.node {
3753 ForeignItemKind::Fn(ref fdec, ref generics) => {
3754 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3757 AnonymousLifetimeMode::PassThrough,
3760 // Disallow impl Trait in foreign items
3761 this.lower_fn_decl(fdec, None, false, None),
3762 this.lower_fn_args_to_names(fdec),
3767 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3769 ForeignItemKind::Static(ref t, m) => {
3770 hir::ForeignItemKind::Static(
3771 self.lower_ty(t, ImplTraitContext::disallowed()), self.lower_mutability(m))
3773 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3774 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3776 vis: self.lower_visibility(&i.vis, None),
3781 fn lower_method_sig(
3783 generics: &Generics,
3786 impl_trait_return_allow: bool,
3787 is_async: Option<NodeId>,
3788 ) -> (hir::Generics, hir::MethodSig) {
3789 let header = self.lower_fn_header(&sig.header);
3790 let (generics, decl) = self.add_in_band_defs(
3793 AnonymousLifetimeMode::PassThrough,
3794 |this, idty| this.lower_fn_decl(
3796 Some((fn_def_id, idty)),
3797 impl_trait_return_allow,
3801 (generics, hir::MethodSig { header, decl })
3804 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3806 IsAuto::Yes => hir::IsAuto::Yes,
3807 IsAuto::No => hir::IsAuto::No,
3811 fn lower_fn_header(&mut self, h: &FnHeader) -> hir::FnHeader {
3813 unsafety: self.lower_unsafety(h.unsafety),
3814 asyncness: self.lower_asyncness(&h.asyncness.node),
3815 constness: self.lower_constness(h.constness),
3820 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3822 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3823 Unsafety::Normal => hir::Unsafety::Normal,
3827 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3829 Constness::Const => hir::Constness::Const,
3830 Constness::NotConst => hir::Constness::NotConst,
3834 fn lower_asyncness(&mut self, a: &IsAsync) -> hir::IsAsync {
3836 IsAsync::Async { .. } => hir::IsAsync::Async,
3837 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3841 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3843 UnOp::Deref => hir::UnDeref,
3844 UnOp::Not => hir::UnNot,
3845 UnOp::Neg => hir::UnNeg,
3849 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3851 node: match b.node {
3852 BinOpKind::Add => hir::BinOpKind::Add,
3853 BinOpKind::Sub => hir::BinOpKind::Sub,
3854 BinOpKind::Mul => hir::BinOpKind::Mul,
3855 BinOpKind::Div => hir::BinOpKind::Div,
3856 BinOpKind::Rem => hir::BinOpKind::Rem,
3857 BinOpKind::And => hir::BinOpKind::And,
3858 BinOpKind::Or => hir::BinOpKind::Or,
3859 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3860 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3861 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3862 BinOpKind::Shl => hir::BinOpKind::Shl,
3863 BinOpKind::Shr => hir::BinOpKind::Shr,
3864 BinOpKind::Eq => hir::BinOpKind::Eq,
3865 BinOpKind::Lt => hir::BinOpKind::Lt,
3866 BinOpKind::Le => hir::BinOpKind::Le,
3867 BinOpKind::Ne => hir::BinOpKind::Ne,
3868 BinOpKind::Ge => hir::BinOpKind::Ge,
3869 BinOpKind::Gt => hir::BinOpKind::Gt,
3875 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3876 let node = match p.node {
3877 PatKind::Wild => hir::PatKind::Wild,
3878 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3879 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3880 // `None` can occur in body-less function signatures
3881 def @ None | def @ Some(Def::Local(_)) => {
3882 let canonical_id = match def {
3883 Some(Def::Local(id)) => id,
3887 hir::PatKind::Binding(
3888 self.lower_binding_mode(binding_mode),
3889 self.lower_node_id(canonical_id),
3891 sub.as_ref().map(|x| self.lower_pat(x)),
3894 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3898 def: self.lower_def(def),
3899 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3904 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3905 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3906 let qpath = self.lower_qpath(
3910 ParamMode::Optional,
3911 ImplTraitContext::disallowed(),
3913 hir::PatKind::TupleStruct(
3915 pats.iter().map(|x| self.lower_pat(x)).collect(),
3919 PatKind::Path(ref qself, ref path) => {
3920 let qpath = self.lower_qpath(
3924 ParamMode::Optional,
3925 ImplTraitContext::disallowed(),
3927 hir::PatKind::Path(qpath)
3929 PatKind::Struct(ref path, ref fields, etc) => {
3930 let qpath = self.lower_qpath(
3934 ParamMode::Optional,
3935 ImplTraitContext::disallowed(),
3943 node: hir::FieldPat {
3944 hir_id: self.next_id(),
3945 ident: f.node.ident,
3946 pat: self.lower_pat(&f.node.pat),
3947 is_shorthand: f.node.is_shorthand,
3952 hir::PatKind::Struct(qpath, fs, etc)
3954 PatKind::Tuple(ref elts, ddpos) => {
3955 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3957 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3958 PatKind::Ref(ref inner, mutbl) => {
3959 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3961 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3962 P(self.lower_expr(e1)),
3963 P(self.lower_expr(e2)),
3964 self.lower_range_end(end),
3966 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3967 before.iter().map(|x| self.lower_pat(x)).collect(),
3968 slice.as_ref().map(|x| self.lower_pat(x)),
3969 after.iter().map(|x| self.lower_pat(x)).collect(),
3971 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3972 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3976 hir_id: self.lower_node_id(p.id),
3982 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3984 RangeEnd::Included(_) => hir::RangeEnd::Included,
3985 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3989 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3990 self.with_new_scopes(|this| {
3992 hir_id: this.lower_node_id(c.id),
3993 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3998 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3999 let kind = match e.node {
4000 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
4001 ExprKind::ObsoleteInPlace(..) => {
4002 self.sess.abort_if_errors();
4003 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
4005 ExprKind::Array(ref exprs) => {
4006 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
4008 ExprKind::Repeat(ref expr, ref count) => {
4009 let expr = P(self.lower_expr(expr));
4010 let count = self.lower_anon_const(count);
4011 hir::ExprKind::Repeat(expr, count)
4013 ExprKind::Tup(ref elts) => {
4014 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
4016 ExprKind::Call(ref f, ref args) => {
4017 let f = P(self.lower_expr(f));
4018 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
4020 ExprKind::MethodCall(ref seg, ref args) => {
4021 let hir_seg = P(self.lower_path_segment(
4024 ParamMode::Optional,
4026 ParenthesizedGenericArgs::Err,
4027 ImplTraitContext::disallowed(),
4030 let args = args.iter().map(|x| self.lower_expr(x)).collect();
4031 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
4033 ExprKind::Binary(binop, ref lhs, ref rhs) => {
4034 let binop = self.lower_binop(binop);
4035 let lhs = P(self.lower_expr(lhs));
4036 let rhs = P(self.lower_expr(rhs));
4037 hir::ExprKind::Binary(binop, lhs, rhs)
4039 ExprKind::Unary(op, ref ohs) => {
4040 let op = self.lower_unop(op);
4041 let ohs = P(self.lower_expr(ohs));
4042 hir::ExprKind::Unary(op, ohs)
4044 ExprKind::Lit(ref l) => hir::ExprKind::Lit((*l).clone()),
4045 ExprKind::Cast(ref expr, ref ty) => {
4046 let expr = P(self.lower_expr(expr));
4047 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4049 ExprKind::Type(ref expr, ref ty) => {
4050 let expr = P(self.lower_expr(expr));
4051 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4053 ExprKind::AddrOf(m, ref ohs) => {
4054 let m = self.lower_mutability(m);
4055 let ohs = P(self.lower_expr(ohs));
4056 hir::ExprKind::AddrOf(m, ohs)
4058 // More complicated than you might expect because the else branch
4059 // might be `if let`.
4060 ExprKind::If(ref cond, ref blk, ref else_opt) => {
4061 let else_opt = else_opt.as_ref().map(|els| {
4063 ExprKind::IfLet(..) => {
4064 // Wrap the `if let` expr in a block.
4065 let span = els.span;
4066 let els = P(self.lower_expr(els));
4067 let blk = P(hir::Block {
4070 hir_id: self.next_id(),
4071 rules: hir::DefaultBlock,
4073 targeted_by_break: false,
4075 P(self.expr_block(blk, ThinVec::new()))
4077 _ => P(self.lower_expr(els)),
4081 let then_blk = self.lower_block(blk, false);
4082 let then_expr = self.expr_block(then_blk, ThinVec::new());
4084 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
4086 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4087 hir::ExprKind::While(
4088 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
4089 this.lower_block(body, false),
4090 this.lower_label(opt_label),
4093 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4094 hir::ExprKind::Loop(
4095 this.lower_block(body, false),
4096 this.lower_label(opt_label),
4097 hir::LoopSource::Loop,
4100 ExprKind::TryBlock(ref body) => {
4101 self.with_catch_scope(body.id, |this| {
4102 let unstable_span = this.mark_span_with_reason(
4103 CompilerDesugaringKind::TryBlock,
4106 Symbol::intern("try_trait"),
4109 let mut block = this.lower_block(body, true).into_inner();
4110 let tail = block.expr.take().map_or_else(
4112 let span = this.sess.source_map().end_point(unstable_span);
4115 node: hir::ExprKind::Tup(hir_vec![]),
4116 attrs: ThinVec::new(),
4117 hir_id: this.next_id(),
4120 |x: P<hir::Expr>| x.into_inner(),
4122 block.expr = Some(this.wrap_in_try_constructor(
4123 "from_ok", tail, unstable_span));
4124 hir::ExprKind::Block(P(block), None)
4127 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
4128 P(self.lower_expr(expr)),
4129 arms.iter().map(|x| self.lower_arm(x)).collect(),
4130 hir::MatchSource::Normal,
4132 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
4133 self.make_async_expr(capture_clause, closure_node_id, None, block.span, |this| {
4134 this.with_new_scopes(|this| {
4135 let block = this.lower_block(block, false);
4136 this.expr_block(block, ThinVec::new())
4141 capture_clause, ref asyncness, movability, ref decl, ref body, fn_decl_span
4143 if let IsAsync::Async { closure_id, .. } = asyncness {
4144 let outer_decl = FnDecl {
4145 inputs: decl.inputs.clone(),
4146 output: FunctionRetTy::Default(fn_decl_span),
4149 // We need to lower the declaration outside the new scope, because we
4150 // have to conserve the state of being inside a loop condition for the
4151 // closure argument types.
4152 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
4154 self.with_new_scopes(|this| {
4155 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
4156 if capture_clause == CaptureBy::Ref &&
4157 !decl.inputs.is_empty()
4163 "`async` non-`move` closures with arguments \
4164 are not currently supported",
4166 .help("consider using `let` statements to manually capture \
4167 variables by reference before entering an \
4168 `async move` closure")
4172 // Transform `async |x: u8| -> X { ... }` into
4173 // `|x: u8| future_from_generator(|| -> X { ... })`.
4174 let body_id = this.lower_body(Some(&outer_decl), |this| {
4175 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
4178 let async_body = this.make_async_expr(
4179 capture_clause, *closure_id, async_ret_ty, body.span,
4181 this.with_new_scopes(|this| this.lower_expr(body))
4183 this.expr(fn_decl_span, async_body, ThinVec::new())
4185 hir::ExprKind::Closure(
4186 this.lower_capture_clause(capture_clause),
4194 // Lower outside new scope to preserve `is_in_loop_condition`.
4195 let fn_decl = self.lower_fn_decl(decl, None, false, None);
4197 self.with_new_scopes(|this| {
4198 let mut is_generator = false;
4199 let body_id = this.lower_body(Some(decl), |this| {
4200 let e = this.lower_expr(body);
4201 is_generator = this.is_generator;
4204 let generator_option = if is_generator {
4205 if !decl.inputs.is_empty() {
4210 "generators cannot have explicit arguments"
4212 this.sess.abort_if_errors();
4214 Some(match movability {
4215 Movability::Movable => hir::GeneratorMovability::Movable,
4216 Movability::Static => hir::GeneratorMovability::Static,
4219 if movability == Movability::Static {
4224 "closures cannot be static"
4229 hir::ExprKind::Closure(
4230 this.lower_capture_clause(capture_clause),
4239 ExprKind::Block(ref blk, opt_label) => {
4240 hir::ExprKind::Block(self.lower_block(blk,
4241 opt_label.is_some()),
4242 self.lower_label(opt_label))
4244 ExprKind::Assign(ref el, ref er) => {
4245 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
4247 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
4248 self.lower_binop(op),
4249 P(self.lower_expr(el)),
4250 P(self.lower_expr(er)),
4252 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
4253 ExprKind::Index(ref el, ref er) => {
4254 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
4256 // Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
4257 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
4258 let id = self.next_id();
4259 let e1 = self.lower_expr(e1);
4260 let e2 = self.lower_expr(e2);
4261 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
4262 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
4263 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
4264 let new_path = hir::QPath::TypeRelative(ty, new_seg);
4265 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
4266 hir::ExprKind::Call(new, hir_vec![e1, e2])
4268 ExprKind::Range(ref e1, ref e2, lims) => {
4269 use syntax::ast::RangeLimits::*;
4271 let path = match (e1, e2, lims) {
4272 (&None, &None, HalfOpen) => "RangeFull",
4273 (&Some(..), &None, HalfOpen) => "RangeFrom",
4274 (&None, &Some(..), HalfOpen) => "RangeTo",
4275 (&Some(..), &Some(..), HalfOpen) => "Range",
4276 (&None, &Some(..), Closed) => "RangeToInclusive",
4277 (&Some(..), &Some(..), Closed) => unreachable!(),
4278 (_, &None, Closed) => self.diagnostic()
4279 .span_fatal(e.span, "inclusive range with no end")
4283 let fields = e1.iter()
4284 .map(|e| ("start", e))
4285 .chain(e2.iter().map(|e| ("end", e)))
4287 let expr = P(self.lower_expr(&e));
4288 let ident = Ident::new(Symbol::intern(s), e.span);
4289 self.field(ident, expr, e.span)
4291 .collect::<P<[hir::Field]>>();
4293 let is_unit = fields.is_empty();
4294 let struct_path = ["ops", path];
4295 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
4296 let struct_path = hir::QPath::Resolved(None, P(struct_path));
4299 hir_id: self.lower_node_id(e.id),
4301 hir::ExprKind::Path(struct_path)
4303 hir::ExprKind::Struct(P(struct_path), fields, None)
4306 attrs: e.attrs.clone(),
4309 ExprKind::Path(ref qself, ref path) => {
4310 let qpath = self.lower_qpath(
4314 ParamMode::Optional,
4315 ImplTraitContext::disallowed(),
4317 hir::ExprKind::Path(qpath)
4319 ExprKind::Break(opt_label, ref opt_expr) => {
4320 let destination = if self.is_in_loop_condition && opt_label.is_none() {
4323 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4326 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4328 hir::ExprKind::Break(
4330 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
4333 ExprKind::Continue(opt_label) => {
4334 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
4337 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4340 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4343 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
4344 ExprKind::InlineAsm(ref asm) => {
4345 let hir_asm = hir::InlineAsm {
4346 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
4347 outputs: asm.outputs
4349 .map(|out| hir::InlineAsmOutput {
4350 constraint: out.constraint.clone(),
4352 is_indirect: out.is_indirect,
4353 span: out.expr.span,
4356 asm: asm.asm.clone(),
4357 asm_str_style: asm.asm_str_style,
4358 clobbers: asm.clobbers.clone().into(),
4359 volatile: asm.volatile,
4360 alignstack: asm.alignstack,
4361 dialect: asm.dialect,
4364 let outputs = asm.outputs
4366 .map(|out| self.lower_expr(&out.expr))
4368 let inputs = asm.inputs
4370 .map(|&(_, ref input)| self.lower_expr(input))
4372 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
4374 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4379 ParamMode::Optional,
4380 ImplTraitContext::disallowed(),
4382 fields.iter().map(|x| self.lower_field(x)).collect(),
4383 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4385 ExprKind::Paren(ref ex) => {
4386 let mut ex = self.lower_expr(ex);
4387 // Include parens in span, but only if it is a super-span.
4388 if e.span.contains(ex.span) {
4391 // Merge attributes into the inner expression.
4392 let mut attrs = e.attrs.clone();
4393 attrs.extend::<Vec<_>>(ex.attrs.into());
4398 ExprKind::Yield(ref opt_expr) => {
4399 self.is_generator = true;
4402 .map(|x| self.lower_expr(x))
4404 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
4406 hir::ExprKind::Yield(P(expr))
4409 ExprKind::Err => hir::ExprKind::Err,
4411 // Desugar `ExprIfLet`
4412 // from: `if let <pat> = <sub_expr> <body> [<else_opt>]`
4413 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4416 // match <sub_expr> {
4418 // _ => [<else_opt> | ()]
4421 let mut arms = vec![];
4423 // `<pat> => <body>`
4425 let body = self.lower_block(body, false);
4426 let body_expr = P(self.expr_block(body, ThinVec::new()));
4427 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4428 arms.push(self.arm(pats, body_expr));
4431 // _ => [<else_opt>|()]
4433 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4434 let wildcard_pattern = self.pat_wild(e.span);
4435 let body = if let Some(else_expr) = wildcard_arm {
4436 P(self.lower_expr(else_expr))
4438 self.expr_tuple(e.span, hir_vec![])
4440 arms.push(self.arm(hir_vec![wildcard_pattern], body));
4443 let contains_else_clause = else_opt.is_some();
4445 let sub_expr = P(self.lower_expr(sub_expr));
4447 hir::ExprKind::Match(
4450 hir::MatchSource::IfLetDesugar {
4451 contains_else_clause,
4456 // Desugar `ExprWhileLet`
4457 // from: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4458 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4461 // [opt_ident]: loop {
4462 // match <sub_expr> {
4468 // Note that the block AND the condition are evaluated in the loop scope.
4469 // This is done to allow `break` from inside the condition of the loop.
4470 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4472 this.lower_block(body, false),
4473 this.expr_break(e.span, ThinVec::new()),
4474 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4478 // `<pat> => <body>`
4480 let body_expr = P(self.expr_block(body, ThinVec::new()));
4481 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4482 self.arm(pats, body_expr)
4487 let pat_under = self.pat_wild(e.span);
4488 self.arm(hir_vec![pat_under], break_expr)
4491 // `match <sub_expr> { ... }`
4492 let arms = hir_vec![pat_arm, break_arm];
4493 let match_expr = self.expr(
4495 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4499 // `[opt_ident]: loop { ... }`
4500 let loop_block = P(self.block_expr(P(match_expr)));
4501 let loop_expr = hir::ExprKind::Loop(
4503 self.lower_label(opt_label),
4504 hir::LoopSource::WhileLet,
4506 // Add attributes to the outer returned expr node.
4510 // Desugar `ExprForLoop`
4511 // from: `[opt_ident]: for <pat> in <head> <body>`
4512 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4516 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4518 // [opt_ident]: loop {
4520 // match ::std::iter::Iterator::next(&mut iter) {
4521 // ::std::option::Option::Some(val) => __next = val,
4522 // ::std::option::Option::None => break
4524 // let <pat> = __next;
4525 // StmtKind::Expr(<body>);
4533 let mut head = self.lower_expr(head);
4534 let head_sp = head.span;
4535 let desugared_span = self.mark_span_with_reason(
4536 CompilerDesugaringKind::ForLoop,
4540 head.span = desugared_span;
4542 let iter = self.str_to_ident("iter");
4544 let next_ident = self.str_to_ident("__next");
4545 let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
4548 hir::BindingAnnotation::Mutable,
4551 // `::std::option::Option::Some(val) => next = val`
4553 let val_ident = self.str_to_ident("val");
4554 let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
4555 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat_hid));
4556 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat_hid));
4557 let assign = P(self.expr(
4559 hir::ExprKind::Assign(next_expr, val_expr),
4562 let some_pat = self.pat_some(pat.span, val_pat);
4563 self.arm(hir_vec![some_pat], assign)
4566 // `::std::option::Option::None => break`
4569 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4570 let pat = self.pat_none(e.span);
4571 self.arm(hir_vec![pat], break_expr)
4575 let (iter_pat, iter_pat_nid) = self.pat_ident_binding_mode(
4578 hir::BindingAnnotation::Mutable
4581 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4583 let iter = P(self.expr_ident(head_sp, iter, iter_pat_nid));
4584 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4585 let next_path = &["iter", "Iterator", "next"];
4586 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4587 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4588 let arms = hir_vec![pat_arm, break_arm];
4592 hir::ExprKind::Match(
4595 hir::MatchSource::ForLoopDesugar
4600 let match_stmt = hir::Stmt {
4601 hir_id: self.next_id(),
4602 node: hir::StmtKind::Expr(match_expr),
4606 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat_hid));
4609 let next_let = self.stmt_let_pat(
4613 hir::LocalSource::ForLoopDesugar,
4616 // `let <pat> = __next`
4617 let pat = self.lower_pat(pat);
4618 let pat_let = self.stmt_let_pat(
4622 hir::LocalSource::ForLoopDesugar,
4625 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4626 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4627 let body_stmt = hir::Stmt {
4628 hir_id: self.next_id(),
4629 node: hir::StmtKind::Expr(body_expr),
4633 let loop_block = P(self.block_all(
4635 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4639 // `[opt_ident]: loop { ... }`
4640 let loop_expr = hir::ExprKind::Loop(
4642 self.lower_label(opt_label),
4643 hir::LoopSource::ForLoop,
4645 let loop_expr = P(hir::Expr {
4646 hir_id: self.lower_node_id(e.id),
4649 attrs: ThinVec::new(),
4652 // `mut iter => { ... }`
4653 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4655 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4656 let into_iter_expr = {
4657 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4658 let into_iter = P(self.expr_std_path(
4659 head_sp, into_iter_path, None, ThinVec::new()));
4660 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4663 let match_expr = P(self.expr_match(
4667 hir::MatchSource::ForLoopDesugar,
4670 // This is effectively `{ let _result = ...; _result }`.
4671 // The construct was introduced in #21984.
4672 // FIXME(60253): Is this still necessary?
4673 // Also, add the attributes to the outer returned expr node.
4674 return self.expr_use(head_sp, match_expr, e.attrs.clone())
4677 // Desugar `ExprKind::Try`
4679 ExprKind::Try(ref sub_expr) => {
4682 // match Try::into_result(<expr>) {
4683 // Ok(val) => #[allow(unreachable_code)] val,
4684 // Err(err) => #[allow(unreachable_code)]
4685 // // If there is an enclosing `catch {...}`
4686 // break 'catch_target Try::from_error(From::from(err)),
4688 // return Try::from_error(From::from(err)),
4691 let unstable_span = self.mark_span_with_reason(
4692 CompilerDesugaringKind::QuestionMark,
4695 Symbol::intern("try_trait")
4698 let try_span = self.sess.source_map().end_point(e.span);
4699 let try_span = self.mark_span_with_reason(
4700 CompilerDesugaringKind::QuestionMark,
4703 Symbol::intern("try_trait")
4707 // `Try::into_result(<expr>)`
4710 let sub_expr = self.lower_expr(sub_expr);
4712 let path = &["ops", "Try", "into_result"];
4713 let path = P(self.expr_std_path(
4714 unstable_span, path, None, ThinVec::new()));
4715 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4718 // `#[allow(unreachable_code)]`
4720 // `allow(unreachable_code)`
4722 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4723 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4724 let uc_nested = attr::mk_nested_word_item(uc_ident);
4725 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4727 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4729 let attrs = vec![attr];
4731 // `Ok(val) => #[allow(unreachable_code)] val,`
4733 let val_ident = self.str_to_ident("val");
4734 let (val_pat, val_pat_nid) = self.pat_ident(e.span, val_ident);
4735 let val_expr = P(self.expr_ident_with_attrs(
4739 ThinVec::from(attrs.clone()),
4741 let ok_pat = self.pat_ok(e.span, val_pat);
4743 self.arm(hir_vec![ok_pat], val_expr)
4746 // `Err(err) => #[allow(unreachable_code)]
4747 // return Try::from_error(From::from(err)),`
4749 let err_ident = self.str_to_ident("err");
4750 let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
4752 let path = &["convert", "From", "from"];
4753 let from = P(self.expr_std_path(
4754 try_span, path, None, ThinVec::new()));
4755 let err_expr = self.expr_ident(try_span, err_ident, err_local_nid);
4757 self.expr_call(try_span, from, hir_vec![err_expr])
4760 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4761 let thin_attrs = ThinVec::from(attrs);
4762 let catch_scope = self.catch_scopes.last().map(|x| *x);
4763 let ret_expr = if let Some(catch_node) = catch_scope {
4764 let target_id = Ok(self.lower_node_id(catch_node));
4767 hir::ExprKind::Break(
4772 Some(from_err_expr),
4777 P(self.expr(try_span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4780 let err_pat = self.pat_err(try_span, err_local);
4781 self.arm(hir_vec![err_pat], ret_expr)
4784 hir::ExprKind::Match(
4786 hir_vec![err_arm, ok_arm],
4787 hir::MatchSource::TryDesugar,
4791 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4795 hir_id: self.lower_node_id(e.id),
4798 attrs: e.attrs.clone(),
4802 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
4803 smallvec![match s.node {
4804 StmtKind::Local(ref l) => {
4805 let (l, item_ids) = self.lower_local(l);
4806 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
4809 let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
4812 hir_id: self.next_id(),
4813 node: hir::StmtKind::Item(item_id),
4820 hir_id: self.lower_node_id(s.id),
4821 node: hir::StmtKind::Local(P(l)),
4827 StmtKind::Item(ref it) => {
4828 // Can only use the ID once.
4829 let mut id = Some(s.id);
4830 return self.lower_item_id(it)
4833 let hir_id = id.take()
4834 .map(|id| self.lower_node_id(id))
4835 .unwrap_or_else(|| self.next_id());
4839 node: hir::StmtKind::Item(item_id),
4845 StmtKind::Expr(ref e) => {
4847 hir_id: self.lower_node_id(s.id),
4848 node: hir::StmtKind::Expr(P(self.lower_expr(e))),
4852 StmtKind::Semi(ref e) => {
4854 hir_id: self.lower_node_id(s.id),
4855 node: hir::StmtKind::Semi(P(self.lower_expr(e))),
4859 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4863 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4865 CaptureBy::Value => hir::CaptureByValue,
4866 CaptureBy::Ref => hir::CaptureByRef,
4870 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4871 /// the address space of that item instead of the item currently being
4872 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4873 /// lower a `Visibility` value although we haven't lowered the owning
4874 /// `ImplItem` in question yet.
4875 fn lower_visibility(
4878 explicit_owner: Option<NodeId>,
4879 ) -> hir::Visibility {
4880 let node = match v.node {
4881 VisibilityKind::Public => hir::VisibilityKind::Public,
4882 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4883 VisibilityKind::Restricted { ref path, id } => {
4884 debug!("lower_visibility: restricted path id = {:?}", id);
4885 let lowered_id = if let Some(owner) = explicit_owner {
4886 self.lower_node_id_with_owner(id, owner)
4888 self.lower_node_id(id)
4890 let def = self.expect_full_def(id);
4891 let def = self.lower_def(def);
4892 hir::VisibilityKind::Restricted {
4893 path: P(self.lower_path_extra(
4896 ParamMode::Explicit,
4902 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4904 respan(v.span, node)
4907 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4909 Defaultness::Default => hir::Defaultness::Default {
4910 has_value: has_value,
4912 Defaultness::Final => {
4914 hir::Defaultness::Final
4919 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4921 BlockCheckMode::Default => hir::DefaultBlock,
4922 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4926 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4928 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4929 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4930 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4931 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4935 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4937 CompilerGenerated => hir::CompilerGenerated,
4938 UserProvided => hir::UserProvided,
4942 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4944 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4945 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4949 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4951 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4952 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4956 // Helper methods for building HIR.
4958 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4967 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4969 hir_id: self.next_id(),
4973 is_shorthand: false,
4977 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4978 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4979 P(self.expr(span, expr_break, attrs))
4986 args: hir::HirVec<hir::Expr>,
4988 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4991 fn expr_ident(&mut self, span: Span, ident: Ident, binding: hir::HirId) -> hir::Expr {
4992 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4995 fn expr_ident_with_attrs(
4999 binding: hir::HirId,
5000 attrs: ThinVec<Attribute>,
5002 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
5006 def: Def::Local(binding),
5007 segments: hir_vec![hir::PathSegment::from_ident(ident)],
5011 self.expr(span, expr_path, attrs)
5014 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
5015 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
5021 components: &[&str],
5022 params: Option<P<hir::GenericArgs>>,
5023 attrs: ThinVec<Attribute>,
5025 let path = self.std_path(span, components, params, true);
5028 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
5033 /// Wrap the given `expr` in `hir::ExprKind::Use`.
5035 /// In terms of drop order, it has the same effect as
5036 /// wrapping `expr` in `{ let _t = $expr; _t }` but
5037 /// should provide better compile-time performance.
5039 /// The drop order can be important in e.g. `if expr { .. }`.
5040 fn expr_use(&mut self, span: Span, expr: P<hir::Expr>, attrs: ThinVec<Attribute>) -> hir::Expr {
5041 self.expr(span, hir::ExprKind::Use(expr), attrs)
5048 arms: hir::HirVec<hir::Arm>,
5049 source: hir::MatchSource,
5051 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
5054 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
5055 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
5058 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
5059 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
5062 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
5064 hir_id: self.next_id(),
5074 ex: Option<P<hir::Expr>>,
5076 source: hir::LocalSource,
5078 let local = hir::Local {
5082 hir_id: self.next_id(),
5084 attrs: ThinVec::new(),
5089 hir_id: self.next_id(),
5090 node: hir::StmtKind::Local(P(local)),
5095 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
5096 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
5102 stmts: hir::HirVec<hir::Stmt>,
5103 expr: Option<P<hir::Expr>>,
5108 hir_id: self.next_id(),
5109 rules: hir::DefaultBlock,
5111 targeted_by_break: false,
5115 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5116 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
5119 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5120 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
5123 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5124 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
5127 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
5128 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
5134 components: &[&str],
5135 subpats: hir::HirVec<P<hir::Pat>>,
5137 let path = self.std_path(span, components, None, true);
5138 let qpath = hir::QPath::Resolved(None, P(path));
5139 let pt = if subpats.is_empty() {
5140 hir::PatKind::Path(qpath)
5142 hir::PatKind::TupleStruct(qpath, subpats, None)
5147 fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<hir::Pat>, hir::HirId) {
5148 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
5151 fn pat_ident_binding_mode(
5155 bm: hir::BindingAnnotation,
5156 ) -> (P<hir::Pat>, hir::HirId) {
5157 let hir_id = self.next_id();
5162 node: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
5169 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
5170 self.pat(span, hir::PatKind::Wild)
5173 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
5175 hir_id: self.next_id(),
5181 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
5182 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
5183 /// The path is also resolved according to `is_value`.
5187 components: &[&str],
5188 params: Option<P<hir::GenericArgs>>,
5191 let mut path = self.resolver
5192 .resolve_str_path(span, self.crate_root, components, is_value);
5193 path.segments.last_mut().unwrap().args = params;
5196 for seg in path.segments.iter_mut() {
5197 if seg.hir_id.is_some() {
5198 seg.hir_id = Some(self.next_id());
5204 fn ty_path(&mut self, mut hir_id: hir::HirId, span: Span, qpath: hir::QPath) -> hir::Ty {
5205 let node = match qpath {
5206 hir::QPath::Resolved(None, path) => {
5207 // Turn trait object paths into `TyKind::TraitObject` instead.
5209 Def::Trait(_) | Def::TraitAlias(_) => {
5210 let principal = hir::PolyTraitRef {
5211 bound_generic_params: hir::HirVec::new(),
5212 trait_ref: hir::TraitRef {
5213 path: path.and_then(|path| path),
5219 // The original ID is taken by the `PolyTraitRef`,
5220 // so the `Ty` itself needs a different one.
5221 hir_id = self.next_id();
5222 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
5224 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
5227 _ => hir::TyKind::Path(qpath),
5236 /// Invoked to create the lifetime argument for a type `&T`
5237 /// with no explicit lifetime.
5238 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
5239 match self.anonymous_lifetime_mode {
5240 // Intercept when we are in an impl header or async fn and introduce an in-band
5242 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
5244 AnonymousLifetimeMode::CreateParameter => {
5245 let fresh_name = self.collect_fresh_in_band_lifetime(span);
5247 hir_id: self.next_id(),
5249 name: hir::LifetimeName::Param(fresh_name),
5253 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5255 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5257 AnonymousLifetimeMode::Replace(replacement) => {
5258 self.new_replacement_lifetime(replacement, span)
5263 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
5264 /// return a "error lifetime".
5265 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
5266 let (id, msg, label) = match id {
5267 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
5270 self.sess.next_node_id(),
5271 "`&` without an explicit lifetime name cannot be used here",
5272 "explicit lifetime name needed here",
5276 let mut err = struct_span_err!(
5283 err.span_label(span, label);
5286 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5289 /// Invoked to create the lifetime argument(s) for a path like
5290 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
5291 /// sorts of cases are deprecated. This may therefore report a warning or an
5292 /// error, depending on the mode.
5293 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
5295 .map(|_| self.elided_path_lifetime(span))
5299 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
5300 match self.anonymous_lifetime_mode {
5301 // N.B., We intentionally ignore the create-parameter mode here
5302 // and instead "pass through" to resolve-lifetimes, which will then
5303 // report an error. This is because we don't want to support
5304 // impl elision for deprecated forms like
5306 // impl Foo for std::cell::Ref<u32> // note lack of '_
5307 AnonymousLifetimeMode::CreateParameter |
5308 // This is the normal case.
5309 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5311 AnonymousLifetimeMode::Replace(replacement) => {
5312 self.new_replacement_lifetime(replacement, span)
5315 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5319 /// Invoked to create the lifetime argument(s) for an elided trait object
5320 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
5321 /// when the bound is written, even if it is written with `'_` like in
5322 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
5323 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
5324 match self.anonymous_lifetime_mode {
5325 // NB. We intentionally ignore the create-parameter mode here.
5326 // and instead "pass through" to resolve-lifetimes, which will apply
5327 // the object-lifetime-defaulting rules. Elided object lifetime defaults
5328 // do not act like other elided lifetimes. In other words, given this:
5330 // impl Foo for Box<dyn Debug>
5332 // we do not introduce a fresh `'_` to serve as the bound, but instead
5333 // ultimately translate to the equivalent of:
5335 // impl Foo for Box<dyn Debug + 'static>
5337 // `resolve_lifetime` has the code to make that happen.
5338 AnonymousLifetimeMode::CreateParameter => {}
5340 AnonymousLifetimeMode::ReportError => {
5341 // ReportError applies to explicit use of `'_`.
5344 // This is the normal case.
5345 AnonymousLifetimeMode::PassThrough => {}
5347 // We don't need to do any replacement here as this lifetime
5348 // doesn't refer to an elided lifetime elsewhere in the function
5350 AnonymousLifetimeMode::Replace(_) => {}
5353 self.new_implicit_lifetime(span)
5356 fn new_replacement_lifetime(
5358 replacement: LtReplacement,
5360 ) -> hir::Lifetime {
5361 let hir_id = self.next_id();
5362 self.replace_elided_lifetime(hir_id, span, replacement)
5365 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
5367 hir_id: self.next_id(),
5369 name: hir::LifetimeName::Implicit,
5373 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
5374 self.sess.buffer_lint_with_diagnostic(
5375 builtin::BARE_TRAIT_OBJECTS,
5378 "trait objects without an explicit `dyn` are deprecated",
5379 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
5383 fn wrap_in_try_constructor(
5385 method: &'static str,
5387 unstable_span: Span,
5389 let path = &["ops", "Try", method];
5390 let from_err = P(self.expr_std_path(unstable_span, path, None,
5392 P(self.expr_call(e.span, from_err, hir_vec![e]))
5396 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5397 // Sorting by span ensures that we get things in order within a
5398 // file, and also puts the files in a sensible order.
5399 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5400 body_ids.sort_by_key(|b| bodies[b].value.span);