1 //! Lowers the AST to the HIR.
3 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
4 //! much like a fold. Where lowering involves a bit more work things get more
5 //! interesting and there are some invariants you should know about. These mostly
6 //! concern spans and IDs.
8 //! Spans are assigned to AST nodes during parsing and then are modified during
9 //! expansion to indicate the origin of a node and the process it went through
10 //! being expanded. IDs are assigned to AST nodes just before lowering.
12 //! For the simpler lowering steps, IDs and spans should be preserved. Unlike
13 //! expansion we do not preserve the process of lowering in the spans, so spans
14 //! should not be modified here. When creating a new node (as opposed to
15 //! 'folding' an existing one), then you create a new ID using `next_id()`.
17 //! You must ensure that IDs are unique. That means that you should only use the
18 //! ID from an AST node in a single HIR node (you can assume that AST node IDs
19 //! are unique). Every new node must have a unique ID. Avoid cloning HIR nodes.
20 //! If you do, you must then set the new node's ID to a fresh one.
22 //! Spans are used for error messages and for tools to map semantics back to
23 //! source code. It is therefore not as important with spans as IDs to be strict
24 //! about use (you can't break the compiler by screwing up a span). Obviously, a
25 //! HIR node can only have a single span. But multiple nodes can have the same
26 //! span and spans don't need to be kept in order, etc. Where code is preserved
27 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
28 //! new it is probably best to give a span for the whole AST node being lowered.
29 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
30 //! get confused if the spans from leaf AST nodes occur in multiple places
31 //! in the HIR, especially for multiple identifiers.
33 use crate::dep_graph::DepGraph;
34 use crate::hir::{self, ParamName};
35 use crate::hir::HirVec;
36 use crate::hir::map::{DefKey, DefPathData, Definitions};
37 use crate::hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX};
38 use crate::hir::def::{Def, PathResolution, PerNS};
39 use crate::hir::{GenericArg, ConstArg};
40 use crate::lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
41 ELIDED_LIFETIMES_IN_PATHS};
42 use crate::middle::cstore::CrateStore;
43 use crate::session::Session;
44 use crate::session::config::nightly_options;
45 use crate::util::common::FN_OUTPUT_NAME;
46 use crate::util::nodemap::{DefIdMap, NodeMap};
47 use errors::Applicability;
48 use rustc_data_structures::fx::FxHashSet;
49 use rustc_data_structures::indexed_vec::IndexVec;
50 use rustc_data_structures::thin_vec::ThinVec;
51 use rustc_data_structures::sync::Lrc;
53 use std::collections::{BTreeSet, BTreeMap};
55 use smallvec::SmallVec;
60 use syntax::ext::hygiene::{Mark, SyntaxContext};
61 use syntax::print::pprust;
63 use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned};
64 use syntax::std_inject;
65 use syntax::symbol::{keywords, Symbol};
66 use syntax::tokenstream::{TokenStream, TokenTree};
67 use syntax::parse::token::Token;
68 use syntax::visit::{self, Visitor};
71 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
73 pub struct LoweringContext<'a> {
74 crate_root: Option<&'static str>,
76 /// Used to assign ids to HIR nodes that do not directly correspond to an AST node.
79 cstore: &'a dyn CrateStore,
81 resolver: &'a mut dyn Resolver,
83 /// The items being lowered are collected here.
84 items: BTreeMap<hir::HirId, hir::Item>,
86 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
87 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
88 bodies: BTreeMap<hir::BodyId, hir::Body>,
89 exported_macros: Vec<hir::MacroDef>,
91 trait_impls: BTreeMap<DefId, Vec<hir::HirId>>,
93 modules: BTreeMap<NodeId, hir::ModuleItems>,
97 catch_scopes: Vec<NodeId>,
98 loop_scopes: Vec<NodeId>,
99 is_in_loop_condition: bool,
100 is_in_trait_impl: bool,
102 /// What to do when we encounter either an "anonymous lifetime
103 /// reference". The term "anonymous" is meant to encompass both
104 /// `'_` lifetimes as well as fully elided cases where nothing is
105 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
106 anonymous_lifetime_mode: AnonymousLifetimeMode,
108 /// Used to create lifetime definitions from in-band lifetime usages.
109 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
110 /// When a named lifetime is encountered in a function or impl header and
111 /// has not been defined
112 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
113 /// to this list. The results of this list are then added to the list of
114 /// lifetime definitions in the corresponding impl or function generics.
115 lifetimes_to_define: Vec<(Span, ParamName)>,
117 /// Whether or not in-band lifetimes are being collected. This is used to
118 /// indicate whether or not we're in a place where new lifetimes will result
119 /// in in-band lifetime definitions, such a function or an impl header,
120 /// including implicit lifetimes from `impl_header_lifetime_elision`.
121 is_collecting_in_band_lifetimes: bool,
123 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
124 /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
125 /// against this list to see if it is already in-scope, or if a definition
126 /// needs to be created for it.
127 in_scope_lifetimes: Vec<Ident>,
129 current_module: NodeId,
131 type_def_lifetime_params: DefIdMap<usize>,
133 current_hir_id_owner: Vec<(DefIndex, u32)>,
134 item_local_id_counters: NodeMap<u32>,
135 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
139 /// Resolve a path generated by the lowerer when expanding `for`, `if let`, etc.
146 /// Obtain the resolution for a `NodeId`.
147 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
149 /// Obtain the possible resolutions for the given `use` statement.
150 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
152 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
153 /// This should only return `None` during testing.
154 fn definitions(&mut self) -> &mut Definitions;
156 /// Given suffix `["b", "c", "d"]`, creates a HIR path for `[::crate_root]::b::c::d` and
157 /// resolves it based on `is_value`.
161 crate_root: Option<&str>,
168 enum ImplTraitContext<'a> {
169 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
170 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
171 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
173 /// Newly generated parameters should be inserted into the given `Vec`.
174 Universal(&'a mut Vec<hir::GenericParam>),
176 /// Treat `impl Trait` as shorthand for a new existential parameter.
177 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
178 /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
180 /// We optionally store a `DefId` for the parent item here so we can look up necessary
181 /// information later. It is `None` when no information about the context should be stored,
182 /// e.g., for consts and statics.
183 Existential(Option<DefId>),
185 /// `impl Trait` is not accepted in this position.
186 Disallowed(ImplTraitPosition),
189 /// Position in which `impl Trait` is disallowed. Used for error reporting.
190 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
191 enum ImplTraitPosition {
196 impl<'a> ImplTraitContext<'a> {
198 fn disallowed() -> Self {
199 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
202 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
203 use self::ImplTraitContext::*;
205 Universal(params) => Universal(params),
206 Existential(did) => Existential(*did),
207 Disallowed(pos) => Disallowed(*pos),
214 cstore: &dyn CrateStore,
215 dep_graph: &DepGraph,
217 resolver: &mut dyn Resolver,
219 // We're constructing the HIR here; we don't care what we will
220 // read, since we haven't even constructed the *input* to
222 dep_graph.assert_ignored();
225 crate_root: std_inject::injected_crate_name(),
229 items: BTreeMap::new(),
230 trait_items: BTreeMap::new(),
231 impl_items: BTreeMap::new(),
232 bodies: BTreeMap::new(),
233 trait_impls: BTreeMap::new(),
234 modules: BTreeMap::new(),
235 exported_macros: Vec::new(),
236 catch_scopes: Vec::new(),
237 loop_scopes: Vec::new(),
238 is_in_loop_condition: false,
239 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
240 type_def_lifetime_params: Default::default(),
241 current_module: CRATE_NODE_ID,
242 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
243 item_local_id_counters: Default::default(),
244 node_id_to_hir_id: IndexVec::new(),
246 is_in_trait_impl: false,
247 lifetimes_to_define: Vec::new(),
248 is_collecting_in_band_lifetimes: false,
249 in_scope_lifetimes: Vec::new(),
253 #[derive(Copy, Clone, PartialEq)]
255 /// Any path in a type context.
257 /// The `module::Type` in `module::Type::method` in an expression.
262 struct LoweredNodeId {
267 enum ParenthesizedGenericArgs {
273 /// What to do when we encounter an **anonymous** lifetime
274 /// reference. Anonymous lifetime references come in two flavors. You
275 /// have implicit, or fully elided, references to lifetimes, like the
276 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
277 /// or `Ref<'_, T>`. These often behave the same, but not always:
279 /// - certain usages of implicit references are deprecated, like
280 /// `Ref<T>`, and we sometimes just give hard errors in those cases
282 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
283 /// the same as `Box<dyn Foo + '_>`.
285 /// We describe the effects of the various modes in terms of three cases:
287 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
288 /// of a `&` (e.g., the missing lifetime in something like `&T`)
289 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
290 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
291 /// elided bounds follow special rules. Note that this only covers
292 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
293 /// '_>` is a case of "modern" elision.
294 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
295 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
296 /// non-deprecated equivalent.
298 /// Currently, the handling of lifetime elision is somewhat spread out
299 /// between HIR lowering and -- as described below -- the
300 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
301 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
302 /// everything into HIR lowering.
303 #[derive(Copy, Clone)]
304 enum AnonymousLifetimeMode {
305 /// For **Modern** cases, create a new anonymous region parameter
306 /// and reference that.
308 /// For **Dyn Bound** cases, pass responsibility to
309 /// `resolve_lifetime` code.
311 /// For **Deprecated** cases, report an error.
314 /// Give a hard error when either `&` or `'_` is written. Used to
315 /// rule out things like `where T: Foo<'_>`. Does not imply an
316 /// error on default object bounds (e.g., `Box<dyn Foo>`).
319 /// Pass responsibility to `resolve_lifetime` code for all cases.
322 /// Used in the return types of `async fn` where there exists
323 /// exactly one argument-position elided lifetime.
325 /// In `async fn`, we lower the arguments types using the `CreateParameter`
326 /// mode, meaning that non-`dyn` elided lifetimes are assigned a fresh name.
327 /// If any corresponding elided lifetimes appear in the output, we need to
328 /// replace them with references to the fresh name assigned to the corresponding
329 /// elided lifetime in the arguments.
331 /// For **Modern cases**, replace the anonymous parameter with a
332 /// reference to a specific freshly-named lifetime that was
333 /// introduced in argument
335 /// For **Dyn Bound** cases, pass responsibility to
336 /// `resole_lifetime` code.
337 Replace(LtReplacement),
340 /// The type of elided lifetime replacement to perform on `async fn` return types.
341 #[derive(Copy, Clone)]
343 /// Fresh name introduced by the single non-dyn elided lifetime
344 /// in the arguments of the async fn.
347 /// There is no single non-dyn elided lifetime because no lifetimes
348 /// appeared in the arguments.
351 /// There is no single non-dyn elided lifetime because multiple
352 /// lifetimes appeared in the arguments.
356 /// Calculates the `LtReplacement` to use for elided lifetimes in the return
357 /// type based on the fresh elided lifetimes introduced in argument position.
358 fn get_elided_lt_replacement(arg_position_lifetimes: &[(Span, ParamName)]) -> LtReplacement {
359 match arg_position_lifetimes {
360 [] => LtReplacement::NoLifetimes,
361 [(_span, param)] => LtReplacement::Some(*param),
362 _ => LtReplacement::MultipleLifetimes,
366 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[NodeId; 1]> }
368 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
369 fn visit_ty(&mut self, ty: &'a Ty) {
375 TyKind::ImplTrait(id, _) => self.ids.push(id),
378 visit::walk_ty(self, ty);
381 fn visit_path_segment(
384 path_segment: &'v PathSegment,
386 if let Some(ref p) = path_segment.args {
387 if let GenericArgs::Parenthesized(_) = **p {
391 visit::walk_path_segment(self, path_span, path_segment)
395 impl<'a> LoweringContext<'a> {
396 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
397 /// Full-crate AST visitor that inserts into a fresh
398 /// `LoweringContext` any information that may be
399 /// needed from arbitrary locations in the crate,
400 /// e.g., the number of lifetime generic parameters
401 /// declared for every type and trait definition.
402 struct MiscCollector<'lcx, 'interner: 'lcx> {
403 lctx: &'lcx mut LoweringContext<'interner>,
404 hir_id_owner: Option<NodeId>,
407 impl MiscCollector<'_, '_> {
408 fn allocate_use_tree_hir_id_counters(
414 UseTreeKind::Simple(_, id1, id2) => {
415 for &id in &[id1, id2] {
416 self.lctx.resolver.definitions().create_def_with_parent(
420 DefIndexAddressSpace::High,
424 self.lctx.allocate_hir_id_counter(id);
427 UseTreeKind::Glob => (),
428 UseTreeKind::Nested(ref trees) => {
429 for &(ref use_tree, id) in trees {
430 let hir_id = self.lctx.allocate_hir_id_counter(id).hir_id;
431 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
437 fn with_hir_id_owner<F, T>(&mut self, owner: Option<NodeId>, f: F) -> T
439 F: FnOnce(&mut Self) -> T,
441 let old = mem::replace(&mut self.hir_id_owner, owner);
443 self.hir_id_owner = old;
448 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
449 fn visit_pat(&mut self, p: &'lcx Pat) {
451 // Doesn't generate a HIR node
452 PatKind::Paren(..) => {},
454 if let Some(owner) = self.hir_id_owner {
455 self.lctx.lower_node_id_with_owner(p.id, owner);
460 visit::walk_pat(self, p)
463 fn visit_fn(&mut self, fk: visit::FnKind<'lcx>, fd: &'lcx FnDecl, s: Span, _: NodeId) {
464 if fk.header().map(|h| h.asyncness.node.is_async()).unwrap_or(false) {
465 // Don't visit the original pattern for async functions as it will be
467 for arg in &fd.inputs {
468 self.visit_ty(&arg.ty)
470 self.visit_fn_ret_ty(&fd.output);
473 visit::FnKind::ItemFn(_, decl, _, body) => {
474 self.visit_fn_header(decl);
475 self.visit_block(body)
477 visit::FnKind::Method(_, sig, _, body) => {
478 self.visit_fn_header(&sig.header);
479 self.visit_block(body)
481 visit::FnKind::Closure(body) => self.visit_expr(body),
484 visit::walk_fn(self, fk, fd, s)
488 fn visit_item(&mut self, item: &'lcx Item) {
489 let hir_id = self.lctx.allocate_hir_id_counter(item.id).hir_id;
492 ItemKind::Struct(_, ref generics)
493 | ItemKind::Union(_, ref generics)
494 | ItemKind::Enum(_, ref generics)
495 | ItemKind::Ty(_, ref generics)
496 | ItemKind::Existential(_, ref generics)
497 | ItemKind::Trait(_, _, ref generics, ..) => {
498 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
502 .filter(|param| match param.kind {
503 ast::GenericParamKind::Lifetime { .. } => true,
507 self.lctx.type_def_lifetime_params.insert(def_id, count);
509 ItemKind::Use(ref use_tree) => {
510 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
515 self.with_hir_id_owner(Some(item.id), |this| {
516 visit::walk_item(this, item);
520 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
521 self.lctx.allocate_hir_id_counter(item.id);
524 TraitItemKind::Method(_, None) => {
525 // Ignore patterns in trait methods without bodies
526 self.with_hir_id_owner(None, |this| {
527 visit::walk_trait_item(this, item)
530 _ => self.with_hir_id_owner(Some(item.id), |this| {
531 visit::walk_trait_item(this, item);
536 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
537 self.lctx.allocate_hir_id_counter(item.id);
538 self.with_hir_id_owner(Some(item.id), |this| {
539 visit::walk_impl_item(this, item);
543 fn visit_foreign_item(&mut self, i: &'lcx ForeignItem) {
544 // Ignore patterns in foreign items
545 self.with_hir_id_owner(None, |this| {
546 visit::walk_foreign_item(this, i)
550 fn visit_ty(&mut self, t: &'lcx Ty) {
552 // Mirrors the case in visit::walk_ty
553 TyKind::BareFn(ref f) => {
559 // Mirrors visit::walk_fn_decl
560 for argument in &f.decl.inputs {
561 // We don't lower the ids of argument patterns
562 self.with_hir_id_owner(None, |this| {
563 this.visit_pat(&argument.pat);
565 self.visit_ty(&argument.ty)
567 self.visit_fn_ret_ty(&f.decl.output)
569 _ => visit::walk_ty(self, t),
574 struct ItemLowerer<'lcx, 'interner: 'lcx> {
575 lctx: &'lcx mut LoweringContext<'interner>,
578 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
579 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
581 F: FnOnce(&mut Self),
583 let old = self.lctx.is_in_trait_impl;
584 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
590 self.lctx.is_in_trait_impl = old;
594 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
595 fn visit_mod(&mut self, m: &'lcx Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
596 self.lctx.modules.insert(n, hir::ModuleItems {
597 items: BTreeSet::new(),
598 trait_items: BTreeSet::new(),
599 impl_items: BTreeSet::new(),
602 let old = self.lctx.current_module;
603 self.lctx.current_module = n;
604 visit::walk_mod(self, m);
605 self.lctx.current_module = old;
608 fn visit_item(&mut self, item: &'lcx Item) {
609 let mut item_hir_id = None;
610 self.lctx.with_hir_id_owner(item.id, |lctx| {
611 if let Some(hir_item) = lctx.lower_item(item) {
612 item_hir_id = Some(hir_item.hir_id);
613 lctx.insert_item(hir_item);
617 if let Some(hir_id) = item_hir_id {
618 let item_generics = match self.lctx.items.get(&hir_id).unwrap().node {
619 hir::ItemKind::Impl(_, _, _, ref generics, ..)
620 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
621 generics.params.clone()
626 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
627 let this = &mut ItemLowerer { lctx: this };
628 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
629 this.with_trait_impl_ref(opt_trait_ref, |this| {
630 visit::walk_item(this, item)
633 visit::walk_item(this, item);
639 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
640 self.lctx.with_hir_id_owner(item.id, |lctx| {
641 let hir_item = lctx.lower_trait_item(item);
642 let id = hir::TraitItemId { hir_id: hir_item.hir_id };
643 lctx.trait_items.insert(id, hir_item);
644 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
647 visit::walk_trait_item(self, item);
650 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
651 self.lctx.with_hir_id_owner(item.id, |lctx| {
652 let hir_item = lctx.lower_impl_item(item);
653 let id = hir::ImplItemId { hir_id: hir_item.hir_id };
654 lctx.impl_items.insert(id, hir_item);
655 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
657 visit::walk_impl_item(self, item);
661 self.lower_node_id(CRATE_NODE_ID);
662 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
664 visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
665 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
667 let module = self.lower_mod(&c.module);
668 let attrs = self.lower_attrs(&c.attrs);
669 let body_ids = body_ids(&self.bodies);
673 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
679 exported_macros: hir::HirVec::from(self.exported_macros),
681 trait_items: self.trait_items,
682 impl_items: self.impl_items,
685 trait_impls: self.trait_impls,
686 modules: self.modules,
690 fn insert_item(&mut self, item: hir::Item) {
691 let id = item.hir_id;
692 // FIXME: Use debug_asset-rt
693 assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
694 self.items.insert(id, item);
695 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
698 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> LoweredNodeId {
699 // Setup the counter if needed
700 self.item_local_id_counters.entry(owner).or_insert(0);
701 // Always allocate the first `HirId` for the owner itself.
702 let lowered = self.lower_node_id_with_owner(owner, owner);
703 debug_assert_eq!(lowered.hir_id.local_id.as_u32(), 0);
707 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
709 F: FnOnce(&mut Self) -> hir::HirId,
711 if ast_node_id == DUMMY_NODE_ID {
712 return LoweredNodeId {
713 node_id: DUMMY_NODE_ID,
714 hir_id: hir::DUMMY_HIR_ID,
718 let min_size = ast_node_id.as_usize() + 1;
720 if min_size > self.node_id_to_hir_id.len() {
721 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
724 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
726 if existing_hir_id == hir::DUMMY_HIR_ID {
727 // Generate a new `HirId`.
728 let hir_id = alloc_hir_id(self);
729 self.node_id_to_hir_id[ast_node_id] = hir_id;
731 node_id: ast_node_id,
736 node_id: ast_node_id,
737 hir_id: existing_hir_id,
742 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
744 F: FnOnce(&mut Self) -> T,
746 let counter = self.item_local_id_counters
747 .insert(owner, HIR_ID_COUNTER_LOCKED)
748 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
749 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
750 self.current_hir_id_owner.push((def_index, counter));
752 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
754 debug_assert!(def_index == new_def_index);
755 debug_assert!(new_counter >= counter);
757 let prev = self.item_local_id_counters
758 .insert(owner, new_counter)
760 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
764 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
765 /// the `LoweringContext`'s `NodeId => HirId` map.
766 /// Take care not to call this method if the resulting `HirId` is then not
767 /// actually used in the HIR, as that would trigger an assertion in the
768 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
769 /// properly. Calling the method twice with the same `NodeId` is fine though.
770 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
771 self.lower_node_id_generic(ast_node_id, |this| {
772 let &mut (def_index, ref mut local_id_counter) =
773 this.current_hir_id_owner.last_mut().unwrap();
774 let local_id = *local_id_counter;
775 *local_id_counter += 1;
778 local_id: hir::ItemLocalId::from_u32(local_id),
783 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
784 self.lower_node_id_generic(ast_node_id, |this| {
785 let local_id_counter = this
786 .item_local_id_counters
788 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
789 let local_id = *local_id_counter;
791 // We want to be sure not to modify the counter in the map while it
792 // is also on the stack. Otherwise we'll get lost updates when writing
793 // back from the stack to the map.
794 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
796 *local_id_counter += 1;
800 .opt_def_index(owner)
801 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
802 that do not belong to the current owner");
806 local_id: hir::ItemLocalId::from_u32(local_id),
811 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
812 let body = hir::Body {
813 arguments: decl.map_or(hir_vec![], |decl| {
814 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
816 is_generator: self.is_generator,
820 self.bodies.insert(id, body);
824 fn next_id(&mut self) -> LoweredNodeId {
825 self.lower_node_id(self.sess.next_node_id())
828 fn lower_def(&mut self, def: Def<NodeId>) -> Def {
830 self.lower_node_id_generic(id, |_| {
831 panic!("expected node_id to be lowered already for def {:#?}", def)
836 fn expect_full_def(&mut self, id: NodeId) -> Def<NodeId> {
837 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
838 if pr.unresolved_segments() != 0 {
839 bug!("path not fully resolved: {:?}", pr);
845 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Def<NodeId>> {
846 self.resolver.get_import(id).present_items().map(|pr| {
847 if pr.unresolved_segments() != 0 {
848 bug!("path not fully resolved: {:?}", pr);
854 fn diagnostic(&self) -> &errors::Handler {
855 self.sess.diagnostic()
858 fn str_to_ident(&self, s: &'static str) -> Ident {
859 Ident::with_empty_ctxt(Symbol::gensym(s))
862 /// Reuses the span but adds information like the kind of the desugaring and features that are
863 /// allowed inside this span.
864 fn mark_span_with_reason(
866 reason: CompilerDesugaringKind,
868 allow_internal_unstable: Option<Lrc<[Symbol]>>,
870 let mark = Mark::fresh(Mark::root());
871 mark.set_expn_info(source_map::ExpnInfo {
873 def_site: Some(span),
874 format: source_map::CompilerDesugaring(reason),
875 allow_internal_unstable,
876 allow_internal_unsafe: false,
877 local_inner_macros: false,
878 edition: source_map::hygiene::default_edition(),
880 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
883 fn with_anonymous_lifetime_mode<R>(
885 anonymous_lifetime_mode: AnonymousLifetimeMode,
886 op: impl FnOnce(&mut Self) -> R,
888 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
889 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
890 let result = op(self);
891 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
895 /// Creates a new hir::GenericParam for every new lifetime and
896 /// type parameter encountered while evaluating `f`. Definitions
897 /// are created with the parent provided. If no `parent_id` is
898 /// provided, no definitions will be returned.
900 /// Presuming that in-band lifetimes are enabled, then
901 /// `self.anonymous_lifetime_mode` will be updated to match the
902 /// argument while `f` is running (and restored afterwards).
903 fn collect_in_band_defs<T, F>(
906 anonymous_lifetime_mode: AnonymousLifetimeMode,
908 ) -> (Vec<hir::GenericParam>, T)
910 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
912 assert!(!self.is_collecting_in_band_lifetimes);
913 assert!(self.lifetimes_to_define.is_empty());
914 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
916 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
917 self.is_collecting_in_band_lifetimes = true;
919 let (in_band_ty_params, res) = f(self);
921 self.is_collecting_in_band_lifetimes = false;
922 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
924 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
926 let params = lifetimes_to_define
928 .map(|(span, hir_name)| self.lifetime_to_generic_param(
929 span, hir_name, parent_id.index,
931 .chain(in_band_ty_params.into_iter())
937 /// Converts a lifetime into a new generic parameter.
938 fn lifetime_to_generic_param(
942 parent_index: DefIndex,
943 ) -> hir::GenericParam {
944 let LoweredNodeId { node_id, hir_id } = self.next_id();
946 // Get the name we'll use to make the def-path. Note
947 // that collisions are ok here and this shouldn't
948 // really show up for end-user.
949 let (str_name, kind) = match hir_name {
950 ParamName::Plain(ident) => (
951 ident.as_interned_str(),
952 hir::LifetimeParamKind::InBand,
954 ParamName::Fresh(_) => (
955 keywords::UnderscoreLifetime.name().as_interned_str(),
956 hir::LifetimeParamKind::Elided,
958 ParamName::Error => (
959 keywords::UnderscoreLifetime.name().as_interned_str(),
960 hir::LifetimeParamKind::Error,
964 // Add a definition for the in-band lifetime def.
965 self.resolver.definitions().create_def_with_parent(
968 DefPathData::LifetimeParam(str_name),
969 DefIndexAddressSpace::High,
980 pure_wrt_drop: false,
981 kind: hir::GenericParamKind::Lifetime { kind }
985 /// When there is a reference to some lifetime `'a`, and in-band
986 /// lifetimes are enabled, then we want to push that lifetime into
987 /// the vector of names to define later. In that case, it will get
988 /// added to the appropriate generics.
989 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
990 if !self.is_collecting_in_band_lifetimes {
994 if !self.sess.features_untracked().in_band_lifetimes {
998 if self.in_scope_lifetimes.contains(&ident.modern()) {
1002 let hir_name = ParamName::Plain(ident);
1004 if self.lifetimes_to_define.iter()
1005 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
1009 self.lifetimes_to_define.push((ident.span, hir_name));
1012 /// When we have either an elided or `'_` lifetime in an impl
1013 /// header, we convert it to an in-band lifetime.
1014 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
1015 assert!(self.is_collecting_in_band_lifetimes);
1016 let index = self.lifetimes_to_define.len();
1017 let hir_name = ParamName::Fresh(index);
1018 self.lifetimes_to_define.push((span, hir_name));
1022 // Evaluates `f` with the lifetimes in `params` in-scope.
1023 // This is used to track which lifetimes have already been defined, and
1024 // which are new in-band lifetimes that need to have a definition created
1026 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
1028 F: FnOnce(&mut LoweringContext<'_>) -> T,
1030 let old_len = self.in_scope_lifetimes.len();
1031 let lt_def_names = params.iter().filter_map(|param| match param.kind {
1032 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
1035 self.in_scope_lifetimes.extend(lt_def_names);
1039 self.in_scope_lifetimes.truncate(old_len);
1043 // Same as the method above, but accepts `hir::GenericParam`s
1044 // instead of `ast::GenericParam`s.
1045 // This should only be used with generics that have already had their
1046 // in-band lifetimes added. In practice, this means that this function is
1047 // only used when lowering a child item of a trait or impl.
1048 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
1049 params: &HirVec<hir::GenericParam>,
1052 F: FnOnce(&mut LoweringContext<'_>) -> T,
1054 let old_len = self.in_scope_lifetimes.len();
1055 let lt_def_names = params.iter().filter_map(|param| match param.kind {
1056 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
1059 self.in_scope_lifetimes.extend(lt_def_names);
1063 self.in_scope_lifetimes.truncate(old_len);
1067 /// Appends in-band lifetime defs and argument-position `impl
1068 /// Trait` defs to the existing set of generics.
1070 /// Presuming that in-band lifetimes are enabled, then
1071 /// `self.anonymous_lifetime_mode` will be updated to match the
1072 /// argument while `f` is running (and restored afterwards).
1073 fn add_in_band_defs<F, T>(
1075 generics: &Generics,
1077 anonymous_lifetime_mode: AnonymousLifetimeMode,
1079 ) -> (hir::Generics, T)
1081 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
1083 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
1086 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
1087 let mut params = Vec::new();
1088 // Note: it is necessary to lower generics *before* calling `f`.
1089 // When lowering `async fn`, there's a final step when lowering
1090 // the return type that assumes that all in-scope lifetimes have
1091 // already been added to either `in_scope_lifetimes` or
1092 // `lifetimes_to_define`. If we swapped the order of these two,
1093 // in-band-lifetimes introduced by generics or where-clauses
1094 // wouldn't have been added yet.
1095 let generics = this.lower_generics(
1097 ImplTraitContext::Universal(&mut params),
1099 let res = f(this, &mut params);
1100 (params, (generics, res))
1105 lowered_generics.params = lowered_generics
1109 .chain(in_band_defs)
1112 (lowered_generics, res)
1115 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
1117 F: FnOnce(&mut LoweringContext<'_>) -> T,
1119 let len = self.catch_scopes.len();
1120 self.catch_scopes.push(catch_id);
1122 let result = f(self);
1125 self.catch_scopes.len(),
1126 "catch scopes should be added and removed in stack order"
1129 self.catch_scopes.pop().unwrap();
1136 capture_clause: CaptureBy,
1137 closure_node_id: NodeId,
1138 ret_ty: Option<&Ty>,
1139 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1140 ) -> hir::ExprKind {
1141 let prev_is_generator = mem::replace(&mut self.is_generator, true);
1142 let body_expr = body(self);
1143 let span = body_expr.span;
1144 let output = match ret_ty {
1145 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
1146 None => FunctionRetTy::Default(span),
1153 let body_id = self.record_body(body_expr, Some(&decl));
1154 self.is_generator = prev_is_generator;
1156 let capture_clause = self.lower_capture_clause(capture_clause);
1157 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
1158 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
1159 let generator = hir::Expr {
1160 hir_id: closure_hir_id,
1161 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
1162 Some(hir::GeneratorMovability::Static)),
1164 attrs: ThinVec::new(),
1167 let unstable_span = self.mark_span_with_reason(
1168 CompilerDesugaringKind::Async,
1171 Symbol::intern("gen_future"),
1174 let gen_future = self.expr_std_path(
1175 unstable_span, &["future", "from_generator"], None, ThinVec::new());
1176 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
1179 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
1181 F: FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1183 let prev = mem::replace(&mut self.is_generator, false);
1184 let result = f(self);
1185 let r = self.record_body(result, decl);
1186 self.is_generator = prev;
1190 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
1192 F: FnOnce(&mut LoweringContext<'_>) -> T,
1194 // We're no longer in the base loop's condition; we're in another loop.
1195 let was_in_loop_condition = self.is_in_loop_condition;
1196 self.is_in_loop_condition = false;
1198 let len = self.loop_scopes.len();
1199 self.loop_scopes.push(loop_id);
1201 let result = f(self);
1204 self.loop_scopes.len(),
1205 "Loop scopes should be added and removed in stack order"
1208 self.loop_scopes.pop().unwrap();
1210 self.is_in_loop_condition = was_in_loop_condition;
1215 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
1217 F: FnOnce(&mut LoweringContext<'_>) -> T,
1219 let was_in_loop_condition = self.is_in_loop_condition;
1220 self.is_in_loop_condition = true;
1222 let result = f(self);
1224 self.is_in_loop_condition = was_in_loop_condition;
1229 fn with_new_scopes<T, F>(&mut self, f: F) -> T
1231 F: FnOnce(&mut LoweringContext<'_>) -> T,
1233 let was_in_loop_condition = self.is_in_loop_condition;
1234 self.is_in_loop_condition = false;
1236 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
1237 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
1239 self.catch_scopes = catch_scopes;
1240 self.loop_scopes = loop_scopes;
1242 self.is_in_loop_condition = was_in_loop_condition;
1247 fn def_key(&mut self, id: DefId) -> DefKey {
1249 self.resolver.definitions().def_key(id.index)
1251 self.cstore.def_key(id)
1255 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1256 label.map(|label| hir::Label {
1261 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1262 let target_id = match destination {
1264 if let Def::Label(loop_id) = self.expect_full_def(id) {
1265 Ok(self.lower_node_id(loop_id).hir_id)
1267 Err(hir::LoopIdError::UnresolvedLabel)
1274 .map(|id| Ok(self.lower_node_id(id).hir_id))
1275 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1280 label: self.lower_label(destination.map(|(_, label)| label)),
1285 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1288 .map(|a| self.lower_attr(a))
1292 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1293 // Note that we explicitly do not walk the path. Since we don't really
1294 // lower attributes (we use the AST version) there is nowhere to keep
1295 // the `HirId`s. We don't actually need HIR version of attributes anyway.
1299 path: attr.path.clone(),
1300 tokens: self.lower_token_stream(attr.tokens.clone()),
1301 is_sugared_doc: attr.is_sugared_doc,
1306 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1309 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1313 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1315 TokenTree::Token(span, token) => self.lower_token(token, span),
1316 TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1319 self.lower_token_stream(tts),
1324 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1326 Token::Interpolated(nt) => {
1327 let tts = nt.to_tokenstream(&self.sess.parse_sess, span);
1328 self.lower_token_stream(tts)
1330 other => TokenTree::Token(span, other).into(),
1334 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1336 attrs: self.lower_attrs(&arm.attrs),
1337 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1338 guard: match arm.guard {
1339 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1342 body: P(self.lower_expr(&arm.body)),
1346 fn lower_ty_binding(&mut self, b: &TypeBinding,
1347 itctx: ImplTraitContext<'_>) -> hir::TypeBinding {
1348 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(b.id);
1353 ty: self.lower_ty(&b.ty, itctx),
1358 fn lower_generic_arg(&mut self,
1359 arg: &ast::GenericArg,
1360 itctx: ImplTraitContext<'_>)
1361 -> hir::GenericArg {
1363 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1364 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1365 ast::GenericArg::Const(ct) => {
1366 GenericArg::Const(ConstArg {
1367 value: self.lower_anon_const(&ct),
1368 span: ct.value.span,
1374 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1375 P(self.lower_ty_direct(t, itctx))
1378 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1379 let kind = match t.node {
1380 TyKind::Infer => hir::TyKind::Infer,
1381 TyKind::Err => hir::TyKind::Err,
1382 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1383 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1384 TyKind::Rptr(ref region, ref mt) => {
1385 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1386 let lifetime = match *region {
1387 Some(ref lt) => self.lower_lifetime(lt),
1388 None => self.elided_ref_lifetime(span),
1390 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1392 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1395 this.with_anonymous_lifetime_mode(
1396 AnonymousLifetimeMode::PassThrough,
1398 hir::TyKind::BareFn(P(hir::BareFnTy {
1399 generic_params: this.lower_generic_params(
1401 &NodeMap::default(),
1402 ImplTraitContext::disallowed(),
1404 unsafety: this.lower_unsafety(f.unsafety),
1406 decl: this.lower_fn_decl(&f.decl, None, false, None),
1407 arg_names: this.lower_fn_args_to_names(&f.decl),
1413 TyKind::Never => hir::TyKind::Never,
1414 TyKind::Tup(ref tys) => {
1415 hir::TyKind::Tup(tys.iter().map(|ty| {
1416 self.lower_ty_direct(ty, itctx.reborrow())
1419 TyKind::Paren(ref ty) => {
1420 return self.lower_ty_direct(ty, itctx);
1422 TyKind::Path(ref qself, ref path) => {
1423 let id = self.lower_node_id(t.id);
1424 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1425 let ty = self.ty_path(id, t.span, qpath);
1426 if let hir::TyKind::TraitObject(..) = ty.node {
1427 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1431 TyKind::ImplicitSelf => {
1432 let def = self.expect_full_def(t.id);
1433 let def = self.lower_def(def);
1434 hir::TyKind::Path(hir::QPath::Resolved(
1438 segments: hir_vec![hir::PathSegment::from_ident(
1439 keywords::SelfUpper.ident()
1445 TyKind::Array(ref ty, ref length) => {
1446 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1448 TyKind::Typeof(ref expr) => {
1449 hir::TyKind::Typeof(self.lower_anon_const(expr))
1451 TyKind::TraitObject(ref bounds, kind) => {
1452 let mut lifetime_bound = None;
1455 .filter_map(|bound| match *bound {
1456 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1457 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1459 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1460 GenericBound::Outlives(ref lifetime) => {
1461 if lifetime_bound.is_none() {
1462 lifetime_bound = Some(self.lower_lifetime(lifetime));
1468 let lifetime_bound =
1469 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1470 if kind != TraitObjectSyntax::Dyn {
1471 self.maybe_lint_bare_trait(t.span, t.id, false);
1473 hir::TyKind::TraitObject(bounds, lifetime_bound)
1475 TyKind::ImplTrait(def_node_id, ref bounds) => {
1478 ImplTraitContext::Existential(fn_def_id) => {
1479 self.lower_existential_impl_trait(
1480 span, fn_def_id, def_node_id,
1481 |this| this.lower_param_bounds(bounds, itctx),
1484 ImplTraitContext::Universal(in_band_ty_params) => {
1485 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(def_node_id);
1486 // Add a definition for the in-band `Param`.
1487 let def_index = self
1490 .opt_def_index(def_node_id)
1493 let hir_bounds = self.lower_param_bounds(
1495 ImplTraitContext::Universal(in_band_ty_params),
1497 // Set the name to `impl Bound1 + Bound2`.
1498 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1499 in_band_ty_params.push(hir::GenericParam {
1501 name: ParamName::Plain(ident),
1502 pure_wrt_drop: false,
1506 kind: hir::GenericParamKind::Type {
1508 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1512 hir::TyKind::Path(hir::QPath::Resolved(
1516 def: Def::TyParam(DefId::local(def_index)),
1517 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1521 ImplTraitContext::Disallowed(pos) => {
1522 let allowed_in = if self.sess.features_untracked()
1523 .impl_trait_in_bindings {
1524 "bindings or function and inherent method return types"
1526 "function and inherent method return types"
1528 let mut err = struct_span_err!(
1532 "`impl Trait` not allowed outside of {}",
1535 if pos == ImplTraitPosition::Binding &&
1536 nightly_options::is_nightly_build() {
1538 "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1546 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1547 TyKind::CVarArgs => {
1548 // Create the implicit lifetime of the "spoofed" `VaList`.
1549 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1550 let lt = self.new_implicit_lifetime(span);
1551 hir::TyKind::CVarArgs(lt)
1555 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(t.id);
1563 fn lower_existential_impl_trait(
1566 fn_def_id: Option<DefId>,
1567 exist_ty_node_id: NodeId,
1568 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1570 // Make sure we know that some funky desugaring has been going on here.
1571 // This is a first: there is code in other places like for loop
1572 // desugaring that explicitly states that we don't want to track that.
1573 // Not tracking it makes lints in rustc and clippy very fragile as
1574 // frequently opened issues show.
1575 let exist_ty_span = self.mark_span_with_reason(
1576 CompilerDesugaringKind::ExistentialReturnType,
1581 let exist_ty_def_index = self
1584 .opt_def_index(exist_ty_node_id)
1587 self.allocate_hir_id_counter(exist_ty_node_id);
1589 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1591 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1597 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1598 let LoweredNodeId { node_id: _, hir_id } = lctx.next_id();
1599 let exist_ty_item = hir::ExistTy {
1600 generics: hir::Generics {
1601 params: lifetime_defs,
1602 where_clause: hir::WhereClause {
1604 predicates: hir_vec![],
1609 impl_trait_fn: fn_def_id,
1610 origin: hir::ExistTyOrigin::ReturnImplTrait,
1613 trace!("exist ty from impl trait def index: {:#?}", exist_ty_def_index);
1614 let exist_ty_id = lctx.generate_existential_type(
1621 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1622 hir::TyKind::Def(hir::ItemId { id: exist_ty_id.hir_id }, lifetimes)
1626 /// Registers a new existential type with the proper NodeIds and
1627 /// returns the lowered node ID for the existential type.
1628 fn generate_existential_type(
1630 exist_ty_node_id: NodeId,
1631 exist_ty_item: hir::ExistTy,
1633 exist_ty_span: Span,
1634 ) -> LoweredNodeId {
1635 let exist_ty_item_kind = hir::ItemKind::Existential(exist_ty_item);
1636 let exist_ty_id = self.lower_node_id(exist_ty_node_id);
1637 // Generate an `existential type Foo: Trait;` declaration.
1638 trace!("registering existential type with id {:#?}", exist_ty_id);
1639 let exist_ty_item = hir::Item {
1640 hir_id: exist_ty_id.hir_id,
1641 ident: keywords::Invalid.ident(),
1642 attrs: Default::default(),
1643 node: exist_ty_item_kind,
1644 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1645 span: exist_ty_span,
1648 // Insert the item into the global item list. This usually happens
1649 // automatically for all AST items. But this existential type item
1650 // does not actually exist in the AST.
1651 self.insert_item(exist_ty_item);
1655 fn lifetimes_from_impl_trait_bounds(
1657 exist_ty_id: NodeId,
1658 parent_index: DefIndex,
1659 bounds: &hir::GenericBounds,
1660 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1661 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1662 // appear in the bounds, excluding lifetimes that are created within the bounds.
1663 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1664 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1665 context: &'r mut LoweringContext<'a>,
1667 exist_ty_id: NodeId,
1668 collect_elided_lifetimes: bool,
1669 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1670 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1671 output_lifetimes: Vec<hir::GenericArg>,
1672 output_lifetime_params: Vec<hir::GenericParam>,
1675 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1676 fn nested_visit_map<'this>(
1678 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1679 hir::intravisit::NestedVisitorMap::None
1682 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1683 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1684 if parameters.parenthesized {
1685 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1686 self.collect_elided_lifetimes = false;
1687 hir::intravisit::walk_generic_args(self, span, parameters);
1688 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1690 hir::intravisit::walk_generic_args(self, span, parameters);
1694 fn visit_ty(&mut self, t: &'v hir::Ty) {
1695 // Don't collect elided lifetimes used inside of `fn()` syntax.
1696 if let hir::TyKind::BareFn(_) = t.node {
1697 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1698 self.collect_elided_lifetimes = false;
1700 // Record the "stack height" of `for<'a>` lifetime bindings
1701 // to be able to later fully undo their introduction.
1702 let old_len = self.currently_bound_lifetimes.len();
1703 hir::intravisit::walk_ty(self, t);
1704 self.currently_bound_lifetimes.truncate(old_len);
1706 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1708 hir::intravisit::walk_ty(self, t)
1712 fn visit_poly_trait_ref(
1714 trait_ref: &'v hir::PolyTraitRef,
1715 modifier: hir::TraitBoundModifier,
1717 // Record the "stack height" of `for<'a>` lifetime bindings
1718 // to be able to later fully undo their introduction.
1719 let old_len = self.currently_bound_lifetimes.len();
1720 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1721 self.currently_bound_lifetimes.truncate(old_len);
1724 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1725 // Record the introduction of 'a in `for<'a> ...`.
1726 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1727 // Introduce lifetimes one at a time so that we can handle
1728 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1729 let lt_name = hir::LifetimeName::Param(param.name);
1730 self.currently_bound_lifetimes.push(lt_name);
1733 hir::intravisit::walk_generic_param(self, param);
1736 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1737 let name = match lifetime.name {
1738 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1739 if self.collect_elided_lifetimes {
1740 // Use `'_` for both implicit and underscore lifetimes in
1741 // `abstract type Foo<'_>: SomeTrait<'_>;`.
1742 hir::LifetimeName::Underscore
1747 hir::LifetimeName::Param(_) => lifetime.name,
1748 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1751 if !self.currently_bound_lifetimes.contains(&name)
1752 && !self.already_defined_lifetimes.contains(&name) {
1753 self.already_defined_lifetimes.insert(name);
1755 let LoweredNodeId { node_id: _, hir_id } = self.context.next_id();
1756 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1758 span: lifetime.span,
1762 let def_node_id = self.context.sess.next_node_id();
1763 let LoweredNodeId { node_id: _, hir_id } =
1764 self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1765 self.context.resolver.definitions().create_def_with_parent(
1768 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1769 DefIndexAddressSpace::High,
1774 let (name, kind) = match name {
1775 hir::LifetimeName::Underscore => (
1776 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident()),
1777 hir::LifetimeParamKind::Elided,
1779 hir::LifetimeName::Param(param_name) => (
1781 hir::LifetimeParamKind::Explicit,
1783 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1786 self.output_lifetime_params.push(hir::GenericParam {
1789 span: lifetime.span,
1790 pure_wrt_drop: false,
1793 kind: hir::GenericParamKind::Lifetime { kind }
1799 let mut lifetime_collector = ImplTraitLifetimeCollector {
1801 parent: parent_index,
1803 collect_elided_lifetimes: true,
1804 currently_bound_lifetimes: Vec::new(),
1805 already_defined_lifetimes: FxHashSet::default(),
1806 output_lifetimes: Vec::new(),
1807 output_lifetime_params: Vec::new(),
1810 for bound in bounds {
1811 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1815 lifetime_collector.output_lifetimes.into(),
1816 lifetime_collector.output_lifetime_params.into(),
1820 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1825 .map(|x| self.lower_foreign_item(x))
1830 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1837 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1838 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(v.node.id);
1840 node: hir::VariantKind {
1841 ident: v.node.ident,
1843 attrs: self.lower_attrs(&v.node.attrs),
1844 data: self.lower_variant_data(&v.node.data),
1845 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1854 qself: &Option<QSelf>,
1856 param_mode: ParamMode,
1857 mut itctx: ImplTraitContext<'_>,
1859 let qself_position = qself.as_ref().map(|q| q.position);
1860 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1862 let resolution = self.resolver
1864 .unwrap_or_else(|| PathResolution::new(Def::Err));
1866 let proj_start = p.segments.len() - resolution.unresolved_segments();
1867 let path = P(hir::Path {
1868 def: self.lower_def(resolution.base_def()),
1869 segments: p.segments[..proj_start]
1872 .map(|(i, segment)| {
1873 let param_mode = match (qself_position, param_mode) {
1874 (Some(j), ParamMode::Optional) if i < j => {
1875 // This segment is part of the trait path in a
1876 // qualified path - one of `a`, `b` or `Trait`
1877 // in `<X as a::b::Trait>::T::U::method`.
1883 // Figure out if this is a type/trait segment,
1884 // which may need lifetime elision performed.
1885 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1886 krate: def_id.krate,
1887 index: this.def_key(def_id).parent.expect("missing parent"),
1889 let type_def_id = match resolution.base_def() {
1890 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1891 Some(parent_def_id(self, def_id))
1893 Def::Variant(def_id) if i + 1 == proj_start => {
1894 Some(parent_def_id(self, def_id))
1897 | Def::Union(def_id)
1899 | Def::TyAlias(def_id)
1900 | Def::Trait(def_id) if i + 1 == proj_start =>
1906 let parenthesized_generic_args = match resolution.base_def() {
1907 // `a::b::Trait(Args)`
1908 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1909 // `a::b::Trait(Args)::TraitItem`
1910 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1911 if i + 2 == proj_start =>
1913 ParenthesizedGenericArgs::Ok
1915 // Avoid duplicated errors.
1916 Def::Err => ParenthesizedGenericArgs::Ok,
1922 | Def::Variant(..) if i + 1 == proj_start =>
1924 ParenthesizedGenericArgs::Err
1926 // A warning for now, for compatibility reasons
1927 _ => ParenthesizedGenericArgs::Warn,
1930 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1931 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1934 assert!(!def_id.is_local());
1936 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1937 let n = item_generics.own_counts().lifetimes;
1938 self.type_def_lifetime_params.insert(def_id, n);
1941 self.lower_path_segment(
1946 parenthesized_generic_args,
1955 // Simple case, either no projections, or only fully-qualified.
1956 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
1957 if resolution.unresolved_segments() == 0 {
1958 return hir::QPath::Resolved(qself, path);
1961 // Create the innermost type that we're projecting from.
1962 let mut ty = if path.segments.is_empty() {
1963 // If the base path is empty that means there exists a
1964 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
1965 qself.expect("missing QSelf for <T>::...")
1967 // Otherwise, the base path is an implicit `Self` type path,
1968 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1969 // `<I as Iterator>::Item::default`.
1970 let new_id = self.next_id();
1971 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1974 // Anything after the base path are associated "extensions",
1975 // out of which all but the last one are associated types,
1976 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1977 // * base path is `std::vec::Vec<T>`
1978 // * "extensions" are `IntoIter`, `Item` and `clone`
1979 // * type nodes are:
1980 // 1. `std::vec::Vec<T>` (created above)
1981 // 2. `<std::vec::Vec<T>>::IntoIter`
1982 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1983 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1984 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1985 let segment = P(self.lower_path_segment(
1990 ParenthesizedGenericArgs::Warn,
1994 let qpath = hir::QPath::TypeRelative(ty, segment);
1996 // It's finished, return the extension of the right node type.
1997 if i == p.segments.len() - 1 {
2001 // Wrap the associated extension in another type node.
2002 let new_id = self.next_id();
2003 ty = P(self.ty_path(new_id, p.span, qpath));
2006 // We should've returned in the for loop above.
2009 "lower_qpath: no final extension segment in {}..{}",
2015 fn lower_path_extra(
2019 param_mode: ParamMode,
2020 explicit_owner: Option<NodeId>,
2024 segments: p.segments
2027 self.lower_path_segment(
2032 ParenthesizedGenericArgs::Err,
2033 ImplTraitContext::disallowed(),
2042 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
2043 let def = self.expect_full_def(id);
2044 let def = self.lower_def(def);
2045 self.lower_path_extra(def, p, param_mode, None)
2048 fn lower_path_segment(
2051 segment: &PathSegment,
2052 param_mode: ParamMode,
2053 expected_lifetimes: usize,
2054 parenthesized_generic_args: ParenthesizedGenericArgs,
2055 itctx: ImplTraitContext<'_>,
2056 explicit_owner: Option<NodeId>,
2057 ) -> hir::PathSegment {
2058 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
2059 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
2060 match **generic_args {
2061 GenericArgs::AngleBracketed(ref data) => {
2062 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
2064 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
2065 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
2066 ParenthesizedGenericArgs::Warn => {
2067 self.sess.buffer_lint(
2068 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
2073 (hir::GenericArgs::none(), true)
2075 ParenthesizedGenericArgs::Err => {
2076 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
2077 err.span_label(data.span, "only `Fn` traits may use parentheses");
2078 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
2079 // Do not suggest going from `Trait()` to `Trait<>`
2080 if data.inputs.len() > 0 {
2081 err.span_suggestion(
2083 "use angle brackets instead",
2084 format!("<{}>", &snippet[1..snippet.len() - 1]),
2085 Applicability::MaybeIncorrect,
2090 (self.lower_angle_bracketed_parameter_data(
2091 &data.as_angle_bracketed_args(),
2099 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
2102 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
2103 GenericArg::Lifetime(_) => true,
2106 let first_generic_span = generic_args.args.iter().map(|a| a.span())
2107 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
2108 if !generic_args.parenthesized && !has_lifetimes {
2110 self.elided_path_lifetimes(path_span, expected_lifetimes)
2112 .map(|lt| GenericArg::Lifetime(lt))
2113 .chain(generic_args.args.into_iter())
2115 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
2116 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
2117 let no_ty_args = generic_args.args.len() == expected_lifetimes;
2118 let no_bindings = generic_args.bindings.is_empty();
2119 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
2120 // If there are no (non-implicit) generic args or associated-type
2121 // bindings, our suggestion includes the angle brackets.
2122 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
2124 // Otherwise—sorry, this is kind of gross—we need to infer the
2125 // place to splice in the `'_, ` from the generics that do exist.
2126 let first_generic_span = first_generic_span
2127 .expect("already checked that type args or bindings exist");
2128 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
2130 self.sess.buffer_lint_with_diagnostic(
2131 ELIDED_LIFETIMES_IN_PATHS,
2134 "hidden lifetime parameters in types are deprecated",
2135 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
2136 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
2142 let def = self.expect_full_def(segment.id);
2143 let id = if let Some(owner) = explicit_owner {
2144 self.lower_node_id_with_owner(segment.id, owner)
2146 self.lower_node_id(segment.id)
2149 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
2150 segment.ident, segment.id, id,
2153 hir::PathSegment::new(
2156 Some(self.lower_def(def)),
2162 fn lower_angle_bracketed_parameter_data(
2164 data: &AngleBracketedArgs,
2165 param_mode: ParamMode,
2166 mut itctx: ImplTraitContext<'_>,
2167 ) -> (hir::GenericArgs, bool) {
2168 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
2169 let has_types = args.iter().any(|arg| match arg {
2170 ast::GenericArg::Type(_) => true,
2174 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
2175 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
2176 parenthesized: false,
2178 !has_types && param_mode == ParamMode::Optional)
2181 fn lower_parenthesized_parameter_data(
2183 data: &ParenthesizedArgs,
2184 ) -> (hir::GenericArgs, bool) {
2185 // Switch to `PassThrough` mode for anonymous lifetimes: this
2186 // means that we permit things like `&Ref<T>`, where `Ref` has
2187 // a hidden lifetime parameter. This is needed for backwards
2188 // compatibility, even in contexts like an impl header where
2189 // we generally don't permit such things (see #51008).
2190 self.with_anonymous_lifetime_mode(
2191 AnonymousLifetimeMode::PassThrough,
2193 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2196 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
2198 let mk_tup = |this: &mut Self, tys, span| {
2199 let LoweredNodeId { node_id: _, hir_id } = this.next_id();
2200 hir::Ty { node: hir::TyKind::Tup(tys), hir_id, span }
2202 let LoweredNodeId { node_id: _, hir_id } = this.next_id();
2206 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
2210 ident: Ident::from_str(FN_OUTPUT_NAME),
2213 .map(|ty| this.lower_ty(&ty, ImplTraitContext::disallowed()))
2214 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
2215 span: output.as_ref().map_or(span, |ty| ty.span),
2218 parenthesized: true,
2226 fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) {
2227 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(l.id);
2228 let mut ids = SmallVec::<[NodeId; 1]>::new();
2229 if self.sess.features_untracked().impl_trait_in_bindings {
2230 if let Some(ref ty) = l.ty {
2231 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2232 visitor.visit_ty(ty);
2235 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2240 .map(|t| self.lower_ty(t,
2241 if self.sess.features_untracked().impl_trait_in_bindings {
2242 ImplTraitContext::Existential(Some(parent_def_id))
2244 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2247 pat: self.lower_pat(&l.pat),
2248 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2250 attrs: l.attrs.clone(),
2251 source: self.lower_local_source(l.source),
2255 fn lower_local_source(&mut self, ls: LocalSource) -> hir::LocalSource {
2257 LocalSource::Normal => hir::LocalSource::Normal,
2258 LocalSource::AsyncFn => hir::LocalSource::AsyncFn,
2262 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
2264 Mutability::Mutable => hir::MutMutable,
2265 Mutability::Immutable => hir::MutImmutable,
2269 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
2270 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(arg.id);
2273 pat: self.lower_pat(&arg.pat),
2277 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2280 .map(|arg| match arg.pat.node {
2281 PatKind::Ident(_, ident, _) => ident,
2282 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
2287 // Lowers a function declaration.
2289 // decl: the unlowered (ast) function declaration.
2290 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
2291 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2292 // make_ret_async is also `Some`.
2293 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
2294 // This guards against trait declarations and implementations where impl Trait is
2296 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2297 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
2298 // return type impl Trait item.
2302 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2303 impl_trait_return_allow: bool,
2304 make_ret_async: Option<NodeId>,
2305 ) -> P<hir::FnDecl> {
2306 let lt_mode = if make_ret_async.is_some() {
2307 // In `async fn`, argument-position elided lifetimes
2308 // must be transformed into fresh generic parameters so that
2309 // they can be applied to the existential return type.
2310 AnonymousLifetimeMode::CreateParameter
2312 self.anonymous_lifetime_mode
2315 // Remember how many lifetimes were already around so that we can
2316 // only look at the lifetime parameters introduced by the arguments.
2317 let lifetime_count_before_args = self.lifetimes_to_define.len();
2318 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2322 if let Some((_, ibty)) = &mut in_band_ty_params {
2323 this.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2325 this.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2328 .collect::<HirVec<_>>()
2331 let output = if let Some(ret_id) = make_ret_async {
2332 // Calculate the `LtReplacement` to use for any return-position elided
2333 // lifetimes based on the elided lifetime parameters introduced in the args.
2334 let lt_replacement = get_elided_lt_replacement(
2335 &self.lifetimes_to_define[lifetime_count_before_args..]
2337 self.lower_async_fn_ret_ty(
2339 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
2345 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2346 Some((def_id, _)) if impl_trait_return_allow => {
2347 hir::Return(self.lower_ty(ty,
2348 ImplTraitContext::Existential(Some(def_id))))
2351 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2354 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2361 c_variadic: decl.c_variadic,
2362 implicit_self: decl.inputs.get(0).map_or(
2363 hir::ImplicitSelfKind::None,
2365 let is_mutable_pat = match arg.pat.node {
2366 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2367 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2368 mt == Mutability::Mutable,
2373 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2374 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2375 // Given we are only considering `ImplicitSelf` types, we needn't consider
2376 // the case where we have a mutable pattern to a reference as that would
2377 // no longer be an `ImplicitSelf`.
2378 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2379 mt.mutbl == ast::Mutability::Mutable =>
2380 hir::ImplicitSelfKind::MutRef,
2381 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2382 hir::ImplicitSelfKind::ImmRef,
2383 _ => hir::ImplicitSelfKind::None,
2390 // Transform `-> T` for `async fn` into -> ExistTy { .. }
2391 // combined with the following definition of `ExistTy`:
2393 // existential type ExistTy<generics_from_parent_fn>: Future<Output = T>;
2395 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
2396 // output: unlowered output type (`T` in `-> T`)
2397 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
2398 // exist_ty_node_id: NodeId of the existential type that should be created.
2399 // elided_lt_replacement: replacement for elided lifetimes in the return type
2400 fn lower_async_fn_ret_ty(
2402 output: &FunctionRetTy,
2404 exist_ty_node_id: NodeId,
2405 elided_lt_replacement: LtReplacement,
2406 ) -> hir::FunctionRetTy {
2407 let span = output.span();
2409 let exist_ty_span = self.mark_span_with_reason(
2410 CompilerDesugaringKind::Async,
2415 let exist_ty_def_index = self
2418 .opt_def_index(exist_ty_node_id)
2421 self.allocate_hir_id_counter(exist_ty_node_id);
2423 let (exist_ty_node_id, lifetime_params) = self.with_hir_id_owner(exist_ty_node_id, |this| {
2424 let future_bound = this.with_anonymous_lifetime_mode(
2425 AnonymousLifetimeMode::Replace(elided_lt_replacement),
2426 |this| this.lower_async_fn_output_type_to_future_bound(
2433 // Calculate all the lifetimes that should be captured
2434 // by the existential type. This should include all in-scope
2435 // lifetime parameters, including those defined in-band.
2437 // Note: this must be done after lowering the output type,
2438 // as the output type may introduce new in-band lifetimes.
2439 let lifetime_params: Vec<(Span, ParamName)> =
2440 this.in_scope_lifetimes
2442 .map(|ident| (ident.span, ParamName::Plain(ident)))
2443 .chain(this.lifetimes_to_define.iter().cloned())
2446 let generic_params =
2449 .map(|(span, hir_name)| {
2450 this.lifetime_to_generic_param(span, hir_name, exist_ty_def_index)
2454 let LoweredNodeId { node_id: _, hir_id } = this.next_id();
2455 let exist_ty_item = hir::ExistTy {
2456 generics: hir::Generics {
2457 params: generic_params,
2458 where_clause: hir::WhereClause {
2460 predicates: hir_vec![],
2464 bounds: hir_vec![future_bound],
2465 impl_trait_fn: Some(fn_def_id),
2466 origin: hir::ExistTyOrigin::AsyncFn,
2469 trace!("exist ty from async fn def index: {:#?}", exist_ty_def_index);
2470 let exist_ty_id = this.generate_existential_type(
2477 (exist_ty_id.node_id, lifetime_params)
2483 .map(|(span, hir_name)| {
2484 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
2485 GenericArg::Lifetime(hir::Lifetime {
2488 name: hir::LifetimeName::Param(hir_name),
2493 let exist_ty_hir_id = self.lower_node_id(exist_ty_node_id).hir_id;
2494 let exist_ty_ref = hir::TyKind::Def(hir::ItemId { id: exist_ty_hir_id }, generic_args);
2496 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
2497 hir::FunctionRetTy::Return(P(hir::Ty {
2504 /// Turns `-> T` into `Future<Output = T>`
2505 fn lower_async_fn_output_type_to_future_bound(
2507 output: &FunctionRetTy,
2510 ) -> hir::GenericBound {
2511 // Compute the `T` in `Future<Output = T>` from the return type.
2512 let output_ty = match output {
2513 FunctionRetTy::Ty(ty) => {
2514 self.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2516 FunctionRetTy::Default(ret_ty_span) => {
2517 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
2520 node: hir::TyKind::Tup(hir_vec![]),
2527 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
2528 let future_params = P(hir::GenericArgs {
2530 bindings: hir_vec![hir::TypeBinding {
2531 ident: Ident::from_str(FN_OUTPUT_NAME),
2536 parenthesized: false,
2539 // ::std::future::Future<future_params>
2541 self.std_path(span, &["future", "Future"], Some(future_params), false);
2543 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
2544 hir::GenericBound::Trait(
2546 trait_ref: hir::TraitRef {
2550 bound_generic_params: hir_vec![],
2553 hir::TraitBoundModifier::None,
2557 fn lower_param_bound(
2560 itctx: ImplTraitContext<'_>,
2561 ) -> hir::GenericBound {
2563 GenericBound::Trait(ref ty, modifier) => {
2564 hir::GenericBound::Trait(
2565 self.lower_poly_trait_ref(ty, itctx),
2566 self.lower_trait_bound_modifier(modifier),
2569 GenericBound::Outlives(ref lifetime) => {
2570 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2575 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2576 let span = l.ident.span;
2578 ident if ident.name == keywords::StaticLifetime.name() =>
2579 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2580 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2581 match self.anonymous_lifetime_mode {
2582 AnonymousLifetimeMode::CreateParameter => {
2583 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2584 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2587 AnonymousLifetimeMode::PassThrough => {
2588 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2591 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2593 AnonymousLifetimeMode::Replace(replacement) => {
2594 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(l.id);
2595 self.replace_elided_lifetime(hir_id, span, replacement)
2599 self.maybe_collect_in_band_lifetime(ident);
2600 let param_name = ParamName::Plain(ident);
2601 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2606 fn new_named_lifetime(
2610 name: hir::LifetimeName,
2611 ) -> hir::Lifetime {
2612 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(id);
2621 /// Replace a return-position elided lifetime with the elided lifetime
2622 /// from the arguments.
2623 fn replace_elided_lifetime(
2627 replacement: LtReplacement,
2628 ) -> hir::Lifetime {
2629 let multiple_or_none = match replacement {
2630 LtReplacement::Some(name) => {
2631 return hir::Lifetime {
2634 name: hir::LifetimeName::Param(name),
2637 LtReplacement::MultipleLifetimes => "multiple",
2638 LtReplacement::NoLifetimes => "none",
2641 let mut err = crate::middle::resolve_lifetime::report_missing_lifetime_specifiers(
2647 "return-position elided lifetimes require exactly one \
2648 input-position elided lifetime, found {}.", multiple_or_none));
2651 hir::Lifetime { hir_id, span, name: hir::LifetimeName::Error }
2654 fn lower_generic_params(
2656 params: &[GenericParam],
2657 add_bounds: &NodeMap<Vec<GenericBound>>,
2658 mut itctx: ImplTraitContext<'_>,
2659 ) -> hir::HirVec<hir::GenericParam> {
2660 params.iter().map(|param| {
2661 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2665 fn lower_generic_param(&mut self,
2666 param: &GenericParam,
2667 add_bounds: &NodeMap<Vec<GenericBound>>,
2668 mut itctx: ImplTraitContext<'_>)
2669 -> hir::GenericParam {
2670 let mut bounds = self.with_anonymous_lifetime_mode(
2671 AnonymousLifetimeMode::ReportError,
2672 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2675 let (name, kind) = match param.kind {
2676 GenericParamKind::Lifetime => {
2677 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2678 self.is_collecting_in_band_lifetimes = false;
2680 let lt = self.with_anonymous_lifetime_mode(
2681 AnonymousLifetimeMode::ReportError,
2682 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2684 let param_name = match lt.name {
2685 hir::LifetimeName::Param(param_name) => param_name,
2686 hir::LifetimeName::Implicit
2687 | hir::LifetimeName::Underscore
2688 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2689 hir::LifetimeName::Error => ParamName::Error,
2692 let kind = hir::GenericParamKind::Lifetime {
2693 kind: hir::LifetimeParamKind::Explicit
2696 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2700 GenericParamKind::Type { ref default, .. } => {
2701 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2702 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2703 // Instead, use `gensym("Self")` to create a distinct name that looks the same.
2704 let ident = if param.ident.name == keywords::SelfUpper.name() {
2705 param.ident.gensym()
2710 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2711 if !add_bounds.is_empty() {
2712 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2713 bounds = bounds.into_iter()
2718 let kind = hir::GenericParamKind::Type {
2719 default: default.as_ref().map(|x| {
2720 self.lower_ty(x, ImplTraitContext::disallowed())
2722 synthetic: param.attrs.iter()
2723 .filter(|attr| attr.check_name("rustc_synthetic"))
2724 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2728 (hir::ParamName::Plain(ident), kind)
2730 GenericParamKind::Const { ref ty } => {
2731 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const {
2732 ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2737 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(param.id);
2742 span: param.ident.span,
2743 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2744 attrs: self.lower_attrs(¶m.attrs),
2752 generics: &Generics,
2753 itctx: ImplTraitContext<'_>)
2756 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2757 // FIXME: this could probably be done with less rightward drift. Also looks like two control
2758 // paths where report_error is called are also the only paths that advance to after
2759 // the match statement, so the error reporting could probably just be moved there.
2760 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
2761 for pred in &generics.where_clause.predicates {
2762 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2763 'next_bound: for bound in &bound_pred.bounds {
2764 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2765 let report_error = |this: &mut Self| {
2766 this.diagnostic().span_err(
2767 bound_pred.bounded_ty.span,
2768 "`?Trait` bounds are only permitted at the \
2769 point where a type parameter is declared",
2772 // Check if the where clause type is a plain type parameter.
2773 match bound_pred.bounded_ty.node {
2774 TyKind::Path(None, ref path)
2775 if path.segments.len() == 1
2776 && bound_pred.bound_generic_params.is_empty() =>
2778 if let Some(Def::TyParam(def_id)) = self.resolver
2779 .get_resolution(bound_pred.bounded_ty.id)
2780 .map(|d| d.base_def())
2782 if let Some(node_id) =
2783 self.resolver.definitions().as_local_node_id(def_id)
2785 for param in &generics.params {
2787 GenericParamKind::Type { .. } => {
2788 if node_id == param.id {
2789 add_bounds.entry(param.id)
2791 .push(bound.clone());
2792 continue 'next_bound;
2802 _ => report_error(self),
2810 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2811 where_clause: self.lower_where_clause(&generics.where_clause),
2812 span: generics.span,
2816 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2817 self.with_anonymous_lifetime_mode(
2818 AnonymousLifetimeMode::ReportError,
2820 let LoweredNodeId { node_id: _, hir_id } = this.lower_node_id(wc.id);
2824 predicates: wc.predicates
2826 .map(|predicate| this.lower_where_predicate(predicate))
2833 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2835 WherePredicate::BoundPredicate(WhereBoundPredicate {
2836 ref bound_generic_params,
2841 self.with_in_scope_lifetime_defs(
2842 &bound_generic_params,
2844 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2845 bound_generic_params: this.lower_generic_params(
2846 bound_generic_params,
2847 &NodeMap::default(),
2848 ImplTraitContext::disallowed(),
2850 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
2853 .filter_map(|bound| match *bound {
2854 // Ignore `?Trait` bounds.
2855 // They were copied into type parameters already.
2856 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2857 _ => Some(this.lower_param_bound(
2859 ImplTraitContext::disallowed(),
2868 WherePredicate::RegionPredicate(WhereRegionPredicate {
2872 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2874 lifetime: self.lower_lifetime(lifetime),
2875 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2877 WherePredicate::EqPredicate(WhereEqPredicate {
2883 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(id);
2885 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2887 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
2888 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
2895 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2897 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
2898 fields.iter().enumerate().map(|f| self.lower_struct_field(f)).collect(),
2901 VariantData::Tuple(ref fields, id) => {
2902 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(id);
2904 hir::VariantData::Tuple(
2908 .map(|f| self.lower_struct_field(f))
2913 VariantData::Unit(id) => {
2914 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(id);
2915 hir::VariantData::Unit(hir_id)
2920 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2921 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2922 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2923 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2925 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(p.ref_id);
2932 fn lower_poly_trait_ref(
2935 mut itctx: ImplTraitContext<'_>,
2936 ) -> hir::PolyTraitRef {
2937 let bound_generic_params = self.lower_generic_params(
2938 &p.bound_generic_params,
2939 &NodeMap::default(),
2942 let trait_ref = self.with_parent_impl_lifetime_defs(
2943 &bound_generic_params,
2944 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2948 bound_generic_params,
2954 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2955 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(f.id);
2960 ident: match f.ident {
2961 Some(ident) => ident,
2962 // FIXME(jseyfried): positional field hygiene
2963 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2965 vis: self.lower_visibility(&f.vis, None),
2966 ty: self.lower_ty(&f.ty, ImplTraitContext::disallowed()),
2967 attrs: self.lower_attrs(&f.attrs),
2971 fn lower_field(&mut self, f: &Field) -> hir::Field {
2972 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
2977 expr: P(self.lower_expr(&f.expr)),
2979 is_shorthand: f.is_shorthand,
2983 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2985 ty: self.lower_ty(&mt.ty, itctx),
2986 mutbl: self.lower_mutability(mt.mutbl),
2990 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2991 -> hir::GenericBounds {
2992 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2995 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2996 let mut expr = None;
2998 let mut stmts = vec![];
3000 for (index, stmt) in b.stmts.iter().enumerate() {
3001 if index == b.stmts.len() - 1 {
3002 if let StmtKind::Expr(ref e) = stmt.node {
3003 expr = Some(P(self.lower_expr(e)));
3005 stmts.extend(self.lower_stmt(stmt));
3008 stmts.extend(self.lower_stmt(stmt));
3012 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(b.id);
3016 stmts: stmts.into(),
3018 rules: self.lower_block_check_mode(&b.rules),
3024 fn lower_async_body(
3027 asyncness: &IsAsync,
3030 self.lower_body(Some(&decl), |this| {
3031 if let IsAsync::Async { closure_id, ref arguments, .. } = asyncness {
3032 let mut body = body.clone();
3034 for a in arguments.iter().rev() {
3035 body.stmts.insert(0, a.stmt.clone());
3038 let async_expr = this.make_async_expr(
3039 CaptureBy::Value, *closure_id, None,
3041 let body = this.lower_block(&body, false);
3042 this.expr_block(body, ThinVec::new())
3044 this.expr(body.span, async_expr, ThinVec::new())
3046 let body = this.lower_block(body, false);
3047 this.expr_block(body, ThinVec::new())
3056 attrs: &hir::HirVec<Attribute>,
3057 vis: &mut hir::Visibility,
3059 ) -> hir::ItemKind {
3061 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
3062 ItemKind::Use(ref use_tree) => {
3063 // Start with an empty prefix
3066 span: use_tree.span,
3069 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
3071 ItemKind::Static(ref t, m, ref e) => {
3072 let value = self.lower_body(None, |this| this.lower_expr(e));
3073 hir::ItemKind::Static(
3076 if self.sess.features_untracked().impl_trait_in_bindings {
3077 ImplTraitContext::Existential(None)
3079 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3082 self.lower_mutability(m),
3086 ItemKind::Const(ref t, ref e) => {
3087 let value = self.lower_body(None, |this| this.lower_expr(e));
3088 hir::ItemKind::Const(
3091 if self.sess.features_untracked().impl_trait_in_bindings {
3092 ImplTraitContext::Existential(None)
3094 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3100 ItemKind::Fn(ref decl, ref header, ref generics, ref body) => {
3101 let fn_def_id = self.resolver.definitions().local_def_id(id);
3102 self.with_new_scopes(|this| {
3103 let mut lower_fn = |decl: &FnDecl| {
3104 // Note: we don't need to change the return type from `T` to
3105 // `impl Future<Output = T>` here because lower_body
3106 // only cares about the input argument patterns in the function
3107 // declaration (decl), not the return types.
3108 let body_id = this.lower_async_body(&decl, &header.asyncness.node, body);
3110 let (generics, fn_decl) = this.add_in_band_defs(
3113 AnonymousLifetimeMode::PassThrough,
3114 |this, idty| this.lower_fn_decl(
3116 Some((fn_def_id, idty)),
3118 header.asyncness.node.opt_return_id()
3122 (body_id, generics, fn_decl)
3125 let (body_id, generics, fn_decl) = if let IsAsync::Async {
3127 } = &header.asyncness.node {
3128 let mut decl = decl.clone();
3129 // Replace the arguments of this async function with the generated
3130 // arguments that will be moved into the closure.
3131 decl.inputs = arguments.clone().drain(..).map(|a| a.arg).collect();
3139 this.lower_fn_header(header),
3145 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
3146 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
3147 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
3148 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
3149 self.lower_ty(t, ImplTraitContext::disallowed()),
3150 self.lower_generics(generics, ImplTraitContext::disallowed()),
3152 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
3153 generics: self.lower_generics(generics, ImplTraitContext::disallowed()),
3154 bounds: self.lower_param_bounds(b, ImplTraitContext::disallowed()),
3155 impl_trait_fn: None,
3156 origin: hir::ExistTyOrigin::ExistentialType,
3158 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
3160 variants: enum_definition
3163 .map(|x| self.lower_variant(x))
3166 self.lower_generics(generics, ImplTraitContext::disallowed()),
3168 ItemKind::Struct(ref struct_def, ref generics) => {
3169 let struct_def = self.lower_variant_data(struct_def);
3170 hir::ItemKind::Struct(
3172 self.lower_generics(generics, ImplTraitContext::disallowed()),
3175 ItemKind::Union(ref vdata, ref generics) => {
3176 let vdata = self.lower_variant_data(vdata);
3177 hir::ItemKind::Union(
3179 self.lower_generics(generics, ImplTraitContext::disallowed()),
3191 let def_id = self.resolver.definitions().local_def_id(id);
3193 // Lower the "impl header" first. This ordering is important
3194 // for in-band lifetimes! Consider `'a` here:
3196 // impl Foo<'a> for u32 {
3197 // fn method(&'a self) { .. }
3200 // Because we start by lowering the `Foo<'a> for u32`
3201 // part, we will add `'a` to the list of generics on
3202 // the impl. When we then encounter it later in the
3203 // method, it will not be considered an in-band
3204 // lifetime to be added, but rather a reference to a
3206 let lowered_trait_impl_id = self.lower_node_id(id).hir_id;
3207 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
3210 AnonymousLifetimeMode::CreateParameter,
3212 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
3213 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
3216 if let Some(ref trait_ref) = trait_ref {
3217 if let Def::Trait(def_id) = trait_ref.path.def {
3218 this.trait_impls.entry(def_id).or_default().push(
3219 lowered_trait_impl_id);
3223 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
3225 (trait_ref, lowered_ty)
3229 let new_impl_items = self.with_in_scope_lifetime_defs(
3230 &ast_generics.params,
3234 .map(|item| this.lower_impl_item_ref(item))
3239 hir::ItemKind::Impl(
3240 self.lower_unsafety(unsafety),
3241 self.lower_impl_polarity(polarity),
3242 self.lower_defaultness(defaultness, true /* [1] */),
3249 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
3250 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
3253 .map(|item| self.lower_trait_item_ref(item))
3255 hir::ItemKind::Trait(
3256 self.lower_is_auto(is_auto),
3257 self.lower_unsafety(unsafety),
3258 self.lower_generics(generics, ImplTraitContext::disallowed()),
3263 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
3264 self.lower_generics(generics, ImplTraitContext::disallowed()),
3265 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3267 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
3270 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
3271 // not cause an assertion failure inside the `lower_defaultness` function.
3279 vis: &mut hir::Visibility,
3281 attrs: &hir::HirVec<Attribute>,
3282 ) -> hir::ItemKind {
3283 debug!("lower_use_tree(tree={:?})", tree);
3284 debug!("lower_use_tree: vis = {:?}", vis);
3286 let path = &tree.prefix;
3287 let segments = prefix
3290 .chain(path.segments.iter())
3295 UseTreeKind::Simple(rename, id1, id2) => {
3296 *ident = tree.ident();
3298 // First, apply the prefix to the path.
3299 let mut path = Path {
3304 // Correctly resolve `self` imports.
3305 if path.segments.len() > 1
3306 && path.segments.last().unwrap().ident.name == keywords::SelfLower.name()
3308 let _ = path.segments.pop();
3309 if rename.is_none() {
3310 *ident = path.segments.last().unwrap().ident;
3314 let mut defs = self.expect_full_def_from_use(id);
3315 // We want to return *something* from this function, so hold onto the first item
3317 let ret_def = self.lower_def(defs.next().unwrap_or(Def::Err));
3319 // Here, we are looping over namespaces, if they exist for the definition
3320 // being imported. We only handle type and value namespaces because we
3321 // won't be dealing with macros in the rest of the compiler.
3322 // Essentially a single `use` which imports two names is desugared into
3324 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
3325 let vis = vis.clone();
3326 let ident = ident.clone();
3327 let mut path = path.clone();
3328 for seg in &mut path.segments {
3329 seg.id = self.sess.next_node_id();
3331 let span = path.span;
3333 self.with_hir_id_owner(new_node_id, |this| {
3334 let new_id = this.lower_node_id(new_node_id);
3335 let def = this.lower_def(def);
3337 this.lower_path_extra(def, &path, ParamMode::Explicit, None);
3338 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
3339 let vis_kind = match vis.node {
3340 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3341 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3342 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3343 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
3344 let id = this.next_id();
3345 let path = this.renumber_segment_ids(path);
3346 hir::VisibilityKind::Restricted {
3352 let vis = respan(vis.span, vis_kind);
3356 hir_id: new_id.hir_id,
3358 attrs: attrs.clone(),
3368 P(self.lower_path_extra(ret_def, &path, ParamMode::Explicit, None));
3369 hir::ItemKind::Use(path, hir::UseKind::Single)
3371 UseTreeKind::Glob => {
3372 let path = P(self.lower_path(
3378 ParamMode::Explicit,
3380 hir::ItemKind::Use(path, hir::UseKind::Glob)
3382 UseTreeKind::Nested(ref trees) => {
3383 // Nested imports are desugared into simple imports.
3384 // So, if we start with
3387 // pub(x) use foo::{a, b};
3390 // we will create three items:
3393 // pub(x) use foo::a;
3394 // pub(x) use foo::b;
3395 // pub(x) use foo::{}; // <-- this is called the `ListStem`
3398 // The first two are produced by recursively invoking
3399 // `lower_use_tree` (and indeed there may be things
3400 // like `use foo::{a::{b, c}}` and so forth). They
3401 // wind up being directly added to
3402 // `self.items`. However, the structure of this
3403 // function also requires us to return one item, and
3404 // for that we return the `{}` import (called the
3409 span: prefix.span.to(path.span),
3412 // Add all the nested `PathListItem`s to the HIR.
3413 for &(ref use_tree, id) in trees {
3417 } = self.lower_node_id(id);
3419 let mut vis = vis.clone();
3420 let mut ident = ident.clone();
3421 let mut prefix = prefix.clone();
3423 // Give the segments new node-ids since they are being cloned.
3424 for seg in &mut prefix.segments {
3425 seg.id = self.sess.next_node_id();
3428 // Each `use` import is an item and thus are owners of the
3429 // names in the path. Up to this point the nested import is
3430 // the current owner, since we want each desugared import to
3431 // own its own names, we have to adjust the owner before
3432 // lowering the rest of the import.
3433 self.with_hir_id_owner(new_id, |this| {
3434 let item = this.lower_use_tree(use_tree,
3441 let vis_kind = match vis.node {
3442 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3443 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3444 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3445 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
3446 let id = this.next_id();
3447 let path = this.renumber_segment_ids(path);
3448 hir::VisibilityKind::Restricted {
3454 let vis = respan(vis.span, vis_kind);
3460 attrs: attrs.clone(),
3463 span: use_tree.span,
3469 // Subtle and a bit hacky: we lower the privacy level
3470 // of the list stem to "private" most of the time, but
3471 // not for "restricted" paths. The key thing is that
3472 // we don't want it to stay as `pub` (with no caveats)
3473 // because that affects rustdoc and also the lints
3474 // about `pub` items. But we can't *always* make it
3475 // private -- particularly not for restricted paths --
3476 // because it contains node-ids that would then be
3477 // unused, failing the check that HirIds are "densely
3480 hir::VisibilityKind::Public |
3481 hir::VisibilityKind::Crate(_) |
3482 hir::VisibilityKind::Inherited => {
3483 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3485 hir::VisibilityKind::Restricted { .. } => {
3486 // Do nothing here, as described in the comment on the match.
3490 let def = self.expect_full_def_from_use(id).next().unwrap_or(Def::Err);
3491 let def = self.lower_def(def);
3492 let path = P(self.lower_path_extra(def, &prefix, ParamMode::Explicit, None));
3493 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3498 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
3499 /// many times in the HIR tree; for each occurrence, we need to assign distinct
3500 /// `NodeId`s. (See, e.g., #56128.)
3501 fn renumber_segment_ids(&mut self, path: &P<hir::Path>) -> P<hir::Path> {
3502 debug!("renumber_segment_ids(path = {:?})", path);
3503 let mut path = path.clone();
3504 for seg in path.segments.iter_mut() {
3505 if seg.hir_id.is_some() {
3506 seg.hir_id = Some(self.next_id().hir_id);
3512 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3513 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3514 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
3516 let (generics, node) = match i.node {
3517 TraitItemKind::Const(ref ty, ref default) => (
3518 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3519 hir::TraitItemKind::Const(
3520 self.lower_ty(ty, ImplTraitContext::disallowed()),
3523 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
3526 TraitItemKind::Method(ref sig, None) => {
3527 let names = self.lower_fn_args_to_names(&sig.decl);
3528 let (generics, sig) = self.lower_method_sig(
3535 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3537 TraitItemKind::Method(ref sig, Some(ref body)) => {
3538 let body_id = self.lower_body(Some(&sig.decl), |this| {
3539 let body = this.lower_block(body, false);
3540 this.expr_block(body, ThinVec::new())
3542 let (generics, sig) = self.lower_method_sig(
3549 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3551 TraitItemKind::Type(ref bounds, ref default) => (
3552 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3553 hir::TraitItemKind::Type(
3554 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3557 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3560 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3566 attrs: self.lower_attrs(&i.attrs),
3573 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3574 let (kind, has_default) = match i.node {
3575 TraitItemKind::Const(_, ref default) => {
3576 (hir::AssociatedItemKind::Const, default.is_some())
3578 TraitItemKind::Type(_, ref default) => {
3579 (hir::AssociatedItemKind::Type, default.is_some())
3581 TraitItemKind::Method(ref sig, ref default) => (
3582 hir::AssociatedItemKind::Method {
3583 has_self: sig.decl.has_self(),
3587 TraitItemKind::Macro(..) => unimplemented!(),
3590 id: hir::TraitItemId { hir_id: self.lower_node_id(i.id).hir_id },
3593 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3598 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3599 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3600 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3602 let (generics, node) = match i.node {
3603 ImplItemKind::Const(ref ty, ref expr) => {
3604 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3606 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3607 hir::ImplItemKind::Const(
3608 self.lower_ty(ty, ImplTraitContext::disallowed()),
3613 ImplItemKind::Method(ref sig, ref body) => {
3614 let mut lower_method = |sig: &MethodSig| {
3615 let body_id = self.lower_async_body(
3616 &sig.decl, &sig.header.asyncness.node, body
3618 let impl_trait_return_allow = !self.is_in_trait_impl;
3619 let (generics, sig) = self.lower_method_sig(
3623 impl_trait_return_allow,
3624 sig.header.asyncness.node.opt_return_id(),
3626 (body_id, generics, sig)
3629 let (body_id, generics, sig) = if let IsAsync::Async {
3631 } = sig.header.asyncness.node {
3632 let mut sig = sig.clone();
3633 // Replace the arguments of this async function with the generated
3634 // arguments that will be moved into the closure.
3635 sig.decl.inputs = arguments.clone().drain(..).map(|a| a.arg).collect();
3641 (generics, hir::ImplItemKind::Method(sig, body_id))
3643 ImplItemKind::Type(ref ty) => (
3644 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3645 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3647 ImplItemKind::Existential(ref bounds) => (
3648 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3649 hir::ImplItemKind::Existential(
3650 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3653 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3659 attrs: self.lower_attrs(&i.attrs),
3661 vis: self.lower_visibility(&i.vis, None),
3662 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3667 // [1] since `default impl` is not yet implemented, this is always true in impls
3670 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3672 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id).hir_id },
3675 vis: self.lower_visibility(&i.vis, Some(i.id)),
3676 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3677 kind: match i.node {
3678 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3679 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3680 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3681 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3682 has_self: sig.decl.has_self(),
3684 ImplItemKind::Macro(..) => unimplemented!(),
3688 // [1] since `default impl` is not yet implemented, this is always true in impls
3691 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3694 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3698 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3699 let node_ids = match i.node {
3700 ItemKind::Use(ref use_tree) => {
3701 let mut vec = smallvec![i.id];
3702 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3705 ItemKind::MacroDef(..) => SmallVec::new(),
3707 ItemKind::Impl(.., None, _, _) => smallvec![i.id],
3708 ItemKind::Static(ref ty, ..) => {
3709 let mut ids = smallvec![i.id];
3710 if self.sess.features_untracked().impl_trait_in_bindings {
3711 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3712 visitor.visit_ty(ty);
3716 ItemKind::Const(ref ty, ..) => {
3717 let mut ids = smallvec![i.id];
3718 if self.sess.features_untracked().impl_trait_in_bindings {
3719 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3720 visitor.visit_ty(ty);
3724 _ => smallvec![i.id],
3727 node_ids.into_iter().map(|node_id| hir::ItemId {
3728 id: self.allocate_hir_id_counter(node_id).hir_id
3732 fn lower_item_id_use_tree(&mut self,
3735 vec: &mut SmallVec<[NodeId; 1]>)
3738 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3740 self.lower_item_id_use_tree(nested, id, vec);
3742 UseTreeKind::Glob => {}
3743 UseTreeKind::Simple(_, id1, id2) => {
3744 for (_, &id) in self.expect_full_def_from_use(base_id)
3746 .zip([id1, id2].iter())
3754 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3755 let mut ident = i.ident;
3756 let mut vis = self.lower_visibility(&i.vis, None);
3757 let attrs = self.lower_attrs(&i.attrs);
3758 if let ItemKind::MacroDef(ref def) = i.node {
3759 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3760 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3761 let body = self.lower_token_stream(def.stream());
3762 let hir_id = self.lower_node_id(i.id).hir_id;
3763 self.exported_macros.push(hir::MacroDef {
3776 let node = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.node);
3778 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(i.id);
3790 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3791 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3792 let def_id = self.resolver.definitions().local_def_id(node_id);
3796 attrs: self.lower_attrs(&i.attrs),
3797 node: match i.node {
3798 ForeignItemKind::Fn(ref fdec, ref generics) => {
3799 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3802 AnonymousLifetimeMode::PassThrough,
3805 // Disallow impl Trait in foreign items
3806 this.lower_fn_decl(fdec, None, false, None),
3807 this.lower_fn_args_to_names(fdec),
3812 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3814 ForeignItemKind::Static(ref t, m) => {
3815 hir::ForeignItemKind::Static(
3816 self.lower_ty(t, ImplTraitContext::disallowed()), m)
3818 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3819 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3821 vis: self.lower_visibility(&i.vis, None),
3826 fn lower_method_sig(
3828 generics: &Generics,
3831 impl_trait_return_allow: bool,
3832 is_async: Option<NodeId>,
3833 ) -> (hir::Generics, hir::MethodSig) {
3834 let header = self.lower_fn_header(&sig.header);
3835 let (generics, decl) = self.add_in_band_defs(
3838 AnonymousLifetimeMode::PassThrough,
3839 |this, idty| this.lower_fn_decl(
3841 Some((fn_def_id, idty)),
3842 impl_trait_return_allow,
3846 (generics, hir::MethodSig { header, decl })
3849 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3851 IsAuto::Yes => hir::IsAuto::Yes,
3852 IsAuto::No => hir::IsAuto::No,
3856 fn lower_fn_header(&mut self, h: &FnHeader) -> hir::FnHeader {
3858 unsafety: self.lower_unsafety(h.unsafety),
3859 asyncness: self.lower_asyncness(&h.asyncness.node),
3860 constness: self.lower_constness(h.constness),
3865 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3867 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3868 Unsafety::Normal => hir::Unsafety::Normal,
3872 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3874 Constness::Const => hir::Constness::Const,
3875 Constness::NotConst => hir::Constness::NotConst,
3879 fn lower_asyncness(&mut self, a: &IsAsync) -> hir::IsAsync {
3881 IsAsync::Async { .. } => hir::IsAsync::Async,
3882 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3886 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3888 UnOp::Deref => hir::UnDeref,
3889 UnOp::Not => hir::UnNot,
3890 UnOp::Neg => hir::UnNeg,
3894 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3896 node: match b.node {
3897 BinOpKind::Add => hir::BinOpKind::Add,
3898 BinOpKind::Sub => hir::BinOpKind::Sub,
3899 BinOpKind::Mul => hir::BinOpKind::Mul,
3900 BinOpKind::Div => hir::BinOpKind::Div,
3901 BinOpKind::Rem => hir::BinOpKind::Rem,
3902 BinOpKind::And => hir::BinOpKind::And,
3903 BinOpKind::Or => hir::BinOpKind::Or,
3904 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3905 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3906 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3907 BinOpKind::Shl => hir::BinOpKind::Shl,
3908 BinOpKind::Shr => hir::BinOpKind::Shr,
3909 BinOpKind::Eq => hir::BinOpKind::Eq,
3910 BinOpKind::Lt => hir::BinOpKind::Lt,
3911 BinOpKind::Le => hir::BinOpKind::Le,
3912 BinOpKind::Ne => hir::BinOpKind::Ne,
3913 BinOpKind::Ge => hir::BinOpKind::Ge,
3914 BinOpKind::Gt => hir::BinOpKind::Gt,
3920 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3921 let node = match p.node {
3922 PatKind::Wild => hir::PatKind::Wild,
3923 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3924 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3925 // `None` can occur in body-less function signatures
3926 def @ None | def @ Some(Def::Local(_)) => {
3927 let canonical_id = match def {
3928 Some(Def::Local(id)) => id,
3932 hir::PatKind::Binding(
3933 self.lower_binding_mode(binding_mode),
3934 self.lower_node_id(canonical_id).hir_id,
3936 sub.as_ref().map(|x| self.lower_pat(x)),
3939 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3943 def: self.lower_def(def),
3944 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3949 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3950 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3951 let qpath = self.lower_qpath(
3955 ParamMode::Optional,
3956 ImplTraitContext::disallowed(),
3958 hir::PatKind::TupleStruct(
3960 pats.iter().map(|x| self.lower_pat(x)).collect(),
3964 PatKind::Path(ref qself, ref path) => {
3965 let qpath = self.lower_qpath(
3969 ParamMode::Optional,
3970 ImplTraitContext::disallowed(),
3972 hir::PatKind::Path(qpath)
3974 PatKind::Struct(ref path, ref fields, etc) => {
3975 let qpath = self.lower_qpath(
3979 ParamMode::Optional,
3980 ImplTraitContext::disallowed(),
3986 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
3990 node: hir::FieldPat {
3992 ident: f.node.ident,
3993 pat: self.lower_pat(&f.node.pat),
3994 is_shorthand: f.node.is_shorthand,
3999 hir::PatKind::Struct(qpath, fs, etc)
4001 PatKind::Tuple(ref elts, ddpos) => {
4002 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
4004 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
4005 PatKind::Ref(ref inner, mutbl) => {
4006 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
4008 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
4009 P(self.lower_expr(e1)),
4010 P(self.lower_expr(e2)),
4011 self.lower_range_end(end),
4013 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
4014 before.iter().map(|x| self.lower_pat(x)).collect(),
4015 slice.as_ref().map(|x| self.lower_pat(x)),
4016 after.iter().map(|x| self.lower_pat(x)).collect(),
4018 PatKind::Paren(ref inner) => return self.lower_pat(inner),
4019 PatKind::Mac(_) => panic!("Shouldn't exist here"),
4022 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(p.id);
4030 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
4032 RangeEnd::Included(_) => hir::RangeEnd::Included,
4033 RangeEnd::Excluded => hir::RangeEnd::Excluded,
4037 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
4038 self.with_new_scopes(|this| {
4039 let LoweredNodeId { node_id: _, hir_id } = this.lower_node_id(c.id);
4042 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
4047 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
4048 let kind = match e.node {
4049 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
4050 ExprKind::ObsoleteInPlace(..) => {
4051 self.sess.abort_if_errors();
4052 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
4054 ExprKind::Array(ref exprs) => {
4055 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
4057 ExprKind::Repeat(ref expr, ref count) => {
4058 let expr = P(self.lower_expr(expr));
4059 let count = self.lower_anon_const(count);
4060 hir::ExprKind::Repeat(expr, count)
4062 ExprKind::Tup(ref elts) => {
4063 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
4065 ExprKind::Call(ref f, ref args) => {
4066 let f = P(self.lower_expr(f));
4067 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
4069 ExprKind::MethodCall(ref seg, ref args) => {
4070 let hir_seg = P(self.lower_path_segment(
4073 ParamMode::Optional,
4075 ParenthesizedGenericArgs::Err,
4076 ImplTraitContext::disallowed(),
4079 let args = args.iter().map(|x| self.lower_expr(x)).collect();
4080 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
4082 ExprKind::Binary(binop, ref lhs, ref rhs) => {
4083 let binop = self.lower_binop(binop);
4084 let lhs = P(self.lower_expr(lhs));
4085 let rhs = P(self.lower_expr(rhs));
4086 hir::ExprKind::Binary(binop, lhs, rhs)
4088 ExprKind::Unary(op, ref ohs) => {
4089 let op = self.lower_unop(op);
4090 let ohs = P(self.lower_expr(ohs));
4091 hir::ExprKind::Unary(op, ohs)
4093 ExprKind::Lit(ref l) => hir::ExprKind::Lit((*l).clone()),
4094 ExprKind::Cast(ref expr, ref ty) => {
4095 let expr = P(self.lower_expr(expr));
4096 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4098 ExprKind::Type(ref expr, ref ty) => {
4099 let expr = P(self.lower_expr(expr));
4100 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4102 ExprKind::AddrOf(m, ref ohs) => {
4103 let m = self.lower_mutability(m);
4104 let ohs = P(self.lower_expr(ohs));
4105 hir::ExprKind::AddrOf(m, ohs)
4107 // More complicated than you might expect because the else branch
4108 // might be `if let`.
4109 ExprKind::If(ref cond, ref blk, ref else_opt) => {
4110 let else_opt = else_opt.as_ref().map(|els| {
4112 ExprKind::IfLet(..) => {
4113 // Wrap the `if let` expr in a block.
4114 let span = els.span;
4115 let els = P(self.lower_expr(els));
4116 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
4117 let blk = P(hir::Block {
4121 rules: hir::DefaultBlock,
4123 targeted_by_break: false,
4125 P(self.expr_block(blk, ThinVec::new()))
4127 _ => P(self.lower_expr(els)),
4131 let then_blk = self.lower_block(blk, false);
4132 let then_expr = self.expr_block(then_blk, ThinVec::new());
4134 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
4136 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4137 hir::ExprKind::While(
4138 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
4139 this.lower_block(body, false),
4140 this.lower_label(opt_label),
4143 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4144 hir::ExprKind::Loop(
4145 this.lower_block(body, false),
4146 this.lower_label(opt_label),
4147 hir::LoopSource::Loop,
4150 ExprKind::TryBlock(ref body) => {
4151 self.with_catch_scope(body.id, |this| {
4152 let unstable_span = this.mark_span_with_reason(
4153 CompilerDesugaringKind::TryBlock,
4156 Symbol::intern("try_trait"),
4159 let mut block = this.lower_block(body, true).into_inner();
4160 let tail = block.expr.take().map_or_else(
4162 let LoweredNodeId { node_id: _, hir_id } = this.next_id();
4163 let span = this.sess.source_map().end_point(unstable_span);
4166 node: hir::ExprKind::Tup(hir_vec![]),
4167 attrs: ThinVec::new(),
4171 |x: P<hir::Expr>| x.into_inner(),
4173 block.expr = Some(this.wrap_in_try_constructor(
4174 "from_ok", tail, unstable_span));
4175 hir::ExprKind::Block(P(block), None)
4178 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
4179 P(self.lower_expr(expr)),
4180 arms.iter().map(|x| self.lower_arm(x)).collect(),
4181 hir::MatchSource::Normal,
4183 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
4184 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
4185 this.with_new_scopes(|this| {
4186 let block = this.lower_block(block, false);
4187 this.expr_block(block, ThinVec::new())
4192 capture_clause, ref asyncness, movability, ref decl, ref body, fn_decl_span
4194 if let IsAsync::Async { closure_id, .. } = asyncness {
4195 let outer_decl = FnDecl {
4196 inputs: decl.inputs.clone(),
4197 output: FunctionRetTy::Default(fn_decl_span),
4200 // We need to lower the declaration outside the new scope, because we
4201 // have to conserve the state of being inside a loop condition for the
4202 // closure argument types.
4203 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
4205 self.with_new_scopes(|this| {
4206 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
4207 if capture_clause == CaptureBy::Ref &&
4208 !decl.inputs.is_empty()
4214 "`async` non-`move` closures with arguments \
4215 are not currently supported",
4217 .help("consider using `let` statements to manually capture \
4218 variables by reference before entering an \
4219 `async move` closure")
4223 // Transform `async |x: u8| -> X { ... }` into
4224 // `|x: u8| future_from_generator(|| -> X { ... })`.
4225 let body_id = this.lower_body(Some(&outer_decl), |this| {
4226 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
4229 let async_body = this.make_async_expr(
4230 capture_clause, *closure_id, async_ret_ty,
4232 this.with_new_scopes(|this| this.lower_expr(body))
4234 this.expr(fn_decl_span, async_body, ThinVec::new())
4236 hir::ExprKind::Closure(
4237 this.lower_capture_clause(capture_clause),
4245 // Lower outside new scope to preserve `is_in_loop_condition`.
4246 let fn_decl = self.lower_fn_decl(decl, None, false, None);
4248 self.with_new_scopes(|this| {
4249 let mut is_generator = false;
4250 let body_id = this.lower_body(Some(decl), |this| {
4251 let e = this.lower_expr(body);
4252 is_generator = this.is_generator;
4255 let generator_option = if is_generator {
4256 if !decl.inputs.is_empty() {
4261 "generators cannot have explicit arguments"
4263 this.sess.abort_if_errors();
4265 Some(match movability {
4266 Movability::Movable => hir::GeneratorMovability::Movable,
4267 Movability::Static => hir::GeneratorMovability::Static,
4270 if movability == Movability::Static {
4275 "closures cannot be static"
4280 hir::ExprKind::Closure(
4281 this.lower_capture_clause(capture_clause),
4290 ExprKind::Block(ref blk, opt_label) => {
4291 hir::ExprKind::Block(self.lower_block(blk,
4292 opt_label.is_some()),
4293 self.lower_label(opt_label))
4295 ExprKind::Assign(ref el, ref er) => {
4296 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
4298 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
4299 self.lower_binop(op),
4300 P(self.lower_expr(el)),
4301 P(self.lower_expr(er)),
4303 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
4304 ExprKind::Index(ref el, ref er) => {
4305 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
4307 // Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
4308 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
4309 let id = self.next_id();
4310 let e1 = self.lower_expr(e1);
4311 let e2 = self.lower_expr(e2);
4312 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
4313 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
4314 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
4315 let new_path = hir::QPath::TypeRelative(ty, new_seg);
4316 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
4317 hir::ExprKind::Call(new, hir_vec![e1, e2])
4319 ExprKind::Range(ref e1, ref e2, lims) => {
4320 use syntax::ast::RangeLimits::*;
4322 let path = match (e1, e2, lims) {
4323 (&None, &None, HalfOpen) => "RangeFull",
4324 (&Some(..), &None, HalfOpen) => "RangeFrom",
4325 (&None, &Some(..), HalfOpen) => "RangeTo",
4326 (&Some(..), &Some(..), HalfOpen) => "Range",
4327 (&None, &Some(..), Closed) => "RangeToInclusive",
4328 (&Some(..), &Some(..), Closed) => unreachable!(),
4329 (_, &None, Closed) => self.diagnostic()
4330 .span_fatal(e.span, "inclusive range with no end")
4334 let fields = e1.iter()
4335 .map(|e| ("start", e))
4336 .chain(e2.iter().map(|e| ("end", e)))
4338 let expr = P(self.lower_expr(&e));
4339 let ident = Ident::new(Symbol::intern(s), e.span);
4340 self.field(ident, expr, e.span)
4342 .collect::<P<[hir::Field]>>();
4344 let is_unit = fields.is_empty();
4345 let struct_path = ["ops", path];
4346 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
4347 let struct_path = hir::QPath::Resolved(None, P(struct_path));
4349 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(e.id);
4354 hir::ExprKind::Path(struct_path)
4356 hir::ExprKind::Struct(P(struct_path), fields, None)
4359 attrs: e.attrs.clone(),
4362 ExprKind::Path(ref qself, ref path) => {
4363 let qpath = self.lower_qpath(
4367 ParamMode::Optional,
4368 ImplTraitContext::disallowed(),
4370 hir::ExprKind::Path(qpath)
4372 ExprKind::Break(opt_label, ref opt_expr) => {
4373 let destination = if self.is_in_loop_condition && opt_label.is_none() {
4376 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4379 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4381 hir::ExprKind::Break(
4383 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
4386 ExprKind::Continue(opt_label) => {
4387 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
4390 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4393 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4396 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
4397 ExprKind::InlineAsm(ref asm) => {
4398 let hir_asm = hir::InlineAsm {
4399 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
4400 outputs: asm.outputs
4402 .map(|out| hir::InlineAsmOutput {
4403 constraint: out.constraint.clone(),
4405 is_indirect: out.is_indirect,
4406 span: out.expr.span,
4409 asm: asm.asm.clone(),
4410 asm_str_style: asm.asm_str_style,
4411 clobbers: asm.clobbers.clone().into(),
4412 volatile: asm.volatile,
4413 alignstack: asm.alignstack,
4414 dialect: asm.dialect,
4417 let outputs = asm.outputs
4419 .map(|out| self.lower_expr(&out.expr))
4421 let inputs = asm.inputs
4423 .map(|&(_, ref input)| self.lower_expr(input))
4425 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
4427 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4432 ParamMode::Optional,
4433 ImplTraitContext::disallowed(),
4435 fields.iter().map(|x| self.lower_field(x)).collect(),
4436 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4438 ExprKind::Paren(ref ex) => {
4439 let mut ex = self.lower_expr(ex);
4440 // Include parens in span, but only if it is a super-span.
4441 if e.span.contains(ex.span) {
4444 // Merge attributes into the inner expression.
4445 let mut attrs = e.attrs.clone();
4446 attrs.extend::<Vec<_>>(ex.attrs.into());
4451 ExprKind::Yield(ref opt_expr) => {
4452 self.is_generator = true;
4455 .map(|x| self.lower_expr(x))
4457 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
4459 hir::ExprKind::Yield(P(expr))
4462 ExprKind::Err => hir::ExprKind::Err,
4464 // Desugar `ExprIfLet`
4465 // from: `if let <pat> = <sub_expr> <body> [<else_opt>]`
4466 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4469 // match <sub_expr> {
4471 // _ => [<else_opt> | ()]
4474 let mut arms = vec![];
4476 // `<pat> => <body>`
4478 let body = self.lower_block(body, false);
4479 let body_expr = P(self.expr_block(body, ThinVec::new()));
4480 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4481 arms.push(self.arm(pats, body_expr));
4484 // _ => [<else_opt>|()]
4486 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4487 let wildcard_pattern = self.pat_wild(e.span);
4488 let body = if let Some(else_expr) = wildcard_arm {
4489 P(self.lower_expr(else_expr))
4491 self.expr_tuple(e.span, hir_vec![])
4493 arms.push(self.arm(hir_vec![wildcard_pattern], body));
4496 let contains_else_clause = else_opt.is_some();
4498 let sub_expr = P(self.lower_expr(sub_expr));
4500 hir::ExprKind::Match(
4503 hir::MatchSource::IfLetDesugar {
4504 contains_else_clause,
4509 // Desugar `ExprWhileLet`
4510 // from: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4511 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4514 // [opt_ident]: loop {
4515 // match <sub_expr> {
4521 // Note that the block AND the condition are evaluated in the loop scope.
4522 // This is done to allow `break` from inside the condition of the loop.
4523 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4525 this.lower_block(body, false),
4526 this.expr_break(e.span, ThinVec::new()),
4527 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4531 // `<pat> => <body>`
4533 let body_expr = P(self.expr_block(body, ThinVec::new()));
4534 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4535 self.arm(pats, body_expr)
4540 let pat_under = self.pat_wild(e.span);
4541 self.arm(hir_vec![pat_under], break_expr)
4544 // `match <sub_expr> { ... }`
4545 let arms = hir_vec![pat_arm, break_arm];
4546 let match_expr = self.expr(
4548 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4552 // `[opt_ident]: loop { ... }`
4553 let loop_block = P(self.block_expr(P(match_expr)));
4554 let loop_expr = hir::ExprKind::Loop(
4556 self.lower_label(opt_label),
4557 hir::LoopSource::WhileLet,
4559 // Add attributes to the outer returned expr node.
4563 // Desugar `ExprForLoop`
4564 // from: `[opt_ident]: for <pat> in <head> <body>`
4565 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4569 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4571 // [opt_ident]: loop {
4573 // match ::std::iter::Iterator::next(&mut iter) {
4574 // ::std::option::Option::Some(val) => __next = val,
4575 // ::std::option::Option::None => break
4577 // let <pat> = __next;
4578 // StmtKind::Expr(<body>);
4586 let mut head = self.lower_expr(head);
4587 let head_sp = head.span;
4588 let desugared_span = self.mark_span_with_reason(
4589 CompilerDesugaringKind::ForLoop,
4593 head.span = desugared_span;
4595 let iter = self.str_to_ident("iter");
4597 let next_ident = self.str_to_ident("__next");
4598 let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
4601 hir::BindingAnnotation::Mutable,
4604 // `::std::option::Option::Some(val) => next = val`
4606 let val_ident = self.str_to_ident("val");
4607 let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
4608 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat_hid));
4609 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat_hid));
4610 let assign = P(self.expr(
4612 hir::ExprKind::Assign(next_expr, val_expr),
4615 let some_pat = self.pat_some(pat.span, val_pat);
4616 self.arm(hir_vec![some_pat], assign)
4619 // `::std::option::Option::None => break`
4622 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4623 let pat = self.pat_none(e.span);
4624 self.arm(hir_vec![pat], break_expr)
4628 let (iter_pat, iter_pat_nid) = self.pat_ident_binding_mode(
4631 hir::BindingAnnotation::Mutable
4634 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4636 let iter = P(self.expr_ident(head_sp, iter, iter_pat_nid));
4637 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4638 let next_path = &["iter", "Iterator", "next"];
4639 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4640 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4641 let arms = hir_vec![pat_arm, break_arm];
4645 hir::ExprKind::Match(
4648 hir::MatchSource::ForLoopDesugar
4653 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
4654 let match_stmt = hir::Stmt {
4656 node: hir::StmtKind::Expr(match_expr),
4660 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat_hid));
4663 let next_let = self.stmt_let_pat(
4667 hir::LocalSource::ForLoopDesugar,
4670 // `let <pat> = __next`
4671 let pat = self.lower_pat(pat);
4672 let pat_let = self.stmt_let_pat(
4676 hir::LocalSource::ForLoopDesugar,
4679 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4680 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4681 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
4682 let body_stmt = hir::Stmt {
4684 node: hir::StmtKind::Expr(body_expr),
4688 let loop_block = P(self.block_all(
4690 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4694 // `[opt_ident]: loop { ... }`
4695 let loop_expr = hir::ExprKind::Loop(
4697 self.lower_label(opt_label),
4698 hir::LoopSource::ForLoop,
4700 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(e.id);
4701 let loop_expr = P(hir::Expr {
4705 attrs: ThinVec::new(),
4708 // `mut iter => { ... }`
4709 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4711 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4712 let into_iter_expr = {
4713 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4714 let into_iter = P(self.expr_std_path(
4715 head_sp, into_iter_path, None, ThinVec::new()));
4716 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4719 let match_expr = P(self.expr_match(
4723 hir::MatchSource::ForLoopDesugar,
4726 // `{ let _result = ...; _result }`
4727 // Underscore prevents an `unused_variables` lint if the head diverges.
4728 let result_ident = self.str_to_ident("_result");
4729 let (let_stmt, let_stmt_binding) =
4730 self.stmt_let(e.span, false, result_ident, match_expr);
4732 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4733 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4734 // Add the attributes to the outer returned expr node.
4735 return self.expr_block(block, e.attrs.clone());
4738 // Desugar `ExprKind::Try`
4740 ExprKind::Try(ref sub_expr) => {
4743 // match Try::into_result(<expr>) {
4744 // Ok(val) => #[allow(unreachable_code)] val,
4745 // Err(err) => #[allow(unreachable_code)]
4746 // // If there is an enclosing `catch {...}`
4747 // break 'catch_target Try::from_error(From::from(err)),
4749 // return Try::from_error(From::from(err)),
4752 let unstable_span = self.mark_span_with_reason(
4753 CompilerDesugaringKind::QuestionMark,
4756 Symbol::intern("try_trait")
4759 let try_span = self.sess.source_map().end_point(e.span);
4760 let try_span = self.mark_span_with_reason(
4761 CompilerDesugaringKind::QuestionMark,
4764 Symbol::intern("try_trait")
4768 // `Try::into_result(<expr>)`
4771 let sub_expr = self.lower_expr(sub_expr);
4773 let path = &["ops", "Try", "into_result"];
4774 let path = P(self.expr_std_path(
4775 unstable_span, path, None, ThinVec::new()));
4776 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4779 // `#[allow(unreachable_code)]`
4781 // `allow(unreachable_code)`
4783 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4784 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4785 let uc_nested = attr::mk_nested_word_item(uc_ident);
4786 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4788 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4790 let attrs = vec![attr];
4792 // `Ok(val) => #[allow(unreachable_code)] val,`
4794 let val_ident = self.str_to_ident("val");
4795 let (val_pat, val_pat_nid) = self.pat_ident(e.span, val_ident);
4796 let val_expr = P(self.expr_ident_with_attrs(
4800 ThinVec::from(attrs.clone()),
4802 let ok_pat = self.pat_ok(e.span, val_pat);
4804 self.arm(hir_vec![ok_pat], val_expr)
4807 // `Err(err) => #[allow(unreachable_code)]
4808 // return Try::from_error(From::from(err)),`
4810 let err_ident = self.str_to_ident("err");
4811 let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
4813 let path = &["convert", "From", "from"];
4814 let from = P(self.expr_std_path(
4815 try_span, path, None, ThinVec::new()));
4816 let err_expr = self.expr_ident(try_span, err_ident, err_local_nid);
4818 self.expr_call(try_span, from, hir_vec![err_expr])
4821 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4822 let thin_attrs = ThinVec::from(attrs);
4823 let catch_scope = self.catch_scopes.last().map(|x| *x);
4824 let ret_expr = if let Some(catch_node) = catch_scope {
4825 let target_id = Ok(self.lower_node_id(catch_node).hir_id);
4828 hir::ExprKind::Break(
4833 Some(from_err_expr),
4838 P(self.expr(try_span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4841 let err_pat = self.pat_err(try_span, err_local);
4842 self.arm(hir_vec![err_pat], ret_expr)
4845 hir::ExprKind::Match(
4847 hir_vec![err_arm, ok_arm],
4848 hir::MatchSource::TryDesugar,
4852 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4855 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(e.id);
4861 attrs: e.attrs.clone(),
4865 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
4866 smallvec![match s.node {
4867 StmtKind::Local(ref l) => {
4868 let (l, item_ids) = self.lower_local(l);
4869 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
4872 let item_id = hir::ItemId { id: self.lower_node_id(item_id).hir_id };
4873 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
4877 node: hir::StmtKind::Item(item_id),
4883 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(s.id);
4887 node: hir::StmtKind::Local(P(l)),
4893 StmtKind::Item(ref it) => {
4894 // Can only use the ID once.
4895 let mut id = Some(s.id);
4896 return self.lower_item_id(it)
4899 let LoweredNodeId { node_id: _, hir_id } = id.take()
4900 .map(|id| self.lower_node_id(id))
4901 .unwrap_or_else(|| self.next_id());
4905 node: hir::StmtKind::Item(item_id),
4911 StmtKind::Expr(ref e) => {
4912 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(s.id);
4916 node: hir::StmtKind::Expr(P(self.lower_expr(e))),
4920 StmtKind::Semi(ref e) => {
4921 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(s.id);
4925 node: hir::StmtKind::Semi(P(self.lower_expr(e))),
4929 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4933 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4935 CaptureBy::Value => hir::CaptureByValue,
4936 CaptureBy::Ref => hir::CaptureByRef,
4940 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4941 /// the address space of that item instead of the item currently being
4942 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4943 /// lower a `Visibility` value although we haven't lowered the owning
4944 /// `ImplItem` in question yet.
4945 fn lower_visibility(
4948 explicit_owner: Option<NodeId>,
4949 ) -> hir::Visibility {
4950 let node = match v.node {
4951 VisibilityKind::Public => hir::VisibilityKind::Public,
4952 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4953 VisibilityKind::Restricted { ref path, id } => {
4954 debug!("lower_visibility: restricted path id = {:?}", id);
4955 let lowered_id = if let Some(owner) = explicit_owner {
4956 self.lower_node_id_with_owner(id, owner)
4958 self.lower_node_id(id)
4960 let def = self.expect_full_def(id);
4961 let def = self.lower_def(def);
4962 hir::VisibilityKind::Restricted {
4963 path: P(self.lower_path_extra(
4966 ParamMode::Explicit,
4969 hir_id: lowered_id.hir_id,
4972 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4974 respan(v.span, node)
4977 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4979 Defaultness::Default => hir::Defaultness::Default {
4980 has_value: has_value,
4982 Defaultness::Final => {
4984 hir::Defaultness::Final
4989 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4991 BlockCheckMode::Default => hir::DefaultBlock,
4992 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4996 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4998 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4999 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
5000 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
5001 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
5005 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
5007 CompilerGenerated => hir::CompilerGenerated,
5008 UserProvided => hir::UserProvided,
5012 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
5014 ImplPolarity::Positive => hir::ImplPolarity::Positive,
5015 ImplPolarity::Negative => hir::ImplPolarity::Negative,
5019 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
5021 TraitBoundModifier::None => hir::TraitBoundModifier::None,
5022 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
5026 // Helper methods for building HIR.
5028 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
5037 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
5038 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
5045 is_shorthand: false,
5049 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
5050 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
5051 P(self.expr(span, expr_break, attrs))
5058 args: hir::HirVec<hir::Expr>,
5060 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
5063 fn expr_ident(&mut self, span: Span, ident: Ident, binding: hir::HirId) -> hir::Expr {
5064 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
5067 fn expr_ident_with_attrs(
5071 binding: hir::HirId,
5072 attrs: ThinVec<Attribute>,
5074 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
5078 def: Def::Local(binding),
5079 segments: hir_vec![hir::PathSegment::from_ident(ident)],
5083 self.expr(span, expr_path, attrs)
5086 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
5087 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
5093 components: &[&str],
5094 params: Option<P<hir::GenericArgs>>,
5095 attrs: ThinVec<Attribute>,
5097 let path = self.std_path(span, components, params, true);
5100 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
5109 arms: hir::HirVec<hir::Arm>,
5110 source: hir::MatchSource,
5112 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
5115 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
5116 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
5119 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
5120 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
5123 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
5124 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
5136 ex: Option<P<hir::Expr>>,
5138 source: hir::LocalSource,
5140 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
5142 let local = hir::Local {
5148 attrs: ThinVec::new(),
5152 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
5155 node: hir::StmtKind::Local(P(local)),
5166 ) -> (hir::Stmt, hir::HirId) {
5167 let (pat, pat_hid) = if mutbl {
5168 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
5170 self.pat_ident(sp, ident)
5174 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
5179 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
5180 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
5186 stmts: hir::HirVec<hir::Stmt>,
5187 expr: Option<P<hir::Expr>>,
5189 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
5195 rules: hir::DefaultBlock,
5197 targeted_by_break: false,
5201 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5202 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
5205 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5206 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
5209 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5210 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
5213 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
5214 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
5220 components: &[&str],
5221 subpats: hir::HirVec<P<hir::Pat>>,
5223 let path = self.std_path(span, components, None, true);
5224 let qpath = hir::QPath::Resolved(None, P(path));
5225 let pt = if subpats.is_empty() {
5226 hir::PatKind::Path(qpath)
5228 hir::PatKind::TupleStruct(qpath, subpats, None)
5233 fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<hir::Pat>, hir::HirId) {
5234 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
5237 fn pat_ident_binding_mode(
5241 bm: hir::BindingAnnotation,
5242 ) -> (P<hir::Pat>, hir::HirId) {
5243 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
5248 node: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
5255 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
5256 self.pat(span, hir::PatKind::Wild)
5259 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
5260 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
5268 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
5269 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
5270 /// The path is also resolved according to `is_value`.
5274 components: &[&str],
5275 params: Option<P<hir::GenericArgs>>,
5278 let mut path = self.resolver
5279 .resolve_str_path(span, self.crate_root, components, is_value);
5280 path.segments.last_mut().unwrap().args = params;
5283 for seg in path.segments.iter_mut() {
5284 if seg.hir_id.is_some() {
5285 seg.hir_id = Some(self.next_id().hir_id);
5291 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
5293 let node = match qpath {
5294 hir::QPath::Resolved(None, path) => {
5295 // Turn trait object paths into `TyKind::TraitObject` instead.
5297 Def::Trait(_) | Def::TraitAlias(_) => {
5298 let principal = hir::PolyTraitRef {
5299 bound_generic_params: hir::HirVec::new(),
5300 trait_ref: hir::TraitRef {
5301 path: path.and_then(|path| path),
5302 hir_ref_id: id.hir_id,
5307 // The original ID is taken by the `PolyTraitRef`,
5308 // so the `Ty` itself needs a different one.
5309 id = self.next_id();
5310 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
5312 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
5315 _ => hir::TyKind::Path(qpath),
5324 /// Invoked to create the lifetime argument for a type `&T`
5325 /// with no explicit lifetime.
5326 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
5327 match self.anonymous_lifetime_mode {
5328 // Intercept when we are in an impl header or async fn and introduce an in-band
5330 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
5332 AnonymousLifetimeMode::CreateParameter => {
5333 let fresh_name = self.collect_fresh_in_band_lifetime(span);
5334 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
5338 name: hir::LifetimeName::Param(fresh_name),
5342 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5344 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5346 AnonymousLifetimeMode::Replace(replacement) => {
5347 self.new_replacement_lifetime(replacement, span)
5352 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
5353 /// return a "error lifetime".
5354 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
5355 let (id, msg, label) = match id {
5356 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
5359 self.next_id().node_id,
5360 "`&` without an explicit lifetime name cannot be used here",
5361 "explicit lifetime name needed here",
5365 let mut err = struct_span_err!(
5372 err.span_label(span, label);
5375 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5378 /// Invoked to create the lifetime argument(s) for a path like
5379 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
5380 /// sorts of cases are deprecated. This may therefore report a warning or an
5381 /// error, depending on the mode.
5382 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
5384 .map(|_| self.elided_path_lifetime(span))
5388 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
5389 match self.anonymous_lifetime_mode {
5390 // N.B., We intentionally ignore the create-parameter mode here
5391 // and instead "pass through" to resolve-lifetimes, which will then
5392 // report an error. This is because we don't want to support
5393 // impl elision for deprecated forms like
5395 // impl Foo for std::cell::Ref<u32> // note lack of '_
5396 AnonymousLifetimeMode::CreateParameter |
5397 // This is the normal case.
5398 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5400 AnonymousLifetimeMode::Replace(replacement) => {
5401 self.new_replacement_lifetime(replacement, span)
5404 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5408 /// Invoked to create the lifetime argument(s) for an elided trait object
5409 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
5410 /// when the bound is written, even if it is written with `'_` like in
5411 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
5412 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
5413 match self.anonymous_lifetime_mode {
5414 // NB. We intentionally ignore the create-parameter mode here.
5415 // and instead "pass through" to resolve-lifetimes, which will apply
5416 // the object-lifetime-defaulting rules. Elided object lifetime defaults
5417 // do not act like other elided lifetimes. In other words, given this:
5419 // impl Foo for Box<dyn Debug>
5421 // we do not introduce a fresh `'_` to serve as the bound, but instead
5422 // ultimately translate to the equivalent of:
5424 // impl Foo for Box<dyn Debug + 'static>
5426 // `resolve_lifetime` has the code to make that happen.
5427 AnonymousLifetimeMode::CreateParameter => {}
5429 AnonymousLifetimeMode::ReportError => {
5430 // ReportError applies to explicit use of `'_`.
5433 // This is the normal case.
5434 AnonymousLifetimeMode::PassThrough => {}
5436 // We don't need to do any replacement here as this lifetime
5437 // doesn't refer to an elided lifetime elsewhere in the function
5439 AnonymousLifetimeMode::Replace(_) => {}
5442 self.new_implicit_lifetime(span)
5445 fn new_replacement_lifetime(
5447 replacement: LtReplacement,
5449 ) -> hir::Lifetime {
5450 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
5451 self.replace_elided_lifetime(hir_id, span, replacement)
5454 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
5455 let LoweredNodeId { node_id: _, hir_id } = self.next_id();
5460 name: hir::LifetimeName::Implicit,
5464 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
5465 self.sess.buffer_lint_with_diagnostic(
5466 builtin::BARE_TRAIT_OBJECTS,
5469 "trait objects without an explicit `dyn` are deprecated",
5470 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
5474 fn wrap_in_try_constructor(
5476 method: &'static str,
5478 unstable_span: Span,
5480 let path = &["ops", "Try", method];
5481 let from_err = P(self.expr_std_path(unstable_span, path, None,
5483 P(self.expr_call(e.span, from_err, hir_vec![e]))
5487 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5488 // Sorting by span ensures that we get things in order within a
5489 // file, and also puts the files in a sensible order.
5490 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5491 body_ids.sort_by_key(|b| bodies[b].value.span);