1 // ignore-tidy-filelength
3 //! Lowers the AST to the HIR.
5 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
6 //! much like a fold. Where lowering involves a bit more work things get more
7 //! interesting and there are some invariants you should know about. These mostly
8 //! concern spans and IDs.
10 //! Spans are assigned to AST nodes during parsing and then are modified during
11 //! expansion to indicate the origin of a node and the process it went through
12 //! being expanded. IDs are assigned to AST nodes just before lowering.
14 //! For the simpler lowering steps, IDs and spans should be preserved. Unlike
15 //! expansion we do not preserve the process of lowering in the spans, so spans
16 //! should not be modified here. When creating a new node (as opposed to
17 //! 'folding' an existing one), then you create a new ID using `next_id()`.
19 //! You must ensure that IDs are unique. That means that you should only use the
20 //! ID from an AST node in a single HIR node (you can assume that AST node-IDs
21 //! are unique). Every new node must have a unique ID. Avoid cloning HIR nodes.
22 //! If you do, you must then set the new node's ID to a fresh one.
24 //! Spans are used for error messages and for tools to map semantics back to
25 //! source code. It is therefore not as important with spans as IDs to be strict
26 //! about use (you can't break the compiler by screwing up a span). Obviously, a
27 //! HIR node can only have a single span. But multiple nodes can have the same
28 //! span and spans don't need to be kept in order, etc. Where code is preserved
29 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
30 //! new it is probably best to give a span for the whole AST node being lowered.
31 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
32 //! get confused if the spans from leaf AST nodes occur in multiple places
33 //! in the HIR, especially for multiple identifiers.
35 use crate::dep_graph::DepGraph;
36 use crate::hir::{self, ParamName};
37 use crate::hir::HirVec;
38 use crate::hir::map::{DefKey, DefPathData, Definitions};
39 use crate::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
40 use crate::hir::def::{Res, DefKind, PartialRes, PerNS};
41 use crate::hir::{GenericArg, ConstArg};
42 use crate::hir::ptr::P;
43 use crate::lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
44 ELIDED_LIFETIMES_IN_PATHS};
45 use crate::middle::cstore::CrateStore;
46 use crate::session::Session;
47 use crate::session::config::nightly_options;
48 use crate::util::common::FN_OUTPUT_NAME;
49 use crate::util::nodemap::{DefIdMap, NodeMap};
50 use errors::Applicability;
51 use rustc_data_structures::fx::FxHashSet;
52 use rustc_data_structures::indexed_vec::IndexVec;
53 use rustc_data_structures::thin_vec::ThinVec;
54 use rustc_data_structures::sync::Lrc;
56 use std::collections::{BTreeSet, BTreeMap};
58 use smallvec::SmallVec;
61 use syntax::ptr::P as AstP;
64 use syntax::ext::hygiene::ExpnId;
65 use syntax::print::pprust;
66 use syntax::source_map::{respan, ExpnInfo, ExpnKind, DesugaringKind, Spanned};
67 use syntax::symbol::{kw, sym, Symbol};
68 use syntax::tokenstream::{TokenStream, TokenTree};
69 use syntax::parse::token::{self, Token};
70 use syntax::visit::{self, Visitor};
71 use syntax_pos::{DUMMY_SP, Span};
73 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
75 pub struct LoweringContext<'a> {
76 crate_root: Option<Symbol>,
78 /// Used to assign ids to HIR nodes that do not directly correspond to an AST node.
81 cstore: &'a dyn CrateStore,
83 resolver: &'a mut dyn Resolver,
85 /// The items being lowered are collected here.
86 items: BTreeMap<hir::HirId, hir::Item>,
88 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
89 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
90 bodies: BTreeMap<hir::BodyId, hir::Body>,
91 exported_macros: Vec<hir::MacroDef>,
92 non_exported_macro_attrs: Vec<ast::Attribute>,
94 trait_impls: BTreeMap<DefId, Vec<hir::HirId>>,
96 modules: BTreeMap<NodeId, hir::ModuleItems>,
98 generator_kind: Option<hir::GeneratorKind>,
100 /// Used to get the current `fn`'s def span to point to when using `await`
101 /// outside of an `async fn`.
102 current_item: Option<Span>,
104 catch_scopes: Vec<NodeId>,
105 loop_scopes: Vec<NodeId>,
106 is_in_loop_condition: bool,
107 is_in_trait_impl: bool,
108 is_in_dyn_type: bool,
110 /// What to do when we encounter either an "anonymous lifetime
111 /// reference". The term "anonymous" is meant to encompass both
112 /// `'_` lifetimes as well as fully elided cases where nothing is
113 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
114 anonymous_lifetime_mode: AnonymousLifetimeMode,
116 /// Used to create lifetime definitions from in-band lifetime usages.
117 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
118 /// When a named lifetime is encountered in a function or impl header and
119 /// has not been defined
120 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
121 /// to this list. The results of this list are then added to the list of
122 /// lifetime definitions in the corresponding impl or function generics.
123 lifetimes_to_define: Vec<(Span, ParamName)>,
125 /// Whether or not in-band lifetimes are being collected. This is used to
126 /// indicate whether or not we're in a place where new lifetimes will result
127 /// in in-band lifetime definitions, such a function or an impl header,
128 /// including implicit lifetimes from `impl_header_lifetime_elision`.
129 is_collecting_in_band_lifetimes: bool,
131 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
132 /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
133 /// against this list to see if it is already in-scope, or if a definition
134 /// needs to be created for it.
135 in_scope_lifetimes: Vec<Ident>,
137 current_module: NodeId,
139 type_def_lifetime_params: DefIdMap<usize>,
141 current_hir_id_owner: Vec<(DefIndex, u32)>,
142 item_local_id_counters: NodeMap<u32>,
143 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
145 allow_try_trait: Option<Lrc<[Symbol]>>,
146 allow_gen_future: Option<Lrc<[Symbol]>>,
150 /// Resolve a path generated by the lowerer when expanding `for`, `if let`, etc.
157 /// Obtain resolution for a `NodeId` with a single resolution.
158 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
160 /// Obtain per-namespace resolutions for `use` statement with the given `NoedId`.
161 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
163 /// Obtain resolution for a label with the given `NodeId`.
164 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
166 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
167 /// This should only return `None` during testing.
168 fn definitions(&mut self) -> &mut Definitions;
170 /// Given suffix `["b", "c", "d"]`, creates an AST path for `[::crate_root]::b::c::d` and
171 /// resolves it based on `is_value`.
175 crate_root: Option<Symbol>,
176 components: &[Symbol],
178 ) -> (ast::Path, Res<NodeId>);
181 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
182 /// and if so, what meaning it has.
184 enum ImplTraitContext<'a> {
185 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
186 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
187 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
189 /// Newly generated parameters should be inserted into the given `Vec`.
190 Universal(&'a mut Vec<hir::GenericParam>),
192 /// Treat `impl Trait` as shorthand for a new existential parameter.
193 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
194 /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
196 /// We optionally store a `DefId` for the parent item here so we can look up necessary
197 /// information later. It is `None` when no information about the context should be stored
198 /// (e.g., for consts and statics).
199 Existential(Option<DefId> /* fn def-ID */),
201 /// `impl Trait` is not accepted in this position.
202 Disallowed(ImplTraitPosition),
205 /// Position in which `impl Trait` is disallowed.
206 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
207 enum ImplTraitPosition {
208 /// Disallowed in `let` / `const` / `static` bindings.
211 /// All other posiitons.
215 impl<'a> ImplTraitContext<'a> {
217 fn disallowed() -> Self {
218 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
221 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
222 use self::ImplTraitContext::*;
224 Universal(params) => Universal(params),
225 Existential(fn_def_id) => Existential(*fn_def_id),
226 Disallowed(pos) => Disallowed(*pos),
233 cstore: &dyn CrateStore,
234 dep_graph: &DepGraph,
236 resolver: &mut dyn Resolver,
238 // We're constructing the HIR here; we don't care what we will
239 // read, since we haven't even constructed the *input* to
241 dep_graph.assert_ignored();
244 crate_root: sess.parse_sess.injected_crate_name.try_get().copied(),
248 items: BTreeMap::new(),
249 trait_items: BTreeMap::new(),
250 impl_items: BTreeMap::new(),
251 bodies: BTreeMap::new(),
252 trait_impls: BTreeMap::new(),
253 modules: BTreeMap::new(),
254 exported_macros: Vec::new(),
255 non_exported_macro_attrs: Vec::new(),
256 catch_scopes: Vec::new(),
257 loop_scopes: Vec::new(),
258 is_in_loop_condition: false,
259 is_in_trait_impl: false,
260 is_in_dyn_type: false,
261 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
262 type_def_lifetime_params: Default::default(),
263 current_module: CRATE_NODE_ID,
264 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
265 item_local_id_counters: Default::default(),
266 node_id_to_hir_id: IndexVec::new(),
267 generator_kind: None,
269 lifetimes_to_define: Vec::new(),
270 is_collecting_in_band_lifetimes: false,
271 in_scope_lifetimes: Vec::new(),
272 allow_try_trait: Some([sym::try_trait][..].into()),
273 allow_gen_future: Some([sym::gen_future][..].into()),
277 #[derive(Copy, Clone, PartialEq)]
279 /// Any path in a type context.
281 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
283 /// The `module::Type` in `module::Type::method` in an expression.
287 enum ParenthesizedGenericArgs {
293 /// What to do when we encounter an **anonymous** lifetime
294 /// reference. Anonymous lifetime references come in two flavors. You
295 /// have implicit, or fully elided, references to lifetimes, like the
296 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
297 /// or `Ref<'_, T>`. These often behave the same, but not always:
299 /// - certain usages of implicit references are deprecated, like
300 /// `Ref<T>`, and we sometimes just give hard errors in those cases
302 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
303 /// the same as `Box<dyn Foo + '_>`.
305 /// We describe the effects of the various modes in terms of three cases:
307 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
308 /// of a `&` (e.g., the missing lifetime in something like `&T`)
309 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
310 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
311 /// elided bounds follow special rules. Note that this only covers
312 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
313 /// '_>` is a case of "modern" elision.
314 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
315 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
316 /// non-deprecated equivalent.
318 /// Currently, the handling of lifetime elision is somewhat spread out
319 /// between HIR lowering and -- as described below -- the
320 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
321 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
322 /// everything into HIR lowering.
323 #[derive(Copy, Clone)]
324 enum AnonymousLifetimeMode {
325 /// For **Modern** cases, create a new anonymous region parameter
326 /// and reference that.
328 /// For **Dyn Bound** cases, pass responsibility to
329 /// `resolve_lifetime` code.
331 /// For **Deprecated** cases, report an error.
334 /// Give a hard error when either `&` or `'_` is written. Used to
335 /// rule out things like `where T: Foo<'_>`. Does not imply an
336 /// error on default object bounds (e.g., `Box<dyn Foo>`).
339 /// Pass responsibility to `resolve_lifetime` code for all cases.
342 /// Used in the return types of `async fn` where there exists
343 /// exactly one argument-position elided lifetime.
345 /// In `async fn`, we lower the arguments types using the `CreateParameter`
346 /// mode, meaning that non-`dyn` elided lifetimes are assigned a fresh name.
347 /// If any corresponding elided lifetimes appear in the output, we need to
348 /// replace them with references to the fresh name assigned to the corresponding
349 /// elided lifetime in the arguments.
351 /// For **Modern cases**, replace the anonymous parameter with a
352 /// reference to a specific freshly-named lifetime that was
353 /// introduced in argument
355 /// For **Dyn Bound** cases, pass responsibility to
356 /// `resole_lifetime` code.
357 Replace(LtReplacement),
360 /// The type of elided lifetime replacement to perform on `async fn` return types.
361 #[derive(Copy, Clone)]
363 /// Fresh name introduced by the single non-dyn elided lifetime
364 /// in the arguments of the async fn.
367 /// There is no single non-dyn elided lifetime because no lifetimes
368 /// appeared in the arguments.
371 /// There is no single non-dyn elided lifetime because multiple
372 /// lifetimes appeared in the arguments.
376 /// Calculates the `LtReplacement` to use for elided lifetimes in the return
377 /// type based on the fresh elided lifetimes introduced in argument position.
378 fn get_elided_lt_replacement(arg_position_lifetimes: &[(Span, ParamName)]) -> LtReplacement {
379 match arg_position_lifetimes {
380 [] => LtReplacement::NoLifetimes,
381 [(_span, param)] => LtReplacement::Some(*param),
382 _ => LtReplacement::MultipleLifetimes,
386 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[NodeId; 1]> }
388 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
389 fn visit_ty(&mut self, ty: &'a Ty) {
395 TyKind::ImplTrait(id, _) => self.ids.push(id),
398 visit::walk_ty(self, ty);
401 fn visit_path_segment(
404 path_segment: &'v PathSegment,
406 if let Some(ref p) = path_segment.args {
407 if let GenericArgs::Parenthesized(_) = **p {
411 visit::walk_path_segment(self, path_span, path_segment)
415 impl<'a> LoweringContext<'a> {
416 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
417 /// Full-crate AST visitor that inserts into a fresh
418 /// `LoweringContext` any information that may be
419 /// needed from arbitrary locations in the crate,
420 /// e.g., the number of lifetime generic parameters
421 /// declared for every type and trait definition.
422 struct MiscCollector<'tcx, 'interner> {
423 lctx: &'tcx mut LoweringContext<'interner>,
424 hir_id_owner: Option<NodeId>,
427 impl MiscCollector<'_, '_> {
428 fn allocate_use_tree_hir_id_counters(
434 UseTreeKind::Simple(_, id1, id2) => {
435 for &id in &[id1, id2] {
436 self.lctx.resolver.definitions().create_def_with_parent(
443 self.lctx.allocate_hir_id_counter(id);
446 UseTreeKind::Glob => (),
447 UseTreeKind::Nested(ref trees) => {
448 for &(ref use_tree, id) in trees {
449 let hir_id = self.lctx.allocate_hir_id_counter(id);
450 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
456 fn with_hir_id_owner<F, T>(&mut self, owner: Option<NodeId>, f: F) -> T
458 F: FnOnce(&mut Self) -> T,
460 let old = mem::replace(&mut self.hir_id_owner, owner);
462 self.hir_id_owner = old;
467 impl<'tcx, 'interner> Visitor<'tcx> for MiscCollector<'tcx, 'interner> {
468 fn visit_pat(&mut self, p: &'tcx Pat) {
470 // Doesn't generate a HIR node
471 PatKind::Paren(..) | PatKind::Rest => {},
473 if let Some(owner) = self.hir_id_owner {
474 self.lctx.lower_node_id_with_owner(p.id, owner);
479 visit::walk_pat(self, p)
482 fn visit_item(&mut self, item: &'tcx Item) {
483 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
486 ItemKind::Struct(_, ref generics)
487 | ItemKind::Union(_, ref generics)
488 | ItemKind::Enum(_, ref generics)
489 | ItemKind::Ty(_, ref generics)
490 | ItemKind::Existential(_, ref generics)
491 | ItemKind::Trait(_, _, ref generics, ..) => {
492 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
496 .filter(|param| match param.kind {
497 ast::GenericParamKind::Lifetime { .. } => true,
501 self.lctx.type_def_lifetime_params.insert(def_id, count);
503 ItemKind::Use(ref use_tree) => {
504 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
509 self.with_hir_id_owner(Some(item.id), |this| {
510 visit::walk_item(this, item);
514 fn visit_trait_item(&mut self, item: &'tcx TraitItem) {
515 self.lctx.allocate_hir_id_counter(item.id);
518 TraitItemKind::Method(_, None) => {
519 // Ignore patterns in trait methods without bodies
520 self.with_hir_id_owner(None, |this| {
521 visit::walk_trait_item(this, item)
524 _ => self.with_hir_id_owner(Some(item.id), |this| {
525 visit::walk_trait_item(this, item);
530 fn visit_impl_item(&mut self, item: &'tcx ImplItem) {
531 self.lctx.allocate_hir_id_counter(item.id);
532 self.with_hir_id_owner(Some(item.id), |this| {
533 visit::walk_impl_item(this, item);
537 fn visit_foreign_item(&mut self, i: &'tcx ForeignItem) {
538 // Ignore patterns in foreign items
539 self.with_hir_id_owner(None, |this| {
540 visit::walk_foreign_item(this, i)
544 fn visit_ty(&mut self, t: &'tcx Ty) {
546 // Mirrors the case in visit::walk_ty
547 TyKind::BareFn(ref f) => {
553 // Mirrors visit::walk_fn_decl
554 for argument in &f.decl.inputs {
555 // We don't lower the ids of argument patterns
556 self.with_hir_id_owner(None, |this| {
557 this.visit_pat(&argument.pat);
559 self.visit_ty(&argument.ty)
561 self.visit_fn_ret_ty(&f.decl.output)
563 _ => visit::walk_ty(self, t),
568 struct ItemLowerer<'tcx, 'interner> {
569 lctx: &'tcx mut LoweringContext<'interner>,
572 impl<'tcx, 'interner> ItemLowerer<'tcx, 'interner> {
573 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
575 F: FnOnce(&mut Self),
577 let old = self.lctx.is_in_trait_impl;
578 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
584 self.lctx.is_in_trait_impl = old;
588 impl<'tcx, 'interner> Visitor<'tcx> for ItemLowerer<'tcx, 'interner> {
589 fn visit_mod(&mut self, m: &'tcx Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
590 self.lctx.modules.insert(n, hir::ModuleItems {
591 items: BTreeSet::new(),
592 trait_items: BTreeSet::new(),
593 impl_items: BTreeSet::new(),
596 let old = self.lctx.current_module;
597 self.lctx.current_module = n;
598 visit::walk_mod(self, m);
599 self.lctx.current_module = old;
602 fn visit_item(&mut self, item: &'tcx Item) {
603 let mut item_hir_id = None;
604 self.lctx.with_hir_id_owner(item.id, |lctx| {
605 if let Some(hir_item) = lctx.lower_item(item) {
606 item_hir_id = Some(hir_item.hir_id);
607 lctx.insert_item(hir_item);
611 if let Some(hir_id) = item_hir_id {
612 self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
613 let this = &mut ItemLowerer { lctx: this };
614 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
615 this.with_trait_impl_ref(opt_trait_ref, |this| {
616 visit::walk_item(this, item)
619 visit::walk_item(this, item);
625 fn visit_trait_item(&mut self, item: &'tcx TraitItem) {
626 self.lctx.with_hir_id_owner(item.id, |lctx| {
627 let hir_item = lctx.lower_trait_item(item);
628 let id = hir::TraitItemId { hir_id: hir_item.hir_id };
629 lctx.trait_items.insert(id, hir_item);
630 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
633 visit::walk_trait_item(self, item);
636 fn visit_impl_item(&mut self, item: &'tcx ImplItem) {
637 self.lctx.with_hir_id_owner(item.id, |lctx| {
638 let hir_item = lctx.lower_impl_item(item);
639 let id = hir::ImplItemId { hir_id: hir_item.hir_id };
640 lctx.impl_items.insert(id, hir_item);
641 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
643 visit::walk_impl_item(self, item);
647 self.lower_node_id(CRATE_NODE_ID);
648 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
650 visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
651 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
653 let module = self.lower_mod(&c.module);
654 let attrs = self.lower_attrs(&c.attrs);
655 let body_ids = body_ids(&self.bodies);
659 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
665 exported_macros: hir::HirVec::from(self.exported_macros),
666 non_exported_macro_attrs: hir::HirVec::from(self.non_exported_macro_attrs),
668 trait_items: self.trait_items,
669 impl_items: self.impl_items,
672 trait_impls: self.trait_impls,
673 modules: self.modules,
677 fn insert_item(&mut self, item: hir::Item) {
678 let id = item.hir_id;
679 // FIXME: Use `debug_asset-rt`.
680 assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
681 self.items.insert(id, item);
682 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
685 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
686 // Set up the counter if needed.
687 self.item_local_id_counters.entry(owner).or_insert(0);
688 // Always allocate the first `HirId` for the owner itself.
689 let lowered = self.lower_node_id_with_owner(owner, owner);
690 debug_assert_eq!(lowered.local_id.as_u32(), 0);
694 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> hir::HirId
696 F: FnOnce(&mut Self) -> hir::HirId,
698 if ast_node_id == DUMMY_NODE_ID {
699 return hir::DUMMY_HIR_ID;
702 let min_size = ast_node_id.as_usize() + 1;
704 if min_size > self.node_id_to_hir_id.len() {
705 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
708 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
710 if existing_hir_id == hir::DUMMY_HIR_ID {
711 // Generate a new `HirId`.
712 let hir_id = alloc_hir_id(self);
713 self.node_id_to_hir_id[ast_node_id] = hir_id;
721 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
723 F: FnOnce(&mut Self) -> T,
725 let counter = self.item_local_id_counters
726 .insert(owner, HIR_ID_COUNTER_LOCKED)
727 .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
728 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
729 self.current_hir_id_owner.push((def_index, counter));
731 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
733 debug_assert!(def_index == new_def_index);
734 debug_assert!(new_counter >= counter);
736 let prev = self.item_local_id_counters
737 .insert(owner, new_counter)
739 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
743 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
744 /// the `LoweringContext`'s `NodeId => HirId` map.
745 /// Take care not to call this method if the resulting `HirId` is then not
746 /// actually used in the HIR, as that would trigger an assertion in the
747 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
748 /// properly. Calling the method twice with the same `NodeId` is fine though.
749 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
750 self.lower_node_id_generic(ast_node_id, |this| {
751 let &mut (def_index, ref mut local_id_counter) =
752 this.current_hir_id_owner.last_mut().unwrap();
753 let local_id = *local_id_counter;
754 *local_id_counter += 1;
757 local_id: hir::ItemLocalId::from_u32(local_id),
762 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
763 self.lower_node_id_generic(ast_node_id, |this| {
764 let local_id_counter = this
765 .item_local_id_counters
767 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
768 let local_id = *local_id_counter;
770 // We want to be sure not to modify the counter in the map while it
771 // is also on the stack. Otherwise we'll get lost updates when writing
772 // back from the stack to the map.
773 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
775 *local_id_counter += 1;
779 .opt_def_index(owner)
780 .expect("you forgot to call `create_def_with_parent` or are lowering node-IDs \
781 that do not belong to the current owner");
785 local_id: hir::ItemLocalId::from_u32(local_id),
790 fn generator_movability_for_fn(
794 generator_kind: Option<hir::GeneratorKind>,
795 movability: Movability,
796 ) -> Option<hir::GeneratorMovability> {
797 match generator_kind {
798 Some(hir::GeneratorKind::Gen) => {
799 if !decl.inputs.is_empty() {
804 "generators cannot have explicit arguments"
806 self.sess.abort_if_errors();
808 Some(match movability {
809 Movability::Movable => hir::GeneratorMovability::Movable,
810 Movability::Static => hir::GeneratorMovability::Static,
813 Some(hir::GeneratorKind::Async) => {
814 bug!("non-`async` closure body turned `async` during lowering");
817 if movability == Movability::Static {
822 "closures cannot be static"
830 fn record_body(&mut self, arguments: HirVec<hir::Arg>, value: hir::Expr) -> hir::BodyId {
831 let body = hir::Body {
832 generator_kind: self.generator_kind,
837 self.bodies.insert(id, body);
841 fn next_id(&mut self) -> hir::HirId {
842 self.lower_node_id(self.sess.next_node_id())
845 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
847 self.lower_node_id_generic(id, |_| {
848 panic!("expected node_id to be lowered already for res {:#?}", res)
853 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
854 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
855 if pr.unresolved_segments() != 0 {
856 bug!("path not fully resolved: {:?}", pr);
862 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
863 self.resolver.get_import_res(id).present_items()
866 fn diagnostic(&self) -> &errors::Handler {
867 self.sess.diagnostic()
870 /// Reuses the span but adds information like the kind of the desugaring and features that are
871 /// allowed inside this span.
872 fn mark_span_with_reason(
874 reason: DesugaringKind,
876 allow_internal_unstable: Option<Lrc<[Symbol]>>,
878 span.fresh_expansion(ExpnId::root(), ExpnInfo {
880 allow_internal_unstable,
881 ..ExpnInfo::default(ExpnKind::Desugaring(reason), span, self.sess.edition())
885 fn with_anonymous_lifetime_mode<R>(
887 anonymous_lifetime_mode: AnonymousLifetimeMode,
888 op: impl FnOnce(&mut Self) -> R,
890 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
891 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
892 let result = op(self);
893 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
897 /// Creates a new `hir::GenericParam` for every new lifetime and
898 /// type parameter encountered while evaluating `f`. Definitions
899 /// are created with the parent provided. If no `parent_id` is
900 /// provided, no definitions will be returned.
902 /// Presuming that in-band lifetimes are enabled, then
903 /// `self.anonymous_lifetime_mode` will be updated to match the
904 /// argument while `f` is running (and restored afterwards).
905 fn collect_in_band_defs<T, F>(
908 anonymous_lifetime_mode: AnonymousLifetimeMode,
910 ) -> (Vec<hir::GenericParam>, T)
912 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
914 assert!(!self.is_collecting_in_band_lifetimes);
915 assert!(self.lifetimes_to_define.is_empty());
916 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
918 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
919 self.is_collecting_in_band_lifetimes = true;
921 let (in_band_ty_params, res) = f(self);
923 self.is_collecting_in_band_lifetimes = false;
924 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
926 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
928 let params = lifetimes_to_define
930 .map(|(span, hir_name)| self.lifetime_to_generic_param(
931 span, hir_name, parent_id.index,
933 .chain(in_band_ty_params.into_iter())
939 /// Converts a lifetime into a new generic parameter.
940 fn lifetime_to_generic_param(
944 parent_index: DefIndex,
945 ) -> hir::GenericParam {
946 let node_id = self.sess.next_node_id();
948 // Get the name we'll use to make the def-path. Note
949 // that collisions are ok here and this shouldn't
950 // really show up for end-user.
951 let (str_name, kind) = match hir_name {
952 ParamName::Plain(ident) => (
953 ident.as_interned_str(),
954 hir::LifetimeParamKind::InBand,
956 ParamName::Fresh(_) => (
957 kw::UnderscoreLifetime.as_interned_str(),
958 hir::LifetimeParamKind::Elided,
960 ParamName::Error => (
961 kw::UnderscoreLifetime.as_interned_str(),
962 hir::LifetimeParamKind::Error,
966 // Add a definition for the in-band lifetime def.
967 self.resolver.definitions().create_def_with_parent(
970 DefPathData::LifetimeNs(str_name),
976 hir_id: self.lower_node_id(node_id),
981 pure_wrt_drop: false,
982 kind: hir::GenericParamKind::Lifetime { kind }
986 /// When there is a reference to some lifetime `'a`, and in-band
987 /// lifetimes are enabled, then we want to push that lifetime into
988 /// the vector of names to define later. In that case, it will get
989 /// added to the appropriate generics.
990 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
991 if !self.is_collecting_in_band_lifetimes {
995 if !self.sess.features_untracked().in_band_lifetimes {
999 if self.in_scope_lifetimes.contains(&ident.modern()) {
1003 let hir_name = ParamName::Plain(ident);
1005 if self.lifetimes_to_define.iter()
1006 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
1010 self.lifetimes_to_define.push((ident.span, hir_name));
1013 /// When we have either an elided or `'_` lifetime in an impl
1014 /// header, we convert it to an in-band lifetime.
1015 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
1016 assert!(self.is_collecting_in_band_lifetimes);
1017 let index = self.lifetimes_to_define.len();
1018 let hir_name = ParamName::Fresh(index);
1019 self.lifetimes_to_define.push((span, hir_name));
1023 // Evaluates `f` with the lifetimes in `params` in-scope.
1024 // This is used to track which lifetimes have already been defined, and
1025 // which are new in-band lifetimes that need to have a definition created
1027 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
1029 F: FnOnce(&mut LoweringContext<'_>) -> T,
1031 let old_len = self.in_scope_lifetimes.len();
1032 let lt_def_names = params.iter().filter_map(|param| match param.kind {
1033 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
1036 self.in_scope_lifetimes.extend(lt_def_names);
1040 self.in_scope_lifetimes.truncate(old_len);
1044 // Same as the method above, but accepts `hir::GenericParam`s
1045 // instead of `ast::GenericParam`s.
1046 // This should only be used with generics that have already had their
1047 // in-band lifetimes added. In practice, this means that this function is
1048 // only used when lowering a child item of a trait or impl.
1049 fn with_parent_item_lifetime_defs<T, F>(&mut self,
1050 parent_hir_id: hir::HirId,
1053 F: FnOnce(&mut LoweringContext<'_>) -> T,
1055 let old_len = self.in_scope_lifetimes.len();
1057 let parent_generics = match self.items.get(&parent_hir_id).unwrap().node {
1058 hir::ItemKind::Impl(_, _, _, ref generics, ..)
1059 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1060 &generics.params[..]
1064 let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
1065 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
1068 self.in_scope_lifetimes.extend(lt_def_names);
1072 self.in_scope_lifetimes.truncate(old_len);
1076 /// Appends in-band lifetime defs and argument-position `impl
1077 /// Trait` defs to the existing set of generics.
1079 /// Presuming that in-band lifetimes are enabled, then
1080 /// `self.anonymous_lifetime_mode` will be updated to match the
1081 /// argument while `f` is running (and restored afterwards).
1082 fn add_in_band_defs<F, T>(
1084 generics: &Generics,
1086 anonymous_lifetime_mode: AnonymousLifetimeMode,
1088 ) -> (hir::Generics, T)
1090 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
1092 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
1095 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
1096 let mut params = Vec::new();
1097 // Note: it is necessary to lower generics *before* calling `f`.
1098 // When lowering `async fn`, there's a final step when lowering
1099 // the return type that assumes that all in-scope lifetimes have
1100 // already been added to either `in_scope_lifetimes` or
1101 // `lifetimes_to_define`. If we swapped the order of these two,
1102 // in-band-lifetimes introduced by generics or where-clauses
1103 // wouldn't have been added yet.
1104 let generics = this.lower_generics(
1106 ImplTraitContext::Universal(&mut params),
1108 let res = f(this, &mut params);
1109 (params, (generics, res))
1114 let mut lowered_params: Vec<_> = lowered_generics
1117 .chain(in_band_defs)
1120 // FIXME(const_generics): the compiler doesn't always cope with
1121 // unsorted generic parameters at the moment, so we make sure
1122 // that they're ordered correctly here for now. (When we chain
1123 // the `in_band_defs`, we might make the order unsorted.)
1124 lowered_params.sort_by_key(|param| {
1126 hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime,
1127 hir::GenericParamKind::Type { .. } => ParamKindOrd::Type,
1128 hir::GenericParamKind::Const { .. } => ParamKindOrd::Const,
1132 lowered_generics.params = lowered_params.into();
1134 (lowered_generics, res)
1137 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
1139 F: FnOnce(&mut LoweringContext<'_>) -> T,
1141 let len = self.catch_scopes.len();
1142 self.catch_scopes.push(catch_id);
1144 let result = f(self);
1147 self.catch_scopes.len(),
1148 "catch scopes should be added and removed in stack order"
1151 self.catch_scopes.pop().unwrap();
1158 capture_clause: CaptureBy,
1159 closure_node_id: NodeId,
1160 ret_ty: Option<AstP<Ty>>,
1162 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1163 ) -> hir::ExprKind {
1164 let capture_clause = self.lower_capture_clause(capture_clause);
1165 let output = match ret_ty {
1166 Some(ty) => FunctionRetTy::Ty(ty),
1167 None => FunctionRetTy::Default(span),
1169 let ast_decl = FnDecl {
1174 let decl = self.lower_fn_decl(&ast_decl, None, /* impl trait allowed */ false, None);
1175 let body_id = self.lower_fn_body(&ast_decl, |this| {
1176 this.generator_kind = Some(hir::GeneratorKind::Async);
1179 let generator = hir::Expr {
1180 hir_id: self.lower_node_id(closure_node_id),
1181 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
1182 Some(hir::GeneratorMovability::Static)),
1184 attrs: ThinVec::new(),
1187 let unstable_span = self.mark_span_with_reason(
1188 DesugaringKind::Async,
1190 self.allow_gen_future.clone(),
1192 let gen_future = self.expr_std_path(
1193 unstable_span, &[sym::future, sym::from_generator], None, ThinVec::new());
1194 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
1199 f: impl FnOnce(&mut LoweringContext<'_>) -> (HirVec<hir::Arg>, hir::Expr),
1201 let prev_gen_kind = self.generator_kind.take();
1202 let (arguments, result) = f(self);
1203 let body_id = self.record_body(arguments, result);
1204 self.generator_kind = prev_gen_kind;
1211 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1213 self.lower_body(|this| (
1214 decl.inputs.iter().map(|x| this.lower_arg(x)).collect(),
1219 fn lower_const_body(&mut self, expr: &Expr) -> hir::BodyId {
1220 self.lower_body(|this| (hir_vec![], this.lower_expr(expr)))
1223 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
1225 F: FnOnce(&mut LoweringContext<'_>) -> T,
1227 // We're no longer in the base loop's condition; we're in another loop.
1228 let was_in_loop_condition = self.is_in_loop_condition;
1229 self.is_in_loop_condition = false;
1231 let len = self.loop_scopes.len();
1232 self.loop_scopes.push(loop_id);
1234 let result = f(self);
1237 self.loop_scopes.len(),
1238 "loop scopes should be added and removed in stack order"
1241 self.loop_scopes.pop().unwrap();
1243 self.is_in_loop_condition = was_in_loop_condition;
1248 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
1250 F: FnOnce(&mut LoweringContext<'_>) -> T,
1252 let was_in_loop_condition = self.is_in_loop_condition;
1253 self.is_in_loop_condition = true;
1255 let result = f(self);
1257 self.is_in_loop_condition = was_in_loop_condition;
1262 fn with_dyn_type_scope<T, F>(&mut self, in_scope: bool, f: F) -> T
1264 F: FnOnce(&mut LoweringContext<'_>) -> T,
1266 let was_in_dyn_type = self.is_in_dyn_type;
1267 self.is_in_dyn_type = in_scope;
1269 let result = f(self);
1271 self.is_in_dyn_type = was_in_dyn_type;
1276 fn with_new_scopes<T, F>(&mut self, f: F) -> T
1278 F: FnOnce(&mut LoweringContext<'_>) -> T,
1280 let was_in_loop_condition = self.is_in_loop_condition;
1281 self.is_in_loop_condition = false;
1283 let catch_scopes = mem::take(&mut self.catch_scopes);
1284 let loop_scopes = mem::take(&mut self.loop_scopes);
1286 self.catch_scopes = catch_scopes;
1287 self.loop_scopes = loop_scopes;
1289 self.is_in_loop_condition = was_in_loop_condition;
1294 fn def_key(&mut self, id: DefId) -> DefKey {
1296 self.resolver.definitions().def_key(id.index)
1298 self.cstore.def_key(id)
1302 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1303 label.map(|label| hir::Label {
1308 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1309 let target_id = match destination {
1311 if let Some(loop_id) = self.resolver.get_label_res(id) {
1312 Ok(self.lower_node_id(loop_id))
1314 Err(hir::LoopIdError::UnresolvedLabel)
1321 .map(|id| Ok(self.lower_node_id(id)))
1322 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1327 label: self.lower_label(destination.map(|(_, label)| label)),
1332 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1335 .map(|a| self.lower_attr(a))
1339 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1340 // Note that we explicitly do not walk the path. Since we don't really
1341 // lower attributes (we use the AST version) there is nowhere to keep
1342 // the `HirId`s. We don't actually need HIR version of attributes anyway.
1346 path: attr.path.clone(),
1347 tokens: self.lower_token_stream(attr.tokens.clone()),
1348 is_sugared_doc: attr.is_sugared_doc,
1353 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1356 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1360 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1362 TokenTree::Token(token) => self.lower_token(token),
1363 TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1366 self.lower_token_stream(tts),
1371 fn lower_token(&mut self, token: Token) -> TokenStream {
1373 token::Interpolated(nt) => {
1374 let tts = nt.to_tokenstream(&self.sess.parse_sess, token.span);
1375 self.lower_token_stream(tts)
1377 _ => TokenTree::Token(token).into(),
1381 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1383 hir_id: self.next_id(),
1384 attrs: self.lower_attrs(&arm.attrs),
1385 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1386 guard: match arm.guard {
1387 Some(ref x) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1390 body: P(self.lower_expr(&arm.body)),
1395 /// Given an associated type constraint like one of these:
1398 /// T: Iterator<Item: Debug>
1400 /// T: Iterator<Item = Debug>
1404 /// returns a `hir::TypeBinding` representing `Item`.
1405 fn lower_assoc_ty_constraint(&mut self,
1406 c: &AssocTyConstraint,
1407 itctx: ImplTraitContext<'_>)
1408 -> hir::TypeBinding {
1409 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", c, itctx);
1411 let kind = match c.kind {
1412 AssocTyConstraintKind::Equality { ref ty } => hir::TypeBindingKind::Equality {
1413 ty: self.lower_ty(ty, itctx)
1415 AssocTyConstraintKind::Bound { ref bounds } => {
1416 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1417 let (desugar_to_impl_trait, itctx) = match itctx {
1418 // We are in the return position:
1420 // fn foo() -> impl Iterator<Item: Debug>
1424 // fn foo() -> impl Iterator<Item = impl Debug>
1425 ImplTraitContext::Existential(_) => (true, itctx),
1427 // We are in the argument position, but within a dyn type:
1429 // fn foo(x: dyn Iterator<Item: Debug>)
1433 // fn foo(x: dyn Iterator<Item = impl Debug>)
1434 ImplTraitContext::Universal(_) if self.is_in_dyn_type => (true, itctx),
1436 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1437 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1438 // "impl trait context" to permit `impl Debug` in this position (it desugars
1439 // then to an existential type).
1441 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1442 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type =>
1443 (true, ImplTraitContext::Existential(None)),
1445 // We are in the argument position, but not within a dyn type:
1447 // fn foo(x: impl Iterator<Item: Debug>)
1449 // so we leave it as is and this gets expanded in astconv to a bound like
1450 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1452 _ => (false, itctx),
1455 if desugar_to_impl_trait {
1456 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1457 // constructing the HIR for `impl bounds...` and then lowering that.
1459 let impl_trait_node_id = self.sess.next_node_id();
1460 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
1461 self.resolver.definitions().create_def_with_parent(
1464 DefPathData::ImplTrait,
1469 self.with_dyn_type_scope(false, |this| {
1470 let ty = this.lower_ty(
1472 id: this.sess.next_node_id(),
1473 node: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1479 hir::TypeBindingKind::Equality {
1484 // Desugar `AssocTy: Bounds` into a type binding where the
1485 // later desugars into a trait predicate.
1486 let bounds = self.lower_param_bounds(bounds, itctx);
1488 hir::TypeBindingKind::Constraint {
1496 hir_id: self.lower_node_id(c.id),
1503 fn lower_generic_arg(&mut self,
1504 arg: &ast::GenericArg,
1505 itctx: ImplTraitContext<'_>)
1506 -> hir::GenericArg {
1508 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1509 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1510 ast::GenericArg::Const(ct) => {
1511 GenericArg::Const(ConstArg {
1512 value: self.lower_anon_const(&ct),
1513 span: ct.value.span,
1519 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1520 P(self.lower_ty_direct(t, itctx))
1526 qself: &Option<QSelf>,
1528 param_mode: ParamMode,
1529 itctx: ImplTraitContext<'_>
1531 let id = self.lower_node_id(t.id);
1532 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1533 let ty = self.ty_path(id, t.span, qpath);
1534 if let hir::TyKind::TraitObject(..) = ty.node {
1535 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1540 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1541 let kind = match t.node {
1542 TyKind::Infer => hir::TyKind::Infer,
1543 TyKind::Err => hir::TyKind::Err,
1544 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1545 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1546 TyKind::Rptr(ref region, ref mt) => {
1547 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1548 let lifetime = match *region {
1549 Some(ref lt) => self.lower_lifetime(lt),
1550 None => self.elided_ref_lifetime(span),
1552 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1554 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1557 this.with_anonymous_lifetime_mode(
1558 AnonymousLifetimeMode::PassThrough,
1560 hir::TyKind::BareFn(P(hir::BareFnTy {
1561 generic_params: this.lower_generic_params(
1563 &NodeMap::default(),
1564 ImplTraitContext::disallowed(),
1566 unsafety: this.lower_unsafety(f.unsafety),
1568 decl: this.lower_fn_decl(&f.decl, None, false, None),
1569 arg_names: this.lower_fn_args_to_names(&f.decl),
1575 TyKind::Never => hir::TyKind::Never,
1576 TyKind::Tup(ref tys) => {
1577 hir::TyKind::Tup(tys.iter().map(|ty| {
1578 self.lower_ty_direct(ty, itctx.reborrow())
1581 TyKind::Paren(ref ty) => {
1582 return self.lower_ty_direct(ty, itctx);
1584 TyKind::Path(ref qself, ref path) => {
1585 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1587 TyKind::ImplicitSelf => {
1588 let res = self.expect_full_res(t.id);
1589 let res = self.lower_res(res);
1590 hir::TyKind::Path(hir::QPath::Resolved(
1594 segments: hir_vec![hir::PathSegment::from_ident(
1595 Ident::with_empty_ctxt(kw::SelfUpper)
1601 TyKind::Array(ref ty, ref length) => {
1602 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1604 TyKind::Typeof(ref expr) => {
1605 hir::TyKind::Typeof(self.lower_anon_const(expr))
1607 TyKind::TraitObject(ref bounds, kind) => {
1608 let mut lifetime_bound = None;
1609 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1612 .filter_map(|bound| match *bound {
1613 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1614 Some(this.lower_poly_trait_ref(ty, itctx.reborrow()))
1616 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1617 GenericBound::Outlives(ref lifetime) => {
1618 if lifetime_bound.is_none() {
1619 lifetime_bound = Some(this.lower_lifetime(lifetime));
1625 let lifetime_bound =
1626 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1627 (bounds, lifetime_bound)
1629 if kind != TraitObjectSyntax::Dyn {
1630 self.maybe_lint_bare_trait(t.span, t.id, false);
1632 hir::TyKind::TraitObject(bounds, lifetime_bound)
1634 TyKind::ImplTrait(def_node_id, ref bounds) => {
1637 ImplTraitContext::Existential(fn_def_id) => {
1638 self.lower_existential_impl_trait(
1639 span, fn_def_id, def_node_id,
1640 |this| this.lower_param_bounds(bounds, itctx),
1643 ImplTraitContext::Universal(in_band_ty_params) => {
1644 // Add a definition for the in-band `Param`.
1645 let def_index = self
1648 .opt_def_index(def_node_id)
1651 let hir_bounds = self.lower_param_bounds(
1653 ImplTraitContext::Universal(in_band_ty_params),
1655 // Set the name to `impl Bound1 + Bound2`.
1656 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1657 in_band_ty_params.push(hir::GenericParam {
1658 hir_id: self.lower_node_id(def_node_id),
1659 name: ParamName::Plain(ident),
1660 pure_wrt_drop: false,
1664 kind: hir::GenericParamKind::Type {
1666 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1670 hir::TyKind::Path(hir::QPath::Resolved(
1674 res: Res::Def(DefKind::TyParam, DefId::local(def_index)),
1675 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1679 ImplTraitContext::Disallowed(pos) => {
1680 let allowed_in = if self.sess.features_untracked()
1681 .impl_trait_in_bindings {
1682 "bindings or function and inherent method return types"
1684 "function and inherent method return types"
1686 let mut err = struct_span_err!(
1690 "`impl Trait` not allowed outside of {}",
1693 if pos == ImplTraitPosition::Binding &&
1694 nightly_options::is_nightly_build() {
1696 "add `#![feature(impl_trait_in_bindings)]` to the crate \
1697 attributes to enable");
1704 TyKind::Mac(_) => bug!("`TyMac` should have been expanded by now."),
1705 TyKind::CVarArgs => {
1706 // Create the implicit lifetime of the "spoofed" `VaListImpl`.
1707 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1708 let lt = self.new_implicit_lifetime(span);
1709 hir::TyKind::CVarArgs(lt)
1716 hir_id: self.lower_node_id(t.id),
1720 fn lower_existential_impl_trait(
1723 fn_def_id: Option<DefId>,
1724 exist_ty_node_id: NodeId,
1725 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1727 // Make sure we know that some funky desugaring has been going on here.
1728 // This is a first: there is code in other places like for loop
1729 // desugaring that explicitly states that we don't want to track that.
1730 // Not tracking it makes lints in rustc and clippy very fragile, as
1731 // frequently opened issues show.
1732 let exist_ty_span = self.mark_span_with_reason(
1733 DesugaringKind::ExistentialType,
1738 let exist_ty_def_index = self
1741 .opt_def_index(exist_ty_node_id)
1744 self.allocate_hir_id_counter(exist_ty_node_id);
1746 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1748 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1754 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1755 let exist_ty_item = hir::ExistTy {
1756 generics: hir::Generics {
1757 params: lifetime_defs,
1758 where_clause: hir::WhereClause {
1759 predicates: hir_vec![],
1765 impl_trait_fn: fn_def_id,
1766 origin: hir::ExistTyOrigin::ReturnImplTrait,
1769 trace!("exist ty from impl trait def-index: {:#?}", exist_ty_def_index);
1770 let exist_ty_id = lctx.generate_existential_type(
1777 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1778 hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, lifetimes)
1782 /// Registers a new existential type with the proper `NodeId`s and
1783 /// returns the lowered node-ID for the existential type.
1784 fn generate_existential_type(
1786 exist_ty_node_id: NodeId,
1787 exist_ty_item: hir::ExistTy,
1789 exist_ty_span: Span,
1791 let exist_ty_item_kind = hir::ItemKind::Existential(exist_ty_item);
1792 let exist_ty_id = self.lower_node_id(exist_ty_node_id);
1793 // Generate an `existential type Foo: Trait;` declaration.
1794 trace!("registering existential type with id {:#?}", exist_ty_id);
1795 let exist_ty_item = hir::Item {
1796 hir_id: exist_ty_id,
1797 ident: Ident::invalid(),
1798 attrs: Default::default(),
1799 node: exist_ty_item_kind,
1800 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1801 span: exist_ty_span,
1804 // Insert the item into the global item list. This usually happens
1805 // automatically for all AST items. But this existential type item
1806 // does not actually exist in the AST.
1807 self.insert_item(exist_ty_item);
1811 fn lifetimes_from_impl_trait_bounds(
1813 exist_ty_id: NodeId,
1814 parent_index: DefIndex,
1815 bounds: &hir::GenericBounds,
1816 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1817 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1818 // appear in the bounds, excluding lifetimes that are created within the bounds.
1819 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1820 struct ImplTraitLifetimeCollector<'r, 'a> {
1821 context: &'r mut LoweringContext<'a>,
1823 exist_ty_id: NodeId,
1824 collect_elided_lifetimes: bool,
1825 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1826 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1827 output_lifetimes: Vec<hir::GenericArg>,
1828 output_lifetime_params: Vec<hir::GenericParam>,
1831 impl<'r, 'a, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1832 fn nested_visit_map<'this>(
1834 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1835 hir::intravisit::NestedVisitorMap::None
1838 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1839 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1840 if parameters.parenthesized {
1841 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1842 self.collect_elided_lifetimes = false;
1843 hir::intravisit::walk_generic_args(self, span, parameters);
1844 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1846 hir::intravisit::walk_generic_args(self, span, parameters);
1850 fn visit_ty(&mut self, t: &'v hir::Ty) {
1851 // Don't collect elided lifetimes used inside of `fn()` syntax.
1852 if let hir::TyKind::BareFn(_) = t.node {
1853 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1854 self.collect_elided_lifetimes = false;
1856 // Record the "stack height" of `for<'a>` lifetime bindings
1857 // to be able to later fully undo their introduction.
1858 let old_len = self.currently_bound_lifetimes.len();
1859 hir::intravisit::walk_ty(self, t);
1860 self.currently_bound_lifetimes.truncate(old_len);
1862 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1864 hir::intravisit::walk_ty(self, t)
1868 fn visit_poly_trait_ref(
1870 trait_ref: &'v hir::PolyTraitRef,
1871 modifier: hir::TraitBoundModifier,
1873 // Record the "stack height" of `for<'a>` lifetime bindings
1874 // to be able to later fully undo their introduction.
1875 let old_len = self.currently_bound_lifetimes.len();
1876 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1877 self.currently_bound_lifetimes.truncate(old_len);
1880 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1881 // Record the introduction of 'a in `for<'a> ...`.
1882 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1883 // Introduce lifetimes one at a time so that we can handle
1884 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1885 let lt_name = hir::LifetimeName::Param(param.name);
1886 self.currently_bound_lifetimes.push(lt_name);
1889 hir::intravisit::walk_generic_param(self, param);
1892 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1893 let name = match lifetime.name {
1894 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1895 if self.collect_elided_lifetimes {
1896 // Use `'_` for both implicit and underscore lifetimes in
1897 // `abstract type Foo<'_>: SomeTrait<'_>;`.
1898 hir::LifetimeName::Underscore
1903 hir::LifetimeName::Param(_) => lifetime.name,
1904 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1907 if !self.currently_bound_lifetimes.contains(&name)
1908 && !self.already_defined_lifetimes.contains(&name) {
1909 self.already_defined_lifetimes.insert(name);
1911 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1912 hir_id: self.context.next_id(),
1913 span: lifetime.span,
1917 let def_node_id = self.context.sess.next_node_id();
1919 self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1920 self.context.resolver.definitions().create_def_with_parent(
1923 DefPathData::LifetimeNs(name.ident().as_interned_str()),
1927 let (name, kind) = match name {
1928 hir::LifetimeName::Underscore => (
1929 hir::ParamName::Plain(Ident::with_empty_ctxt(kw::UnderscoreLifetime)),
1930 hir::LifetimeParamKind::Elided,
1932 hir::LifetimeName::Param(param_name) => (
1934 hir::LifetimeParamKind::Explicit,
1936 _ => bug!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1939 self.output_lifetime_params.push(hir::GenericParam {
1942 span: lifetime.span,
1943 pure_wrt_drop: false,
1946 kind: hir::GenericParamKind::Lifetime { kind }
1952 let mut lifetime_collector = ImplTraitLifetimeCollector {
1954 parent: parent_index,
1956 collect_elided_lifetimes: true,
1957 currently_bound_lifetimes: Vec::new(),
1958 already_defined_lifetimes: FxHashSet::default(),
1959 output_lifetimes: Vec::new(),
1960 output_lifetime_params: Vec::new(),
1963 for bound in bounds {
1964 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1968 lifetime_collector.output_lifetimes.into(),
1969 lifetime_collector.output_lifetime_params.into(),
1973 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1978 .map(|x| self.lower_foreign_item(x))
1983 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1990 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1992 node: hir::VariantKind {
1993 ident: v.node.ident,
1994 id: self.lower_node_id(v.node.id),
1995 attrs: self.lower_attrs(&v.node.attrs),
1996 data: self.lower_variant_data(&v.node.data),
1997 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
2006 qself: &Option<QSelf>,
2008 param_mode: ParamMode,
2009 mut itctx: ImplTraitContext<'_>,
2011 let qself_position = qself.as_ref().map(|q| q.position);
2012 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
2014 let partial_res = self.resolver
2015 .get_partial_res(id)
2016 .unwrap_or_else(|| PartialRes::new(Res::Err));
2018 let proj_start = p.segments.len() - partial_res.unresolved_segments();
2019 let path = P(hir::Path {
2020 res: self.lower_res(partial_res.base_res()),
2021 segments: p.segments[..proj_start]
2024 .map(|(i, segment)| {
2025 let param_mode = match (qself_position, param_mode) {
2026 (Some(j), ParamMode::Optional) if i < j => {
2027 // This segment is part of the trait path in a
2028 // qualified path - one of `a`, `b` or `Trait`
2029 // in `<X as a::b::Trait>::T::U::method`.
2035 // Figure out if this is a type/trait segment,
2036 // which may need lifetime elision performed.
2037 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
2038 krate: def_id.krate,
2039 index: this.def_key(def_id).parent.expect("missing parent"),
2041 let type_def_id = match partial_res.base_res() {
2042 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2043 Some(parent_def_id(self, def_id))
2045 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
2046 Some(parent_def_id(self, def_id))
2048 Res::Def(DefKind::Struct, def_id)
2049 | Res::Def(DefKind::Union, def_id)
2050 | Res::Def(DefKind::Enum, def_id)
2051 | Res::Def(DefKind::TyAlias, def_id)
2052 | Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start =>
2058 let parenthesized_generic_args = match partial_res.base_res() {
2059 // `a::b::Trait(Args)`
2060 Res::Def(DefKind::Trait, _)
2061 if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
2062 // `a::b::Trait(Args)::TraitItem`
2063 Res::Def(DefKind::Method, _)
2064 | Res::Def(DefKind::AssocConst, _)
2065 | Res::Def(DefKind::AssocTy, _)
2066 if i + 2 == proj_start =>
2068 ParenthesizedGenericArgs::Ok
2070 // Avoid duplicated errors.
2071 Res::Err => ParenthesizedGenericArgs::Ok,
2073 Res::Def(DefKind::Struct, _)
2074 | Res::Def(DefKind::Enum, _)
2075 | Res::Def(DefKind::Union, _)
2076 | Res::Def(DefKind::TyAlias, _)
2077 | Res::Def(DefKind::Variant, _) if i + 1 == proj_start =>
2079 ParenthesizedGenericArgs::Err
2081 // A warning for now, for compatibility reasons.
2082 _ => ParenthesizedGenericArgs::Warn,
2085 let num_lifetimes = type_def_id.map_or(0, |def_id| {
2086 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
2089 assert!(!def_id.is_local());
2091 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
2092 let n = item_generics.own_counts().lifetimes;
2093 self.type_def_lifetime_params.insert(def_id, n);
2096 self.lower_path_segment(
2101 parenthesized_generic_args,
2110 // Simple case, either no projections, or only fully-qualified.
2111 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
2112 if partial_res.unresolved_segments() == 0 {
2113 return hir::QPath::Resolved(qself, path);
2116 // Create the innermost type that we're projecting from.
2117 let mut ty = if path.segments.is_empty() {
2118 // If the base path is empty that means there exists a
2119 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
2120 qself.expect("missing QSelf for <T>::...")
2122 // Otherwise, the base path is an implicit `Self` type path,
2123 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
2124 // `<I as Iterator>::Item::default`.
2125 let new_id = self.next_id();
2126 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
2129 // Anything after the base path are associated "extensions",
2130 // out of which all but the last one are associated types,
2131 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
2132 // * base path is `std::vec::Vec<T>`
2133 // * "extensions" are `IntoIter`, `Item` and `clone`
2134 // * type nodes are:
2135 // 1. `std::vec::Vec<T>` (created above)
2136 // 2. `<std::vec::Vec<T>>::IntoIter`
2137 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
2138 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
2139 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
2140 let segment = P(self.lower_path_segment(
2145 ParenthesizedGenericArgs::Warn,
2149 let qpath = hir::QPath::TypeRelative(ty, segment);
2151 // It's finished, return the extension of the right node type.
2152 if i == p.segments.len() - 1 {
2156 // Wrap the associated extension in another type node.
2157 let new_id = self.next_id();
2158 ty = P(self.ty_path(new_id, p.span, qpath));
2161 // We should've returned in the for loop above.
2164 "lower_qpath: no final extension segment in {}..{}",
2170 fn lower_path_extra(
2174 param_mode: ParamMode,
2175 explicit_owner: Option<NodeId>,
2179 segments: p.segments
2182 self.lower_path_segment(
2187 ParenthesizedGenericArgs::Err,
2188 ImplTraitContext::disallowed(),
2197 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
2198 let res = self.expect_full_res(id);
2199 let res = self.lower_res(res);
2200 self.lower_path_extra(res, p, param_mode, None)
2203 fn lower_path_segment(
2206 segment: &PathSegment,
2207 param_mode: ParamMode,
2208 expected_lifetimes: usize,
2209 parenthesized_generic_args: ParenthesizedGenericArgs,
2210 itctx: ImplTraitContext<'_>,
2211 explicit_owner: Option<NodeId>,
2212 ) -> hir::PathSegment {
2213 let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
2214 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
2215 match **generic_args {
2216 GenericArgs::AngleBracketed(ref data) => {
2217 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
2219 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
2220 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
2221 ParenthesizedGenericArgs::Warn => {
2222 self.sess.buffer_lint(
2223 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
2228 (hir::GenericArgs::none(), true)
2230 ParenthesizedGenericArgs::Err => {
2231 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
2232 err.span_label(data.span, "only `Fn` traits may use parentheses");
2233 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
2234 // Do not suggest going from `Trait()` to `Trait<>`
2235 if data.inputs.len() > 0 {
2236 err.span_suggestion(
2238 "use angle brackets instead",
2239 format!("<{}>", &snippet[1..snippet.len() - 1]),
2240 Applicability::MaybeIncorrect,
2246 self.lower_angle_bracketed_parameter_data(
2247 &data.as_angle_bracketed_args(),
2257 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
2260 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
2261 GenericArg::Lifetime(_) => true,
2264 let first_generic_span = generic_args.args.iter().map(|a| a.span())
2265 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
2266 if !generic_args.parenthesized && !has_lifetimes {
2268 self.elided_path_lifetimes(path_span, expected_lifetimes)
2270 .map(|lt| GenericArg::Lifetime(lt))
2271 .chain(generic_args.args.into_iter())
2273 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
2274 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
2275 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
2276 let no_bindings = generic_args.bindings.is_empty();
2277 let (incl_angl_brckt, insertion_sp, suggestion) = if no_non_lt_args && no_bindings {
2278 // If there are no (non-implicit) generic args or associated type
2279 // bindings, our suggestion includes the angle brackets.
2280 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
2282 // Otherwise (sorry, this is kind of gross) we need to infer the
2283 // place to splice in the `'_, ` from the generics that do exist.
2284 let first_generic_span = first_generic_span
2285 .expect("already checked that non-lifetime args or bindings exist");
2286 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
2288 match self.anonymous_lifetime_mode {
2289 // In create-parameter mode we error here because we don't want to support
2290 // deprecated impl elision in new features like impl elision and `async fn`,
2291 // both of which work using the `CreateParameter` mode:
2293 // impl Foo for std::cell::Ref<u32> // note lack of '_
2294 // async fn foo(_: std::cell::Ref<u32>) { ... }
2295 AnonymousLifetimeMode::CreateParameter => {
2296 let mut err = struct_span_err!(
2300 "implicit elided lifetime not allowed here"
2302 crate::lint::builtin::add_elided_lifetime_in_path_suggestion(
2313 AnonymousLifetimeMode::PassThrough |
2314 AnonymousLifetimeMode::ReportError |
2315 AnonymousLifetimeMode::Replace(_) => {
2316 self.sess.buffer_lint_with_diagnostic(
2317 ELIDED_LIFETIMES_IN_PATHS,
2320 "hidden lifetime parameters in types are deprecated",
2321 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
2334 let res = self.expect_full_res(segment.id);
2335 let id = if let Some(owner) = explicit_owner {
2336 self.lower_node_id_with_owner(segment.id, owner)
2338 self.lower_node_id(segment.id)
2341 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
2342 segment.ident, segment.id, id,
2345 hir::PathSegment::new(
2348 Some(self.lower_res(res)),
2354 fn lower_angle_bracketed_parameter_data(
2356 data: &AngleBracketedArgs,
2357 param_mode: ParamMode,
2358 mut itctx: ImplTraitContext<'_>,
2359 ) -> (hir::GenericArgs, bool) {
2360 let &AngleBracketedArgs { ref args, ref constraints, .. } = data;
2361 let has_non_lt_args = args.iter().any(|arg| match arg {
2362 ast::GenericArg::Lifetime(_) => false,
2363 ast::GenericArg::Type(_) => true,
2364 ast::GenericArg::Const(_) => true,
2368 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
2369 bindings: constraints.iter()
2370 .map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow()))
2372 parenthesized: false,
2374 !has_non_lt_args && param_mode == ParamMode::Optional
2378 fn lower_parenthesized_parameter_data(
2380 data: &ParenthesizedArgs,
2381 ) -> (hir::GenericArgs, bool) {
2382 // Switch to `PassThrough` mode for anonymous lifetimes; this
2383 // means that we permit things like `&Ref<T>`, where `Ref` has
2384 // a hidden lifetime parameter. This is needed for backwards
2385 // compatibility, even in contexts like an impl header where
2386 // we generally don't permit such things (see #51008).
2387 self.with_anonymous_lifetime_mode(
2388 AnonymousLifetimeMode::PassThrough,
2390 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2393 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
2395 let mk_tup = |this: &mut Self, tys, span| {
2396 hir::Ty { node: hir::TyKind::Tup(tys), hir_id: this.next_id(), span }
2400 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
2403 hir_id: this.next_id(),
2404 ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
2405 kind: hir::TypeBindingKind::Equality {
2408 .map(|ty| this.lower_ty(
2410 ImplTraitContext::disallowed()
2413 P(mk_tup(this, hir::HirVec::new(), span))
2416 span: output.as_ref().map_or(span, |ty| ty.span),
2419 parenthesized: true,
2427 fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) {
2428 let mut ids = SmallVec::<[NodeId; 1]>::new();
2429 if self.sess.features_untracked().impl_trait_in_bindings {
2430 if let Some(ref ty) = l.ty {
2431 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2432 visitor.visit_ty(ty);
2435 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2437 hir_id: self.lower_node_id(l.id),
2440 .map(|t| self.lower_ty(t,
2441 if self.sess.features_untracked().impl_trait_in_bindings {
2442 ImplTraitContext::Existential(Some(parent_def_id))
2444 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2447 pat: self.lower_pat(&l.pat),
2448 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2450 attrs: l.attrs.clone(),
2451 source: hir::LocalSource::Normal,
2455 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
2457 Mutability::Mutable => hir::MutMutable,
2458 Mutability::Immutable => hir::MutImmutable,
2462 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
2464 attrs: self.lower_attrs(&arg.attrs),
2465 hir_id: self.lower_node_id(arg.id),
2466 pat: self.lower_pat(&arg.pat),
2471 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2474 .map(|arg| match arg.pat.node {
2475 PatKind::Ident(_, ident, _) => ident,
2476 _ => Ident::new(kw::Invalid, arg.pat.span),
2481 // Lowers a function declaration.
2483 // `decl`: the unlowered (AST) function declaration.
2484 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
2485 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2486 // `make_ret_async` is also `Some`.
2487 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
2488 // This guards against trait declarations and implementations where `impl Trait` is
2490 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2491 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
2492 // return type `impl Trait` item.
2496 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2497 impl_trait_return_allow: bool,
2498 make_ret_async: Option<NodeId>,
2499 ) -> P<hir::FnDecl> {
2500 let lt_mode = if make_ret_async.is_some() {
2501 // In `async fn`, argument-position elided lifetimes
2502 // must be transformed into fresh generic parameters so that
2503 // they can be applied to the existential return type.
2504 AnonymousLifetimeMode::CreateParameter
2506 self.anonymous_lifetime_mode
2509 // Remember how many lifetimes were already around so that we can
2510 // only look at the lifetime parameters introduced by the arguments.
2511 let lifetime_count_before_args = self.lifetimes_to_define.len();
2512 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2516 if let Some((_, ibty)) = &mut in_band_ty_params {
2517 this.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2519 this.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2522 .collect::<HirVec<_>>()
2525 let output = if let Some(ret_id) = make_ret_async {
2526 // Calculate the `LtReplacement` to use for any return-position elided
2527 // lifetimes based on the elided lifetime parameters introduced in the args.
2528 let lt_replacement = get_elided_lt_replacement(
2529 &self.lifetimes_to_define[lifetime_count_before_args..]
2531 self.lower_async_fn_ret_ty(
2533 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
2539 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2540 Some((def_id, _)) if impl_trait_return_allow => {
2541 hir::Return(self.lower_ty(ty,
2542 ImplTraitContext::Existential(Some(def_id))
2546 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2549 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2556 c_variadic: decl.c_variadic,
2557 implicit_self: decl.inputs.get(0).map_or(
2558 hir::ImplicitSelfKind::None,
2560 let is_mutable_pat = match arg.pat.node {
2561 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2562 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2563 mt == Mutability::Mutable,
2568 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2569 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2570 // Given we are only considering `ImplicitSelf` types, we needn't consider
2571 // the case where we have a mutable pattern to a reference as that would
2572 // no longer be an `ImplicitSelf`.
2573 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2574 mt.mutbl == ast::Mutability::Mutable =>
2575 hir::ImplicitSelfKind::MutRef,
2576 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2577 hir::ImplicitSelfKind::ImmRef,
2578 _ => hir::ImplicitSelfKind::None,
2585 // Transforms `-> T` for `async fn` into `-> ExistTy { .. }`
2586 // combined with the following definition of `ExistTy`:
2588 // existential type ExistTy<generics_from_parent_fn>: Future<Output = T>;
2590 // `inputs`: lowered types of arguments to the function (used to collect lifetimes)
2591 // `output`: unlowered output type (`T` in `-> T`)
2592 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
2593 // `exist_ty_node_id`: `NodeId` of the existential type that should be created
2594 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
2595 fn lower_async_fn_ret_ty(
2597 output: &FunctionRetTy,
2599 exist_ty_node_id: NodeId,
2600 elided_lt_replacement: LtReplacement,
2601 ) -> hir::FunctionRetTy {
2602 let span = output.span();
2604 let exist_ty_span = self.mark_span_with_reason(
2605 DesugaringKind::Async,
2610 let exist_ty_def_index = self
2613 .opt_def_index(exist_ty_node_id)
2616 self.allocate_hir_id_counter(exist_ty_node_id);
2618 let (exist_ty_id, lifetime_params) = self.with_hir_id_owner(exist_ty_node_id, |this| {
2619 let future_bound = this.with_anonymous_lifetime_mode(
2620 AnonymousLifetimeMode::Replace(elided_lt_replacement),
2621 |this| this.lower_async_fn_output_type_to_future_bound(
2628 // Calculate all the lifetimes that should be captured
2629 // by the existential type. This should include all in-scope
2630 // lifetime parameters, including those defined in-band.
2632 // Note: this must be done after lowering the output type,
2633 // as the output type may introduce new in-band lifetimes.
2634 let lifetime_params: Vec<(Span, ParamName)> =
2635 this.in_scope_lifetimes
2637 .map(|ident| (ident.span, ParamName::Plain(ident)))
2638 .chain(this.lifetimes_to_define.iter().cloned())
2641 let generic_params =
2644 .map(|(span, hir_name)| {
2645 this.lifetime_to_generic_param(span, hir_name, exist_ty_def_index)
2649 let exist_ty_item = hir::ExistTy {
2650 generics: hir::Generics {
2651 params: generic_params,
2652 where_clause: hir::WhereClause {
2653 predicates: hir_vec![],
2658 bounds: hir_vec![future_bound],
2659 impl_trait_fn: Some(fn_def_id),
2660 origin: hir::ExistTyOrigin::AsyncFn,
2663 trace!("exist ty from async fn def index: {:#?}", exist_ty_def_index);
2664 let exist_ty_id = this.generate_existential_type(
2671 (exist_ty_id, lifetime_params)
2677 .map(|(span, hir_name)| {
2678 GenericArg::Lifetime(hir::Lifetime {
2679 hir_id: self.next_id(),
2681 name: hir::LifetimeName::Param(hir_name),
2686 let exist_ty_ref = hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, generic_args);
2688 hir::FunctionRetTy::Return(P(hir::Ty {
2691 hir_id: self.next_id(),
2695 /// Transforms `-> T` into `Future<Output = T>`
2696 fn lower_async_fn_output_type_to_future_bound(
2698 output: &FunctionRetTy,
2701 ) -> hir::GenericBound {
2702 // Compute the `T` in `Future<Output = T>` from the return type.
2703 let output_ty = match output {
2704 FunctionRetTy::Ty(ty) => {
2705 self.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2707 FunctionRetTy::Default(ret_ty_span) => {
2709 hir_id: self.next_id(),
2710 node: hir::TyKind::Tup(hir_vec![]),
2717 let future_params = P(hir::GenericArgs {
2719 bindings: hir_vec![hir::TypeBinding {
2720 ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
2721 kind: hir::TypeBindingKind::Equality {
2724 hir_id: self.next_id(),
2727 parenthesized: false,
2730 // ::std::future::Future<future_params>
2732 P(self.std_path(span, &[sym::future, sym::Future], Some(future_params), false));
2734 hir::GenericBound::Trait(
2736 trait_ref: hir::TraitRef {
2738 hir_ref_id: self.next_id(),
2740 bound_generic_params: hir_vec![],
2743 hir::TraitBoundModifier::None,
2747 fn lower_param_bound(
2750 itctx: ImplTraitContext<'_>,
2751 ) -> hir::GenericBound {
2753 GenericBound::Trait(ref ty, modifier) => {
2754 hir::GenericBound::Trait(
2755 self.lower_poly_trait_ref(ty, itctx),
2756 self.lower_trait_bound_modifier(modifier),
2759 GenericBound::Outlives(ref lifetime) => {
2760 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2765 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2766 let span = l.ident.span;
2768 ident if ident.name == kw::StaticLifetime =>
2769 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2770 ident if ident.name == kw::UnderscoreLifetime =>
2771 match self.anonymous_lifetime_mode {
2772 AnonymousLifetimeMode::CreateParameter => {
2773 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2774 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2777 AnonymousLifetimeMode::PassThrough => {
2778 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2781 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2783 AnonymousLifetimeMode::Replace(replacement) => {
2784 let hir_id = self.lower_node_id(l.id);
2785 self.replace_elided_lifetime(hir_id, span, replacement)
2789 self.maybe_collect_in_band_lifetime(ident);
2790 let param_name = ParamName::Plain(ident);
2791 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2796 fn new_named_lifetime(
2800 name: hir::LifetimeName,
2801 ) -> hir::Lifetime {
2803 hir_id: self.lower_node_id(id),
2809 /// Replace a return-position elided lifetime with the elided lifetime
2810 /// from the arguments.
2811 fn replace_elided_lifetime(
2815 replacement: LtReplacement,
2816 ) -> hir::Lifetime {
2817 let multiple_or_none = match replacement {
2818 LtReplacement::Some(name) => {
2819 return hir::Lifetime {
2822 name: hir::LifetimeName::Param(name),
2825 LtReplacement::MultipleLifetimes => "multiple",
2826 LtReplacement::NoLifetimes => "none",
2829 let mut err = crate::middle::resolve_lifetime::report_missing_lifetime_specifiers(
2835 "return-position elided lifetimes require exactly one \
2836 input-position elided lifetime, found {}.", multiple_or_none));
2839 hir::Lifetime { hir_id, span, name: hir::LifetimeName::Error }
2842 fn lower_generic_params(
2844 params: &[GenericParam],
2845 add_bounds: &NodeMap<Vec<GenericBound>>,
2846 mut itctx: ImplTraitContext<'_>,
2847 ) -> hir::HirVec<hir::GenericParam> {
2848 params.iter().map(|param| {
2849 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2853 fn lower_generic_param(&mut self,
2854 param: &GenericParam,
2855 add_bounds: &NodeMap<Vec<GenericBound>>,
2856 mut itctx: ImplTraitContext<'_>)
2857 -> hir::GenericParam {
2858 let mut bounds = self.with_anonymous_lifetime_mode(
2859 AnonymousLifetimeMode::ReportError,
2860 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2863 let (name, kind) = match param.kind {
2864 GenericParamKind::Lifetime => {
2865 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2866 self.is_collecting_in_band_lifetimes = false;
2868 let lt = self.with_anonymous_lifetime_mode(
2869 AnonymousLifetimeMode::ReportError,
2870 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2872 let param_name = match lt.name {
2873 hir::LifetimeName::Param(param_name) => param_name,
2874 hir::LifetimeName::Implicit
2875 | hir::LifetimeName::Underscore
2876 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2877 hir::LifetimeName::Error => ParamName::Error,
2880 let kind = hir::GenericParamKind::Lifetime {
2881 kind: hir::LifetimeParamKind::Explicit
2884 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2888 GenericParamKind::Type { ref default, .. } => {
2889 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2890 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2891 // Instead, use `gensym("Self")` to create a distinct name that looks the same.
2892 let ident = if param.ident.name == kw::SelfUpper {
2893 param.ident.gensym()
2898 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2899 if !add_bounds.is_empty() {
2900 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2901 bounds = bounds.into_iter()
2906 let kind = hir::GenericParamKind::Type {
2907 default: default.as_ref().map(|x| {
2908 self.lower_ty(x, ImplTraitContext::Existential(None))
2910 synthetic: param.attrs.iter()
2911 .filter(|attr| attr.check_name(sym::rustc_synthetic))
2912 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2916 (hir::ParamName::Plain(ident), kind)
2918 GenericParamKind::Const { ref ty } => {
2919 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const {
2920 ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2926 hir_id: self.lower_node_id(param.id),
2928 span: param.ident.span,
2929 pure_wrt_drop: attr::contains_name(¶m.attrs, sym::may_dangle),
2930 attrs: self.lower_attrs(¶m.attrs),
2938 generics: &Generics,
2939 itctx: ImplTraitContext<'_>)
2942 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2943 // FIXME: this could probably be done with less rightward drift. It also looks like two
2944 // control paths where `report_error` is called are the only paths that advance to after the
2945 // match statement, so the error reporting could probably just be moved there.
2946 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
2947 for pred in &generics.where_clause.predicates {
2948 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2949 'next_bound: for bound in &bound_pred.bounds {
2950 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2951 let report_error = |this: &mut Self| {
2952 this.diagnostic().span_err(
2953 bound_pred.bounded_ty.span,
2954 "`?Trait` bounds are only permitted at the \
2955 point where a type parameter is declared",
2958 // Check if the where clause type is a plain type parameter.
2959 match bound_pred.bounded_ty.node {
2960 TyKind::Path(None, ref path)
2961 if path.segments.len() == 1
2962 && bound_pred.bound_generic_params.is_empty() =>
2964 if let Some(Res::Def(DefKind::TyParam, def_id)) = self.resolver
2965 .get_partial_res(bound_pred.bounded_ty.id)
2966 .map(|d| d.base_res())
2968 if let Some(node_id) =
2969 self.resolver.definitions().as_local_node_id(def_id)
2971 for param in &generics.params {
2973 GenericParamKind::Type { .. } => {
2974 if node_id == param.id {
2975 add_bounds.entry(param.id)
2977 .push(bound.clone());
2978 continue 'next_bound;
2988 _ => report_error(self),
2996 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2997 where_clause: self.lower_where_clause(&generics.where_clause),
2998 span: generics.span,
3002 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
3003 self.with_anonymous_lifetime_mode(
3004 AnonymousLifetimeMode::ReportError,
3007 predicates: wc.predicates
3009 .map(|predicate| this.lower_where_predicate(predicate))
3017 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
3019 WherePredicate::BoundPredicate(WhereBoundPredicate {
3020 ref bound_generic_params,
3025 self.with_in_scope_lifetime_defs(
3026 &bound_generic_params,
3028 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
3029 bound_generic_params: this.lower_generic_params(
3030 bound_generic_params,
3031 &NodeMap::default(),
3032 ImplTraitContext::disallowed(),
3034 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
3037 .filter_map(|bound| match *bound {
3038 // Ignore `?Trait` bounds.
3039 // They were copied into type parameters already.
3040 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
3041 _ => Some(this.lower_param_bound(
3043 ImplTraitContext::disallowed(),
3052 WherePredicate::RegionPredicate(WhereRegionPredicate {
3056 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
3058 lifetime: self.lower_lifetime(lifetime),
3059 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3061 WherePredicate::EqPredicate(WhereEqPredicate {
3067 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
3068 hir_id: self.lower_node_id(id),
3069 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
3070 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
3077 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
3079 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
3080 fields.iter().enumerate().map(|f| self.lower_struct_field(f)).collect(),
3083 VariantData::Tuple(ref fields, id) => {
3084 hir::VariantData::Tuple(
3088 .map(|f| self.lower_struct_field(f))
3090 self.lower_node_id(id),
3093 VariantData::Unit(id) => {
3094 hir::VariantData::Unit(self.lower_node_id(id))
3099 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
3100 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
3101 hir::QPath::Resolved(None, path) => path,
3102 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
3106 hir_ref_id: self.lower_node_id(p.ref_id),
3110 fn lower_poly_trait_ref(
3113 mut itctx: ImplTraitContext<'_>,
3114 ) -> hir::PolyTraitRef {
3115 let bound_generic_params = self.lower_generic_params(
3116 &p.bound_generic_params,
3117 &NodeMap::default(),
3120 let trait_ref = self.with_in_scope_lifetime_defs(
3121 &p.bound_generic_params,
3122 |this| this.lower_trait_ref(&p.trait_ref, itctx),
3126 bound_generic_params,
3132 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
3133 let ty = if let TyKind::Path(ref qself, ref path) = f.ty.node {
3134 let t = self.lower_path_ty(
3138 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
3139 ImplTraitContext::disallowed()
3143 self.lower_ty(&f.ty, ImplTraitContext::disallowed())
3147 hir_id: self.lower_node_id(f.id),
3148 ident: match f.ident {
3149 Some(ident) => ident,
3150 // FIXME(jseyfried): positional field hygiene.
3151 None => Ident::new(sym::integer(index), f.span),
3153 vis: self.lower_visibility(&f.vis, None),
3155 attrs: self.lower_attrs(&f.attrs),
3159 fn lower_field(&mut self, f: &Field) -> hir::Field {
3161 hir_id: self.next_id(),
3163 expr: P(self.lower_expr(&f.expr)),
3165 is_shorthand: f.is_shorthand,
3169 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
3171 ty: self.lower_ty(&mt.ty, itctx),
3172 mutbl: self.lower_mutability(mt.mutbl),
3176 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
3177 -> hir::GenericBounds {
3178 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
3181 fn lower_block_with_stmts(
3184 targeted_by_break: bool,
3185 mut stmts: Vec<hir::Stmt>,
3186 ) -> P<hir::Block> {
3187 let mut expr = None;
3189 for (index, stmt) in b.stmts.iter().enumerate() {
3190 if index == b.stmts.len() - 1 {
3191 if let StmtKind::Expr(ref e) = stmt.node {
3192 expr = Some(P(self.lower_expr(e)));
3194 stmts.extend(self.lower_stmt(stmt));
3197 stmts.extend(self.lower_stmt(stmt));
3202 hir_id: self.lower_node_id(b.id),
3203 stmts: stmts.into(),
3205 rules: self.lower_block_check_mode(&b.rules),
3211 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
3212 self.lower_block_with_stmts(b, targeted_by_break, vec![])
3215 fn lower_maybe_async_body(
3221 let closure_id = match asyncness {
3222 IsAsync::Async { closure_id, .. } => closure_id,
3223 IsAsync::NotAsync => return self.lower_fn_body(&decl, |this| {
3224 let body = this.lower_block(body, false);
3225 this.expr_block(body, ThinVec::new())
3229 self.lower_body(|this| {
3230 let mut arguments: Vec<hir::Arg> = Vec::new();
3231 let mut statements: Vec<hir::Stmt> = Vec::new();
3233 // Async function arguments are lowered into the closure body so that they are
3234 // captured and so that the drop order matches the equivalent non-async functions.
3238 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
3245 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
3247 // let __arg2 = __arg2;
3248 // let <pattern> = __arg2;
3249 // let __arg1 = __arg1;
3250 // let <pattern> = __arg1;
3251 // let __arg0 = __arg0;
3252 // let <pattern> = __arg0;
3256 // If `<pattern>` is a simple ident, then it is lowered to a single
3257 // `let <pattern> = <pattern>;` statement as an optimization.
3258 for (index, argument) in decl.inputs.iter().enumerate() {
3259 let argument = this.lower_arg(argument);
3260 let span = argument.pat.span;
3262 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
3263 // `let <pat> = __argN;` statement. In this case, we do not rename the argument.
3264 let (ident, is_simple_argument) = match argument.pat.node {
3265 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _) =>
3268 // Replace the ident for bindings that aren't simple.
3269 let name = format!("__arg{}", index);
3270 let ident = Ident::from_str(&name);
3276 let desugared_span =
3277 this.mark_span_with_reason(DesugaringKind::Async, span, None);
3279 // Construct an argument representing `__argN: <ty>` to replace the argument of the
3282 // If this is the simple case, this argument will end up being the same as the
3283 // original argument, but with a different pattern id.
3284 let mut stmt_attrs = ThinVec::new();
3285 stmt_attrs.extend(argument.attrs.iter().cloned());
3286 let (new_argument_pat, new_argument_id) = this.pat_ident(desugared_span, ident);
3287 let new_argument = hir::Arg {
3288 attrs: argument.attrs,
3289 hir_id: argument.hir_id,
3290 pat: new_argument_pat,
3291 span: argument.span,
3295 if is_simple_argument {
3296 // If this is the simple case, then we only insert one statement that is
3297 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
3298 // `HirId`s are densely assigned.
3299 let expr = this.expr_ident(desugared_span, ident, new_argument_id);
3300 let stmt = this.stmt_let_pat(
3305 hir::LocalSource::AsyncFn
3307 statements.push(stmt);
3309 // If this is not the simple case, then we construct two statements:
3312 // let __argN = __argN;
3313 // let <pat> = __argN;
3316 // The first statement moves the argument into the closure and thus ensures
3317 // that the drop order is correct.
3319 // The second statement creates the bindings that the user wrote.
3321 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
3322 // because the user may have specified a `ref mut` binding in the next
3324 let (move_pat, move_id) = this.pat_ident_binding_mode(
3325 desugared_span, ident, hir::BindingAnnotation::Mutable);
3326 let move_expr = this.expr_ident(desugared_span, ident, new_argument_id);
3327 let move_stmt = this.stmt_let_pat(
3332 hir::LocalSource::AsyncFn
3335 // Construct the `let <pat> = __argN;` statement. We re-use the original
3336 // argument's pattern so that `HirId`s are densely assigned.
3337 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
3338 let pattern_stmt = this.stmt_let_pat(
3341 Some(P(pattern_expr)),
3343 hir::LocalSource::AsyncFn
3346 statements.push(move_stmt);
3347 statements.push(pattern_stmt);
3350 arguments.push(new_argument);
3353 let async_expr = this.make_async_expr(
3354 CaptureBy::Value, closure_id, None, body.span,
3356 let body = this.lower_block_with_stmts(body, false, statements);
3357 this.expr_block(body, ThinVec::new())
3359 (HirVec::from(arguments), this.expr(body.span, async_expr, ThinVec::new()))
3367 attrs: &hir::HirVec<Attribute>,
3368 vis: &mut hir::Visibility,
3370 ) -> hir::ItemKind {
3372 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
3373 ItemKind::Use(ref use_tree) => {
3374 // Start with an empty prefix.
3377 span: use_tree.span,
3380 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
3382 ItemKind::Static(ref t, m, ref e) => {
3383 hir::ItemKind::Static(
3386 if self.sess.features_untracked().impl_trait_in_bindings {
3387 ImplTraitContext::Existential(None)
3389 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3392 self.lower_mutability(m),
3393 self.lower_const_body(e),
3396 ItemKind::Const(ref t, ref e) => {
3397 hir::ItemKind::Const(
3400 if self.sess.features_untracked().impl_trait_in_bindings {
3401 ImplTraitContext::Existential(None)
3403 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3406 self.lower_const_body(e)
3409 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
3410 let fn_def_id = self.resolver.definitions().local_def_id(id);
3411 self.with_new_scopes(|this| {
3412 this.current_item = Some(ident.span);
3414 // Note: we don't need to change the return type from `T` to
3415 // `impl Future<Output = T>` here because lower_body
3416 // only cares about the input argument patterns in the function
3417 // declaration (decl), not the return types.
3418 let body_id = this.lower_maybe_async_body(&decl, header.asyncness.node, body);
3420 let (generics, fn_decl) = this.add_in_band_defs(
3423 AnonymousLifetimeMode::PassThrough,
3424 |this, idty| this.lower_fn_decl(
3426 Some((fn_def_id, idty)),
3428 header.asyncness.node.opt_return_id()
3434 this.lower_fn_header(header),
3440 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
3441 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
3442 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
3443 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
3444 self.lower_ty(t, ImplTraitContext::disallowed()),
3445 self.lower_generics(generics, ImplTraitContext::disallowed()),
3447 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(
3449 generics: self.lower_generics(generics,
3450 ImplTraitContext::Existential(None)),
3451 bounds: self.lower_param_bounds(b,
3452 ImplTraitContext::Existential(None)),
3453 impl_trait_fn: None,
3454 origin: hir::ExistTyOrigin::ExistentialType,
3457 ItemKind::Enum(ref enum_definition, ref generics) => {
3458 hir::ItemKind::Enum(
3460 variants: enum_definition
3463 .map(|x| self.lower_variant(x))
3466 self.lower_generics(generics, ImplTraitContext::disallowed()),
3469 ItemKind::Struct(ref struct_def, ref generics) => {
3470 let struct_def = self.lower_variant_data(struct_def);
3471 hir::ItemKind::Struct(
3473 self.lower_generics(generics, ImplTraitContext::disallowed()),
3476 ItemKind::Union(ref vdata, ref generics) => {
3477 let vdata = self.lower_variant_data(vdata);
3478 hir::ItemKind::Union(
3480 self.lower_generics(generics, ImplTraitContext::disallowed()),
3492 let def_id = self.resolver.definitions().local_def_id(id);
3494 // Lower the "impl header" first. This ordering is important
3495 // for in-band lifetimes! Consider `'a` here:
3497 // impl Foo<'a> for u32 {
3498 // fn method(&'a self) { .. }
3501 // Because we start by lowering the `Foo<'a> for u32`
3502 // part, we will add `'a` to the list of generics on
3503 // the impl. When we then encounter it later in the
3504 // method, it will not be considered an in-band
3505 // lifetime to be added, but rather a reference to a
3507 let lowered_trait_impl_id = self.lower_node_id(id);
3508 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
3511 AnonymousLifetimeMode::CreateParameter,
3513 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
3514 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
3517 if let Some(ref trait_ref) = trait_ref {
3518 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
3519 this.trait_impls.entry(def_id).or_default().push(
3520 lowered_trait_impl_id);
3524 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
3526 (trait_ref, lowered_ty)
3530 let new_impl_items = self.with_in_scope_lifetime_defs(
3531 &ast_generics.params,
3535 .map(|item| this.lower_impl_item_ref(item))
3540 hir::ItemKind::Impl(
3541 self.lower_unsafety(unsafety),
3542 self.lower_impl_polarity(polarity),
3543 self.lower_defaultness(defaultness, true /* [1] */),
3550 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
3551 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
3554 .map(|item| self.lower_trait_item_ref(item))
3556 hir::ItemKind::Trait(
3557 self.lower_is_auto(is_auto),
3558 self.lower_unsafety(unsafety),
3559 self.lower_generics(generics, ImplTraitContext::disallowed()),
3564 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
3565 self.lower_generics(generics, ImplTraitContext::disallowed()),
3566 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3568 ItemKind::MacroDef(..)
3569 | ItemKind::Mac(..) => bug!("`TyMac` should have been expanded by now"),
3572 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
3573 // not cause an assertion failure inside the `lower_defaultness` function.
3581 vis: &mut hir::Visibility,
3583 attrs: &hir::HirVec<Attribute>,
3584 ) -> hir::ItemKind {
3585 debug!("lower_use_tree(tree={:?})", tree);
3586 debug!("lower_use_tree: vis = {:?}", vis);
3588 let path = &tree.prefix;
3589 let segments = prefix
3592 .chain(path.segments.iter())
3597 UseTreeKind::Simple(rename, id1, id2) => {
3598 *ident = tree.ident();
3600 // First, apply the prefix to the path.
3601 let mut path = Path {
3606 // Correctly resolve `self` imports.
3607 if path.segments.len() > 1
3608 && path.segments.last().unwrap().ident.name == kw::SelfLower
3610 let _ = path.segments.pop();
3611 if rename.is_none() {
3612 *ident = path.segments.last().unwrap().ident;
3616 let mut resolutions = self.expect_full_res_from_use(id);
3617 // We want to return *something* from this function, so hold onto the first item
3619 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
3621 // Here, we are looping over namespaces, if they exist for the definition
3622 // being imported. We only handle type and value namespaces because we
3623 // won't be dealing with macros in the rest of the compiler.
3624 // Essentially a single `use` which imports two names is desugared into
3626 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
3628 let mut path = path.clone();
3629 for seg in &mut path.segments {
3630 seg.id = self.sess.next_node_id();
3632 let span = path.span;
3634 self.with_hir_id_owner(new_node_id, |this| {
3635 let new_id = this.lower_node_id(new_node_id);
3636 let res = this.lower_res(res);
3638 this.lower_path_extra(res, &path, ParamMode::Explicit, None);
3639 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
3640 let vis = this.rebuild_vis(&vis);
3646 attrs: attrs.into_iter().cloned().collect(),
3656 P(self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None));
3657 hir::ItemKind::Use(path, hir::UseKind::Single)
3659 UseTreeKind::Glob => {
3660 let path = P(self.lower_path(
3666 ParamMode::Explicit,
3668 hir::ItemKind::Use(path, hir::UseKind::Glob)
3670 UseTreeKind::Nested(ref trees) => {
3671 // Nested imports are desugared into simple imports.
3672 // So, if we start with
3675 // pub(x) use foo::{a, b};
3678 // we will create three items:
3681 // pub(x) use foo::a;
3682 // pub(x) use foo::b;
3683 // pub(x) use foo::{}; // <-- this is called the `ListStem`
3686 // The first two are produced by recursively invoking
3687 // `lower_use_tree` (and indeed there may be things
3688 // like `use foo::{a::{b, c}}` and so forth). They
3689 // wind up being directly added to
3690 // `self.items`. However, the structure of this
3691 // function also requires us to return one item, and
3692 // for that we return the `{}` import (called the
3697 span: prefix.span.to(path.span),
3700 // Add all the nested `PathListItem`s to the HIR.
3701 for &(ref use_tree, id) in trees {
3702 let new_hir_id = self.lower_node_id(id);
3704 let mut prefix = prefix.clone();
3706 // Give the segments new node-ids since they are being cloned.
3707 for seg in &mut prefix.segments {
3708 seg.id = self.sess.next_node_id();
3711 // Each `use` import is an item and thus are owners of the
3712 // names in the path. Up to this point the nested import is
3713 // the current owner, since we want each desugared import to
3714 // own its own names, we have to adjust the owner before
3715 // lowering the rest of the import.
3716 self.with_hir_id_owner(id, |this| {
3717 let mut vis = this.rebuild_vis(&vis);
3718 let mut ident = *ident;
3720 let item = this.lower_use_tree(use_tree,
3731 attrs: attrs.into_iter().cloned().collect(),
3734 span: use_tree.span,
3740 // Subtle and a bit hacky: we lower the privacy level
3741 // of the list stem to "private" most of the time, but
3742 // not for "restricted" paths. The key thing is that
3743 // we don't want it to stay as `pub` (with no caveats)
3744 // because that affects rustdoc and also the lints
3745 // about `pub` items. But we can't *always* make it
3746 // private -- particularly not for restricted paths --
3747 // because it contains node-ids that would then be
3748 // unused, failing the check that HirIds are "densely
3751 hir::VisibilityKind::Public |
3752 hir::VisibilityKind::Crate(_) |
3753 hir::VisibilityKind::Inherited => {
3754 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3756 hir::VisibilityKind::Restricted { .. } => {
3757 // Do nothing here, as described in the comment on the match.
3761 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
3762 let res = self.lower_res(res);
3763 let path = P(self.lower_path_extra(res, &prefix, ParamMode::Explicit, None));
3764 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3769 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
3770 /// many times in the HIR tree; for each occurrence, we need to assign distinct
3771 /// `NodeId`s. (See, e.g., #56128.)
3772 fn rebuild_use_path(&mut self, path: &hir::Path) -> hir::Path {
3773 debug!("rebuild_use_path(path = {:?})", path);
3774 let segments = path.segments.iter().map(|seg| hir::PathSegment {
3776 hir_id: seg.hir_id.map(|_| self.next_id()),
3779 infer_args: seg.infer_args,
3788 fn rebuild_vis(&mut self, vis: &hir::Visibility) -> hir::Visibility {
3789 let vis_kind = match vis.node {
3790 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3791 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3792 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3793 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
3794 hir::VisibilityKind::Restricted {
3795 path: P(self.rebuild_use_path(path)),
3796 hir_id: self.next_id(),
3800 respan(vis.span, vis_kind)
3803 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3804 let trait_item_def_id = self.resolver.definitions().local_def_id(i.id);
3806 let (generics, node) = match i.node {
3807 TraitItemKind::Const(ref ty, ref default) => (
3808 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3809 hir::TraitItemKind::Const(
3810 self.lower_ty(ty, ImplTraitContext::disallowed()),
3813 .map(|x| self.lower_const_body(x)),
3816 TraitItemKind::Method(ref sig, None) => {
3817 let names = self.lower_fn_args_to_names(&sig.decl);
3818 let (generics, sig) = self.lower_method_sig(
3825 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3827 TraitItemKind::Method(ref sig, Some(ref body)) => {
3828 let body_id = self.lower_fn_body(&sig.decl, |this| {
3829 let body = this.lower_block(body, false);
3830 this.expr_block(body, ThinVec::new())
3832 let (generics, sig) = self.lower_method_sig(
3839 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3841 TraitItemKind::Type(ref bounds, ref default) => {
3842 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
3843 let node = hir::TraitItemKind::Type(
3844 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3847 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3852 TraitItemKind::Macro(..) => bug!("macro item shouldn't exist at this point"),
3856 hir_id: self.lower_node_id(i.id),
3858 attrs: self.lower_attrs(&i.attrs),
3865 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3866 let (kind, has_default) = match i.node {
3867 TraitItemKind::Const(_, ref default) => {
3868 (hir::AssocItemKind::Const, default.is_some())
3870 TraitItemKind::Type(_, ref default) => {
3871 (hir::AssocItemKind::Type, default.is_some())
3873 TraitItemKind::Method(ref sig, ref default) => (
3874 hir::AssocItemKind::Method {
3875 has_self: sig.decl.has_self(),
3879 TraitItemKind::Macro(..) => unimplemented!(),
3882 id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) },
3885 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3890 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3891 let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
3893 let (generics, node) = match i.node {
3894 ImplItemKind::Const(ref ty, ref expr) => (
3895 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3896 hir::ImplItemKind::Const(
3897 self.lower_ty(ty, ImplTraitContext::disallowed()),
3898 self.lower_const_body(expr),
3901 ImplItemKind::Method(ref sig, ref body) => {
3902 self.current_item = Some(i.span);
3903 let body_id = self.lower_maybe_async_body(
3904 &sig.decl, sig.header.asyncness.node, body
3906 let impl_trait_return_allow = !self.is_in_trait_impl;
3907 let (generics, sig) = self.lower_method_sig(
3911 impl_trait_return_allow,
3912 sig.header.asyncness.node.opt_return_id(),
3915 (generics, hir::ImplItemKind::Method(sig, body_id))
3917 ImplItemKind::Type(ref ty) => (
3918 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3919 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3921 ImplItemKind::Existential(ref bounds) => (
3922 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3923 hir::ImplItemKind::Existential(
3924 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3927 ImplItemKind::Macro(..) => bug!("`TyMac` should have been expanded by now"),
3931 hir_id: self.lower_node_id(i.id),
3933 attrs: self.lower_attrs(&i.attrs),
3935 vis: self.lower_visibility(&i.vis, None),
3936 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3941 // [1] since `default impl` is not yet implemented, this is always true in impls
3944 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3946 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
3949 vis: self.lower_visibility(&i.vis, Some(i.id)),
3950 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3951 kind: match i.node {
3952 ImplItemKind::Const(..) => hir::AssocItemKind::Const,
3953 ImplItemKind::Type(..) => hir::AssocItemKind::Type,
3954 ImplItemKind::Existential(..) => hir::AssocItemKind::Existential,
3955 ImplItemKind::Method(ref sig, _) => hir::AssocItemKind::Method {
3956 has_self: sig.decl.has_self(),
3958 ImplItemKind::Macro(..) => unimplemented!(),
3962 // [1] since `default impl` is not yet implemented, this is always true in impls
3965 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3968 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3972 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3973 let node_ids = match i.node {
3974 ItemKind::Use(ref use_tree) => {
3975 let mut vec = smallvec![i.id];
3976 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3979 ItemKind::MacroDef(..) => SmallVec::new(),
3981 ItemKind::Impl(.., None, _, _) => smallvec![i.id],
3982 ItemKind::Static(ref ty, ..) => {
3983 let mut ids = smallvec![i.id];
3984 if self.sess.features_untracked().impl_trait_in_bindings {
3985 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3986 visitor.visit_ty(ty);
3990 ItemKind::Const(ref ty, ..) => {
3991 let mut ids = smallvec![i.id];
3992 if self.sess.features_untracked().impl_trait_in_bindings {
3993 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3994 visitor.visit_ty(ty);
3998 _ => smallvec![i.id],
4001 node_ids.into_iter().map(|node_id| hir::ItemId {
4002 id: self.allocate_hir_id_counter(node_id)
4006 fn lower_item_id_use_tree(&mut self,
4009 vec: &mut SmallVec<[NodeId; 1]>)
4012 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
4014 self.lower_item_id_use_tree(nested, id, vec);
4016 UseTreeKind::Glob => {}
4017 UseTreeKind::Simple(_, id1, id2) => {
4018 for (_, &id) in self.expect_full_res_from_use(base_id)
4020 .zip([id1, id2].iter())
4028 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
4029 let mut ident = i.ident;
4030 let mut vis = self.lower_visibility(&i.vis, None);
4031 let attrs = self.lower_attrs(&i.attrs);
4032 if let ItemKind::MacroDef(ref def) = i.node {
4033 if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) {
4034 let body = self.lower_token_stream(def.stream());
4035 let hir_id = self.lower_node_id(i.id);
4036 self.exported_macros.push(hir::MacroDef {
4046 self.non_exported_macro_attrs.extend(attrs.into_iter());
4051 let node = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.node);
4054 hir_id: self.lower_node_id(i.id),
4063 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
4064 let def_id = self.resolver.definitions().local_def_id(i.id);
4066 hir_id: self.lower_node_id(i.id),
4068 attrs: self.lower_attrs(&i.attrs),
4069 node: match i.node {
4070 ForeignItemKind::Fn(ref fdec, ref generics) => {
4071 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
4074 AnonymousLifetimeMode::PassThrough,
4077 // Disallow impl Trait in foreign items
4078 this.lower_fn_decl(fdec, None, false, None),
4079 this.lower_fn_args_to_names(fdec),
4084 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
4086 ForeignItemKind::Static(ref t, m) => {
4087 hir::ForeignItemKind::Static(
4088 self.lower_ty(t, ImplTraitContext::disallowed()), self.lower_mutability(m))
4090 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
4091 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
4093 vis: self.lower_visibility(&i.vis, None),
4098 fn lower_method_sig(
4100 generics: &Generics,
4103 impl_trait_return_allow: bool,
4104 is_async: Option<NodeId>,
4105 ) -> (hir::Generics, hir::MethodSig) {
4106 let header = self.lower_fn_header(sig.header);
4107 let (generics, decl) = self.add_in_band_defs(
4110 AnonymousLifetimeMode::PassThrough,
4111 |this, idty| this.lower_fn_decl(
4113 Some((fn_def_id, idty)),
4114 impl_trait_return_allow,
4118 (generics, hir::MethodSig { header, decl })
4121 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
4123 IsAuto::Yes => hir::IsAuto::Yes,
4124 IsAuto::No => hir::IsAuto::No,
4128 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
4130 unsafety: self.lower_unsafety(h.unsafety),
4131 asyncness: self.lower_asyncness(h.asyncness.node),
4132 constness: self.lower_constness(h.constness),
4137 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
4139 Unsafety::Unsafe => hir::Unsafety::Unsafe,
4140 Unsafety::Normal => hir::Unsafety::Normal,
4144 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
4146 Constness::Const => hir::Constness::Const,
4147 Constness::NotConst => hir::Constness::NotConst,
4151 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
4153 IsAsync::Async { .. } => hir::IsAsync::Async,
4154 IsAsync::NotAsync => hir::IsAsync::NotAsync,
4158 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
4160 UnOp::Deref => hir::UnDeref,
4161 UnOp::Not => hir::UnNot,
4162 UnOp::Neg => hir::UnNeg,
4166 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
4168 node: match b.node {
4169 BinOpKind::Add => hir::BinOpKind::Add,
4170 BinOpKind::Sub => hir::BinOpKind::Sub,
4171 BinOpKind::Mul => hir::BinOpKind::Mul,
4172 BinOpKind::Div => hir::BinOpKind::Div,
4173 BinOpKind::Rem => hir::BinOpKind::Rem,
4174 BinOpKind::And => hir::BinOpKind::And,
4175 BinOpKind::Or => hir::BinOpKind::Or,
4176 BinOpKind::BitXor => hir::BinOpKind::BitXor,
4177 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
4178 BinOpKind::BitOr => hir::BinOpKind::BitOr,
4179 BinOpKind::Shl => hir::BinOpKind::Shl,
4180 BinOpKind::Shr => hir::BinOpKind::Shr,
4181 BinOpKind::Eq => hir::BinOpKind::Eq,
4182 BinOpKind::Lt => hir::BinOpKind::Lt,
4183 BinOpKind::Le => hir::BinOpKind::Le,
4184 BinOpKind::Ne => hir::BinOpKind::Ne,
4185 BinOpKind::Ge => hir::BinOpKind::Ge,
4186 BinOpKind::Gt => hir::BinOpKind::Gt,
4192 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
4193 let node = match p.node {
4194 PatKind::Wild => hir::PatKind::Wild,
4195 PatKind::Ident(ref binding_mode, ident, ref sub) => {
4196 let lower_sub = |this: &mut Self| sub.as_ref().map(|x| this.lower_pat(x));
4197 self.lower_pat_ident(p, binding_mode, ident, lower_sub)
4199 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
4200 PatKind::TupleStruct(ref path, ref pats) => {
4201 let qpath = self.lower_qpath(
4205 ParamMode::Optional,
4206 ImplTraitContext::disallowed(),
4208 let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple struct");
4209 hir::PatKind::TupleStruct(qpath, pats, ddpos)
4211 PatKind::Path(ref qself, ref path) => {
4212 let qpath = self.lower_qpath(
4216 ParamMode::Optional,
4217 ImplTraitContext::disallowed(),
4219 hir::PatKind::Path(qpath)
4221 PatKind::Struct(ref path, ref fields, etc) => {
4222 let qpath = self.lower_qpath(
4226 ParamMode::Optional,
4227 ImplTraitContext::disallowed(),
4235 node: hir::FieldPat {
4236 hir_id: self.next_id(),
4237 ident: f.node.ident,
4238 pat: self.lower_pat(&f.node.pat),
4239 is_shorthand: f.node.is_shorthand,
4244 hir::PatKind::Struct(qpath, fs, etc)
4246 PatKind::Tuple(ref pats) => {
4247 let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple");
4248 hir::PatKind::Tuple(pats, ddpos)
4250 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
4251 PatKind::Ref(ref inner, mutbl) => {
4252 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
4254 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
4255 P(self.lower_expr(e1)),
4256 P(self.lower_expr(e2)),
4257 self.lower_range_end(end),
4259 PatKind::Slice(ref pats) => self.lower_pat_slice(pats),
4261 // If we reach here the `..` pattern is not semantically allowed.
4262 self.ban_illegal_rest_pat(p.span)
4264 PatKind::Paren(ref inner) => return self.lower_pat(inner),
4265 PatKind::Mac(_) => panic!("Shouldn't exist here"),
4268 self.pat_with_node_id_of(p, node)
4275 ) -> (HirVec<P<hir::Pat>>, Option<usize>) {
4276 let mut elems = Vec::with_capacity(pats.len());
4277 let mut rest = None;
4279 let mut iter = pats.iter().enumerate();
4280 while let Some((idx, pat)) = iter.next() {
4281 // Interpret the first `..` pattern as a subtuple pattern.
4283 rest = Some((idx, pat.span));
4286 // It was not a subslice pattern so lower it normally.
4287 elems.push(self.lower_pat(pat));
4290 while let Some((_, pat)) = iter.next() {
4291 // There was a previous subtuple pattern; make sure we don't allow more.
4293 self.ban_extra_rest_pat(pat.span, rest.unwrap().1, ctx);
4295 elems.push(self.lower_pat(pat));
4299 (elems.into(), rest.map(|(ddpos, _)| ddpos))
4302 fn lower_pat_slice(&mut self, pats: &[AstP<Pat>]) -> hir::PatKind {
4303 let mut before = Vec::new();
4304 let mut after = Vec::new();
4305 let mut slice = None;
4306 let mut prev_rest_span = None;
4308 let mut iter = pats.iter();
4309 while let Some(pat) = iter.next() {
4310 // Interpret the first `((ref mut?)? x @)? ..` pattern as a subslice pattern.
4313 prev_rest_span = Some(pat.span);
4314 slice = Some(self.pat_wild_with_node_id_of(pat));
4317 PatKind::Ident(ref bm, ident, Some(ref sub)) if sub.is_rest() => {
4318 prev_rest_span = Some(sub.span);
4319 let lower_sub = |this: &mut Self| Some(this.pat_wild_with_node_id_of(sub));
4320 let node = self.lower_pat_ident(pat, bm, ident, lower_sub);
4321 slice = Some(self.pat_with_node_id_of(pat, node));
4327 // It was not a subslice pattern so lower it normally.
4328 before.push(self.lower_pat(pat));
4331 while let Some(pat) = iter.next() {
4332 // There was a previous subslice pattern; make sure we don't allow more.
4333 let rest_span = match pat.node {
4334 PatKind::Rest => Some(pat.span),
4335 PatKind::Ident(.., Some(ref sub)) if sub.is_rest() => {
4336 // The `HirValidator` is merciless; add a `_` pattern to avoid ICEs.
4337 after.push(self.pat_wild_with_node_id_of(pat));
4342 if let Some(rest_span) = rest_span {
4343 self.ban_extra_rest_pat(rest_span, prev_rest_span.unwrap(), "slice");
4345 after.push(self.lower_pat(pat));
4349 hir::PatKind::Slice(before.into(), slice, after.into())
4355 binding_mode: &BindingMode,
4357 lower_sub: impl FnOnce(&mut Self) -> Option<P<hir::Pat>>,
4359 match self.resolver.get_partial_res(p.id).map(|d| d.base_res()) {
4360 // `None` can occur in body-less function signatures
4361 res @ None | res @ Some(Res::Local(_)) => {
4362 let canonical_id = match res {
4363 Some(Res::Local(id)) => id,
4367 hir::PatKind::Binding(
4368 self.lower_binding_mode(binding_mode),
4369 self.lower_node_id(canonical_id),
4374 Some(res) => hir::PatKind::Path(hir::QPath::Resolved(
4378 res: self.lower_res(res),
4379 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4385 fn pat_wild_with_node_id_of(&mut self, p: &Pat) -> P<hir::Pat> {
4386 self.pat_with_node_id_of(p, hir::PatKind::Wild)
4389 /// Construct a `Pat` with the `HirId` of `p.id` lowered.
4390 fn pat_with_node_id_of(&mut self, p: &Pat, node: hir::PatKind) -> P<hir::Pat> {
4392 hir_id: self.lower_node_id(p.id),
4398 /// Emit a friendly error for extra `..` patterns in a tuple/tuple struct/slice pattern.
4399 fn ban_extra_rest_pat(&self, sp: Span, prev_sp: Span, ctx: &str) {
4401 .struct_span_err(sp, &format!("`..` can only be used once per {} pattern", ctx))
4402 .span_label(sp, &format!("can only be used once per {} pattern", ctx))
4403 .span_label(prev_sp, "previously used here")
4407 /// Used to ban the `..` pattern in places it shouldn't be semantically.
4408 fn ban_illegal_rest_pat(&self, sp: Span) -> hir::PatKind {
4410 .struct_span_err(sp, "`..` patterns are not allowed here")
4411 .note("only allowed in tuple, tuple struct, and slice patterns")
4414 // We're not in a list context so `..` can be reasonably treated
4415 // as `_` because it should always be valid and roughly matches the
4416 // intent of `..` (notice that the rest of a single slot is that slot).
4420 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
4422 RangeEnd::Included(_) => hir::RangeEnd::Included,
4423 RangeEnd::Excluded => hir::RangeEnd::Excluded,
4427 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
4428 self.with_new_scopes(|this| {
4430 hir_id: this.lower_node_id(c.id),
4431 body: this.lower_const_body(&c.value),
4436 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
4437 let kind = match e.node {
4438 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
4439 ExprKind::Array(ref exprs) => {
4440 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
4442 ExprKind::Repeat(ref expr, ref count) => {
4443 let expr = P(self.lower_expr(expr));
4444 let count = self.lower_anon_const(count);
4445 hir::ExprKind::Repeat(expr, count)
4447 ExprKind::Tup(ref elts) => {
4448 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
4450 ExprKind::Call(ref f, ref args) => {
4451 let f = P(self.lower_expr(f));
4452 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
4454 ExprKind::MethodCall(ref seg, ref args) => {
4455 let hir_seg = P(self.lower_path_segment(
4458 ParamMode::Optional,
4460 ParenthesizedGenericArgs::Err,
4461 ImplTraitContext::disallowed(),
4464 let args = args.iter().map(|x| self.lower_expr(x)).collect();
4465 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
4467 ExprKind::Binary(binop, ref lhs, ref rhs) => {
4468 let binop = self.lower_binop(binop);
4469 let lhs = P(self.lower_expr(lhs));
4470 let rhs = P(self.lower_expr(rhs));
4471 hir::ExprKind::Binary(binop, lhs, rhs)
4473 ExprKind::Unary(op, ref ohs) => {
4474 let op = self.lower_unop(op);
4475 let ohs = P(self.lower_expr(ohs));
4476 hir::ExprKind::Unary(op, ohs)
4478 ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.node.clone())),
4479 ExprKind::Cast(ref expr, ref ty) => {
4480 let expr = P(self.lower_expr(expr));
4481 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4483 ExprKind::Type(ref expr, ref ty) => {
4484 let expr = P(self.lower_expr(expr));
4485 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4487 ExprKind::AddrOf(m, ref ohs) => {
4488 let m = self.lower_mutability(m);
4489 let ohs = P(self.lower_expr(ohs));
4490 hir::ExprKind::AddrOf(m, ohs)
4492 ExprKind::Let(ref pats, ref scrutinee) => {
4493 // If we got here, the `let` expression is not allowed.
4495 .struct_span_err(e.span, "`let` expressions are not supported here")
4496 .note("only supported directly in conditions of `if`- and `while`-expressions")
4497 .note("as well as when nested within `&&` and parenthesis in those conditions")
4500 // For better recovery, we emit:
4502 // match scrutinee { pats => true, _ => false }
4504 // While this doesn't fully match the user's intent, it has key advantages:
4505 // 1. We can avoid using `abort_if_errors`.
4506 // 2. We can typeck both `pats` and `scrutinee`.
4507 // 3. `pats` is allowed to be refutable.
4508 // 4. The return type of the block is `bool` which seems like what the user wanted.
4509 let scrutinee = self.lower_expr(scrutinee);
4511 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4512 let expr = self.expr_bool(e.span, true);
4513 self.arm(pats, P(expr))
4516 let pats = hir_vec![self.pat_wild(e.span)];
4517 let expr = self.expr_bool(e.span, false);
4518 self.arm(pats, P(expr))
4520 hir::ExprKind::Match(
4522 vec![then_arm, else_arm].into(),
4523 hir::MatchSource::Normal,
4526 // FIXME(#53667): handle lowering of && and parens.
4527 ExprKind::If(ref cond, ref then, ref else_opt) => {
4528 // `_ => else_block` where `else_block` is `{}` if there's `None`:
4529 let else_pat = self.pat_wild(e.span);
4530 let (else_expr, contains_else_clause) = match else_opt {
4531 None => (self.expr_block_empty(e.span), false),
4532 Some(els) => (self.lower_expr(els), true),
4534 let else_arm = self.arm(hir_vec![else_pat], P(else_expr));
4536 // Handle then + scrutinee:
4537 let then_blk = self.lower_block(then, false);
4538 let then_expr = self.expr_block(then_blk, ThinVec::new());
4539 let (then_pats, scrutinee, desugar) = match cond.node {
4540 // `<pat> => <then>`:
4541 ExprKind::Let(ref pats, ref scrutinee) => {
4542 let scrutinee = self.lower_expr(scrutinee);
4543 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4544 let desugar = hir::MatchSource::IfLetDesugar { contains_else_clause };
4545 (pats, scrutinee, desugar)
4547 // `true => <then>`:
4550 let cond = self.lower_expr(cond);
4551 let span_block = self.mark_span_with_reason(
4552 DesugaringKind::CondTemporary, cond.span, None
4554 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
4555 // to preserve drop semantics since `if cond { ... }` does not
4556 // let temporaries live outside of `cond`.
4557 let cond = self.expr_drop_temps(span_block, P(cond), ThinVec::new());
4559 let desugar = hir::MatchSource::IfDesugar { contains_else_clause };
4560 let pats = hir_vec![self.pat_bool(e.span, true)];
4561 (pats, cond, desugar)
4564 let then_arm = self.arm(then_pats, P(then_expr));
4566 hir::ExprKind::Match(P(scrutinee), vec![then_arm, else_arm].into(), desugar)
4568 // FIXME(#53667): handle lowering of && and parens.
4569 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4570 // Note that the block AND the condition are evaluated in the loop scope.
4571 // This is done to allow `break` from inside the condition of the loop.
4575 let else_pat = this.pat_wild(e.span);
4576 let else_expr = this.expr_break(e.span, ThinVec::new());
4577 this.arm(hir_vec![else_pat], else_expr)
4580 // Handle then + scrutinee:
4581 let then_blk = this.lower_block(body, false);
4582 let then_expr = this.expr_block(then_blk, ThinVec::new());
4583 let (then_pats, scrutinee, desugar, source) = match cond.node {
4584 ExprKind::Let(ref pats, ref scrutinee) => {
4587 // [opt_ident]: loop {
4588 // match <sub_expr> {
4593 let scrutinee = this.with_loop_condition_scope(|t| t.lower_expr(scrutinee));
4594 let pats = pats.iter().map(|pat| this.lower_pat(pat)).collect();
4595 let desugar = hir::MatchSource::WhileLetDesugar;
4596 (pats, scrutinee, desugar, hir::LoopSource::WhileLet)
4599 // We desugar: `'label: while $cond $body` into:
4603 // match DropTemps($cond) {
4611 let cond = this.with_loop_condition_scope(|this| this.lower_expr(cond));
4612 let span_block = this.mark_span_with_reason(
4613 DesugaringKind::CondTemporary, cond.span, None
4615 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
4616 // to preserve drop semantics since `while cond { ... }` does not
4617 // let temporaries live outside of `cond`.
4618 let cond = this.expr_drop_temps(span_block, P(cond), ThinVec::new());
4620 let desugar = hir::MatchSource::WhileDesugar;
4621 // `true => <then>`:
4622 let pats = hir_vec![this.pat_bool(e.span, true)];
4623 (pats, cond, desugar, hir::LoopSource::While)
4626 let then_arm = this.arm(then_pats, P(then_expr));
4628 // `match <scrutinee> { ... }`
4629 let match_expr = this.expr_match(
4632 hir_vec![then_arm, else_arm],
4636 // `[opt_ident]: loop { ... }`
4637 hir::ExprKind::Loop(
4638 P(this.block_expr(P(match_expr))),
4639 this.lower_label(opt_label),
4643 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4644 hir::ExprKind::Loop(
4645 this.lower_block(body, false),
4646 this.lower_label(opt_label),
4647 hir::LoopSource::Loop,
4650 ExprKind::TryBlock(ref body) => {
4651 self.with_catch_scope(body.id, |this| {
4652 let unstable_span = this.mark_span_with_reason(
4653 DesugaringKind::TryBlock,
4655 this.allow_try_trait.clone(),
4657 let mut block = this.lower_block(body, true).into_inner();
4658 let tail = block.expr.take().map_or_else(
4660 let span = this.sess.source_map().end_point(unstable_span);
4663 node: hir::ExprKind::Tup(hir_vec![]),
4664 attrs: ThinVec::new(),
4665 hir_id: this.next_id(),
4668 |x: P<hir::Expr>| x.into_inner(),
4670 block.expr = Some(this.wrap_in_try_constructor(
4671 sym::from_ok, tail, unstable_span));
4672 hir::ExprKind::Block(P(block), None)
4675 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
4676 P(self.lower_expr(expr)),
4677 arms.iter().map(|x| self.lower_arm(x)).collect(),
4678 hir::MatchSource::Normal,
4680 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
4681 self.make_async_expr(capture_clause, closure_node_id, None, block.span, |this| {
4682 this.with_new_scopes(|this| {
4683 let block = this.lower_block(block, false);
4684 this.expr_block(block, ThinVec::new())
4688 ExprKind::Await(_origin, ref expr) => self.lower_await(e.span, expr),
4690 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
4692 if let IsAsync::Async { closure_id, .. } = asyncness {
4693 let outer_decl = FnDecl {
4694 inputs: decl.inputs.clone(),
4695 output: FunctionRetTy::Default(fn_decl_span),
4698 // We need to lower the declaration outside the new scope, because we
4699 // have to conserve the state of being inside a loop condition for the
4700 // closure argument types.
4701 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
4703 self.with_new_scopes(|this| {
4704 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
4705 if capture_clause == CaptureBy::Ref &&
4706 !decl.inputs.is_empty()
4712 "`async` non-`move` closures with arguments \
4713 are not currently supported",
4715 .help("consider using `let` statements to manually capture \
4716 variables by reference before entering an \
4717 `async move` closure")
4721 // Transform `async |x: u8| -> X { ... }` into
4722 // `|x: u8| future_from_generator(|| -> X { ... })`.
4723 let body_id = this.lower_fn_body(&outer_decl, |this| {
4724 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
4727 let async_body = this.make_async_expr(
4728 capture_clause, closure_id, async_ret_ty, body.span,
4730 this.with_new_scopes(|this| this.lower_expr(body))
4732 this.expr(fn_decl_span, async_body, ThinVec::new())
4734 hir::ExprKind::Closure(
4735 this.lower_capture_clause(capture_clause),
4743 // Lower outside new scope to preserve `is_in_loop_condition`.
4744 let fn_decl = self.lower_fn_decl(decl, None, false, None);
4746 self.with_new_scopes(|this| {
4747 this.current_item = Some(fn_decl_span);
4748 let mut generator_kind = None;
4749 let body_id = this.lower_fn_body(decl, |this| {
4750 let e = this.lower_expr(body);
4751 generator_kind = this.generator_kind;
4754 let generator_option = this.generator_movability_for_fn(
4760 hir::ExprKind::Closure(
4761 this.lower_capture_clause(capture_clause),
4770 ExprKind::Block(ref blk, opt_label) => {
4771 hir::ExprKind::Block(self.lower_block(blk,
4772 opt_label.is_some()),
4773 self.lower_label(opt_label))
4775 ExprKind::Assign(ref el, ref er) => {
4776 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
4778 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
4779 self.lower_binop(op),
4780 P(self.lower_expr(el)),
4781 P(self.lower_expr(er)),
4783 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
4784 ExprKind::Index(ref el, ref er) => {
4785 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
4787 // Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
4788 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
4789 let id = self.next_id();
4790 let e1 = self.lower_expr(e1);
4791 let e2 = self.lower_expr(e2);
4792 self.expr_call_std_assoc_fn(
4795 &[sym::ops, sym::RangeInclusive],
4800 ExprKind::Range(ref e1, ref e2, lims) => {
4801 use syntax::ast::RangeLimits::*;
4803 let path = match (e1, e2, lims) {
4804 (&None, &None, HalfOpen) => sym::RangeFull,
4805 (&Some(..), &None, HalfOpen) => sym::RangeFrom,
4806 (&None, &Some(..), HalfOpen) => sym::RangeTo,
4807 (&Some(..), &Some(..), HalfOpen) => sym::Range,
4808 (&None, &Some(..), Closed) => sym::RangeToInclusive,
4809 (&Some(..), &Some(..), Closed) => unreachable!(),
4810 (_, &None, Closed) => self.diagnostic()
4811 .span_fatal(e.span, "inclusive range with no end")
4815 let fields = e1.iter()
4816 .map(|e| ("start", e))
4817 .chain(e2.iter().map(|e| ("end", e)))
4819 let expr = P(self.lower_expr(&e));
4820 let ident = Ident::new(Symbol::intern(s), e.span);
4821 self.field(ident, expr, e.span)
4823 .collect::<P<[hir::Field]>>();
4825 let is_unit = fields.is_empty();
4826 let struct_path = [sym::ops, path];
4827 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
4828 let struct_path = hir::QPath::Resolved(None, P(struct_path));
4831 hir_id: self.lower_node_id(e.id),
4833 hir::ExprKind::Path(struct_path)
4835 hir::ExprKind::Struct(P(struct_path), fields, None)
4838 attrs: e.attrs.clone(),
4841 ExprKind::Path(ref qself, ref path) => {
4842 let qpath = self.lower_qpath(
4846 ParamMode::Optional,
4847 ImplTraitContext::disallowed(),
4849 hir::ExprKind::Path(qpath)
4851 ExprKind::Break(opt_label, ref opt_expr) => {
4852 let destination = if self.is_in_loop_condition && opt_label.is_none() {
4855 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4858 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4860 hir::ExprKind::Break(
4862 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
4865 ExprKind::Continue(opt_label) => {
4866 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
4869 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4872 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4875 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
4876 ExprKind::InlineAsm(ref asm) => {
4877 let hir_asm = hir::InlineAsm {
4878 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
4879 outputs: asm.outputs
4881 .map(|out| hir::InlineAsmOutput {
4882 constraint: out.constraint.clone(),
4884 is_indirect: out.is_indirect,
4885 span: out.expr.span,
4888 asm: asm.asm.clone(),
4889 asm_str_style: asm.asm_str_style,
4890 clobbers: asm.clobbers.clone().into(),
4891 volatile: asm.volatile,
4892 alignstack: asm.alignstack,
4893 dialect: asm.dialect,
4896 let outputs = asm.outputs
4898 .map(|out| self.lower_expr(&out.expr))
4900 let inputs = asm.inputs
4902 .map(|&(_, ref input)| self.lower_expr(input))
4904 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
4906 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4911 ParamMode::Optional,
4912 ImplTraitContext::disallowed(),
4914 fields.iter().map(|x| self.lower_field(x)).collect(),
4915 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4917 ExprKind::Paren(ref ex) => {
4918 let mut ex = self.lower_expr(ex);
4919 // Include parens in span, but only if it is a super-span.
4920 if e.span.contains(ex.span) {
4923 // Merge attributes into the inner expression.
4924 let mut attrs = e.attrs.clone();
4925 attrs.extend::<Vec<_>>(ex.attrs.into());
4930 ExprKind::Yield(ref opt_expr) => {
4931 match self.generator_kind {
4932 Some(hir::GeneratorKind::Gen) => {},
4933 Some(hir::GeneratorKind::Async) => {
4938 "`async` generators are not yet supported",
4940 self.sess.abort_if_errors();
4943 self.generator_kind = Some(hir::GeneratorKind::Gen);
4948 .map(|x| self.lower_expr(x))
4949 .unwrap_or_else(|| self.expr_unit(e.span));
4950 hir::ExprKind::Yield(P(expr), hir::YieldSource::Yield)
4953 ExprKind::Err => hir::ExprKind::Err,
4955 // Desugar `ExprForLoop`
4956 // from: `[opt_ident]: for <pat> in <head> <body>`
4957 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4961 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4963 // [opt_ident]: loop {
4965 // match ::std::iter::Iterator::next(&mut iter) {
4966 // ::std::option::Option::Some(val) => __next = val,
4967 // ::std::option::Option::None => break
4969 // let <pat> = __next;
4970 // StmtKind::Expr(<body>);
4978 let mut head = self.lower_expr(head);
4979 let head_sp = head.span;
4980 let desugared_span = self.mark_span_with_reason(
4981 DesugaringKind::ForLoop,
4985 head.span = desugared_span;
4987 let iter = Ident::with_empty_ctxt(sym::iter);
4989 let next_ident = Ident::with_empty_ctxt(sym::__next);
4990 let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
4993 hir::BindingAnnotation::Mutable,
4996 // `::std::option::Option::Some(val) => __next = val`
4998 let val_ident = Ident::with_empty_ctxt(sym::val);
4999 let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
5000 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat_hid));
5001 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat_hid));
5002 let assign = P(self.expr(
5004 hir::ExprKind::Assign(next_expr, val_expr),
5007 let some_pat = self.pat_some(pat.span, val_pat);
5008 self.arm(hir_vec![some_pat], assign)
5011 // `::std::option::Option::None => break`
5014 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
5015 let pat = self.pat_none(e.span);
5016 self.arm(hir_vec![pat], break_expr)
5020 let (iter_pat, iter_pat_nid) = self.pat_ident_binding_mode(
5023 hir::BindingAnnotation::Mutable
5026 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
5028 let iter = P(self.expr_ident(head_sp, iter, iter_pat_nid));
5029 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
5030 let next_path = &[sym::iter, sym::Iterator, sym::next];
5031 let next_expr = P(self.expr_call_std_path(
5034 hir_vec![ref_mut_iter],
5036 let arms = hir_vec![pat_arm, break_arm];
5040 hir::ExprKind::Match(
5043 hir::MatchSource::ForLoopDesugar
5048 let match_stmt = self.stmt(head_sp, hir::StmtKind::Expr(match_expr));
5050 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat_hid));
5053 let next_let = self.stmt_let_pat(
5058 hir::LocalSource::ForLoopDesugar,
5061 // `let <pat> = __next`
5062 let pat = self.lower_pat(pat);
5063 let pat_let = self.stmt_let_pat(
5068 hir::LocalSource::ForLoopDesugar,
5071 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
5072 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
5073 let body_stmt = self.stmt(body.span, hir::StmtKind::Expr(body_expr));
5075 let loop_block = P(self.block_all(
5077 hir_vec![next_let, match_stmt, pat_let, body_stmt],
5081 // `[opt_ident]: loop { ... }`
5082 let loop_expr = hir::ExprKind::Loop(
5084 self.lower_label(opt_label),
5085 hir::LoopSource::ForLoop,
5087 let loop_expr = P(hir::Expr {
5088 hir_id: self.lower_node_id(e.id),
5091 attrs: ThinVec::new(),
5094 // `mut iter => { ... }`
5095 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
5097 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
5098 let into_iter_expr = {
5099 let into_iter_path =
5100 &[sym::iter, sym::IntoIterator, sym::into_iter];
5101 P(self.expr_call_std_path(
5108 let match_expr = P(self.expr_match(
5112 hir::MatchSource::ForLoopDesugar,
5115 // This is effectively `{ let _result = ...; _result }`.
5116 // The construct was introduced in #21984.
5117 // FIXME(60253): Is this still necessary?
5118 // Also, add the attributes to the outer returned expr node.
5119 return self.expr_drop_temps(head_sp, match_expr, e.attrs.clone())
5122 // Desugar `ExprKind::Try`
5124 ExprKind::Try(ref sub_expr) => {
5127 // match Try::into_result(<expr>) {
5128 // Ok(val) => #[allow(unreachable_code)] val,
5129 // Err(err) => #[allow(unreachable_code)]
5130 // // If there is an enclosing `catch {...}`
5131 // break 'catch_target Try::from_error(From::from(err)),
5133 // return Try::from_error(From::from(err)),
5136 let unstable_span = self.mark_span_with_reason(
5137 DesugaringKind::QuestionMark,
5139 self.allow_try_trait.clone(),
5141 let try_span = self.sess.source_map().end_point(e.span);
5142 let try_span = self.mark_span_with_reason(
5143 DesugaringKind::QuestionMark,
5145 self.allow_try_trait.clone(),
5148 // `Try::into_result(<expr>)`
5151 let sub_expr = self.lower_expr(sub_expr);
5153 let path = &[sym::ops, sym::Try, sym::into_result];
5154 P(self.expr_call_std_path(
5161 // `#[allow(unreachable_code)]`
5163 // `allow(unreachable_code)`
5165 let allow_ident = Ident::with_empty_ctxt(sym::allow).with_span_pos(e.span);
5166 let uc_ident = Ident::with_empty_ctxt(sym::unreachable_code)
5167 .with_span_pos(e.span);
5168 let uc_nested = attr::mk_nested_word_item(uc_ident);
5169 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
5171 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
5173 let attrs = vec![attr];
5175 // `Ok(val) => #[allow(unreachable_code)] val,`
5177 let val_ident = Ident::with_empty_ctxt(sym::val);
5178 let (val_pat, val_pat_nid) = self.pat_ident(e.span, val_ident);
5179 let val_expr = P(self.expr_ident_with_attrs(
5183 ThinVec::from(attrs.clone()),
5185 let ok_pat = self.pat_ok(e.span, val_pat);
5187 self.arm(hir_vec![ok_pat], val_expr)
5190 // `Err(err) => #[allow(unreachable_code)]
5191 // return Try::from_error(From::from(err)),`
5193 let err_ident = Ident::with_empty_ctxt(sym::err);
5194 let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
5196 let from_path = &[sym::convert, sym::From, sym::from];
5197 let err_expr = self.expr_ident(try_span, err_ident, err_local_nid);
5198 self.expr_call_std_path(try_span, from_path, hir_vec![err_expr])
5201 self.wrap_in_try_constructor(sym::from_error, from_expr, unstable_span);
5202 let thin_attrs = ThinVec::from(attrs);
5203 let catch_scope = self.catch_scopes.last().map(|x| *x);
5204 let ret_expr = if let Some(catch_node) = catch_scope {
5205 let target_id = Ok(self.lower_node_id(catch_node));
5208 hir::ExprKind::Break(
5213 Some(from_err_expr),
5218 P(self.expr(try_span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
5221 let err_pat = self.pat_err(try_span, err_local);
5222 self.arm(hir_vec![err_pat], ret_expr)
5225 hir::ExprKind::Match(
5227 hir_vec![err_arm, ok_arm],
5228 hir::MatchSource::TryDesugar,
5232 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
5236 hir_id: self.lower_node_id(e.id),
5239 attrs: e.attrs.clone(),
5243 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
5244 smallvec![match s.node {
5245 StmtKind::Local(ref l) => {
5246 let (l, item_ids) = self.lower_local(l);
5247 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
5250 let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
5251 self.stmt(s.span, hir::StmtKind::Item(item_id))
5256 hir_id: self.lower_node_id(s.id),
5257 node: hir::StmtKind::Local(P(l)),
5263 StmtKind::Item(ref it) => {
5264 // Can only use the ID once.
5265 let mut id = Some(s.id);
5266 return self.lower_item_id(it)
5269 let hir_id = id.take()
5270 .map(|id| self.lower_node_id(id))
5271 .unwrap_or_else(|| self.next_id());
5275 node: hir::StmtKind::Item(item_id),
5281 StmtKind::Expr(ref e) => {
5283 hir_id: self.lower_node_id(s.id),
5284 node: hir::StmtKind::Expr(P(self.lower_expr(e))),
5288 StmtKind::Semi(ref e) => {
5290 hir_id: self.lower_node_id(s.id),
5291 node: hir::StmtKind::Semi(P(self.lower_expr(e))),
5295 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
5299 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
5301 CaptureBy::Value => hir::CaptureByValue,
5302 CaptureBy::Ref => hir::CaptureByRef,
5306 /// If an `explicit_owner` is given, this method allocates the `HirId` in
5307 /// the address space of that item instead of the item currently being
5308 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
5309 /// lower a `Visibility` value although we haven't lowered the owning
5310 /// `ImplItem` in question yet.
5311 fn lower_visibility(
5314 explicit_owner: Option<NodeId>,
5315 ) -> hir::Visibility {
5316 let node = match v.node {
5317 VisibilityKind::Public => hir::VisibilityKind::Public,
5318 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
5319 VisibilityKind::Restricted { ref path, id } => {
5320 debug!("lower_visibility: restricted path id = {:?}", id);
5321 let lowered_id = if let Some(owner) = explicit_owner {
5322 self.lower_node_id_with_owner(id, owner)
5324 self.lower_node_id(id)
5326 let res = self.expect_full_res(id);
5327 let res = self.lower_res(res);
5328 hir::VisibilityKind::Restricted {
5329 path: P(self.lower_path_extra(
5332 ParamMode::Explicit,
5338 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
5340 respan(v.span, node)
5343 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
5345 Defaultness::Default => hir::Defaultness::Default {
5346 has_value: has_value,
5348 Defaultness::Final => {
5350 hir::Defaultness::Final
5355 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
5357 BlockCheckMode::Default => hir::DefaultBlock,
5358 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
5362 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
5364 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
5365 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
5366 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
5367 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
5371 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
5373 CompilerGenerated => hir::CompilerGenerated,
5374 UserProvided => hir::UserProvided,
5378 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
5380 ImplPolarity::Positive => hir::ImplPolarity::Positive,
5381 ImplPolarity::Negative => hir::ImplPolarity::Negative,
5385 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
5387 TraitBoundModifier::None => hir::TraitBoundModifier::None,
5388 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
5392 // Helper methods for building HIR.
5394 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
5396 hir_id: self.next_id(),
5405 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
5407 hir_id: self.next_id(),
5411 is_shorthand: false,
5415 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
5416 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
5417 P(self.expr(span, expr_break, attrs))
5424 args: hir::HirVec<hir::Expr>,
5426 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
5429 // Note: associated functions must use `expr_call_std_path`.
5430 fn expr_call_std_path(
5433 path_components: &[Symbol],
5434 args: hir::HirVec<hir::Expr>,
5436 let path = P(self.expr_std_path(span, path_components, None, ThinVec::new()));
5437 self.expr_call(span, path, args)
5440 // Create an expression calling an associated function of an std type.
5442 // Associated functions cannot be resolved through the normal `std_path` function,
5443 // as they are resolved differently and so cannot use `expr_call_std_path`.
5445 // This function accepts the path component (`ty_path_components`) separately from
5446 // the name of the associated function (`assoc_fn_name`) in order to facilitate
5447 // separate resolution of the type and creation of a path referring to its associated
5449 fn expr_call_std_assoc_fn(
5451 ty_path_id: hir::HirId,
5453 ty_path_components: &[Symbol],
5454 assoc_fn_name: &str,
5455 args: hir::HirVec<hir::Expr>,
5456 ) -> hir::ExprKind {
5457 let ty_path = P(self.std_path(span, ty_path_components, None, false));
5458 let ty = P(self.ty_path(ty_path_id, span, hir::QPath::Resolved(None, ty_path)));
5459 let fn_seg = P(hir::PathSegment::from_ident(Ident::from_str(assoc_fn_name)));
5460 let fn_path = hir::QPath::TypeRelative(ty, fn_seg);
5461 let fn_expr = P(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
5462 hir::ExprKind::Call(fn_expr, args)
5465 fn expr_ident(&mut self, span: Span, ident: Ident, binding: hir::HirId) -> hir::Expr {
5466 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
5469 fn expr_ident_with_attrs(
5473 binding: hir::HirId,
5474 attrs: ThinVec<Attribute>,
5476 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
5480 res: Res::Local(binding),
5481 segments: hir_vec![hir::PathSegment::from_ident(ident)],
5485 self.expr(span, expr_path, attrs)
5488 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
5489 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
5495 components: &[Symbol],
5496 params: Option<P<hir::GenericArgs>>,
5497 attrs: ThinVec<Attribute>,
5499 let path = self.std_path(span, components, params, true);
5502 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
5507 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
5509 /// In terms of drop order, it has the same effect as wrapping `expr` in
5510 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
5512 /// The drop order can be important in e.g. `if expr { .. }`.
5517 attrs: ThinVec<Attribute>
5519 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
5526 arms: hir::HirVec<hir::Arm>,
5527 source: hir::MatchSource,
5529 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
5532 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
5533 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
5536 fn expr_unit(&mut self, sp: Span) -> hir::Expr {
5537 self.expr_tuple(sp, hir_vec![])
5540 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> hir::Expr {
5541 self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new())
5544 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
5546 hir_id: self.next_id(),
5553 fn stmt(&mut self, span: Span, node: hir::StmtKind) -> hir::Stmt {
5554 hir::Stmt { span, node, hir_id: self.next_id() }
5559 attrs: ThinVec<Attribute>,
5561 init: Option<P<hir::Expr>>,
5563 source: hir::LocalSource,
5565 let local = hir::Local {
5567 hir_id: self.next_id(),
5574 self.stmt(span, hir::StmtKind::Local(P(local)))
5577 fn expr_block_empty(&mut self, span: Span) -> hir::Expr {
5578 let blk = self.block_all(span, hir_vec![], None);
5579 self.expr_block(P(blk), ThinVec::new())
5582 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
5583 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
5589 stmts: hir::HirVec<hir::Stmt>,
5590 expr: Option<P<hir::Expr>>,
5595 hir_id: self.next_id(),
5596 rules: hir::DefaultBlock,
5598 targeted_by_break: false,
5602 fn expr_unsafe(&mut self, expr: P<hir::Expr>) -> hir::Expr {
5603 let hir_id = self.next_id();
5604 let span = expr.span;
5607 hir::ExprKind::Block(P(hir::Block {
5611 rules: hir::UnsafeBlock(hir::CompilerGenerated),
5613 targeted_by_break: false,
5619 /// Constructs a `true` or `false` literal expression.
5620 fn expr_bool(&mut self, span: Span, val: bool) -> hir::Expr {
5621 let lit = Spanned { span, node: LitKind::Bool(val) };
5622 self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new())
5625 /// Constructs a `true` or `false` literal pattern.
5626 fn pat_bool(&mut self, span: Span, val: bool) -> P<hir::Pat> {
5627 let expr = self.expr_bool(span, val);
5628 self.pat(span, hir::PatKind::Lit(P(expr)))
5631 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5632 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![pat])
5635 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5636 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![pat])
5639 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5640 self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![pat])
5643 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
5644 self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], hir_vec![])
5650 components: &[Symbol],
5651 subpats: hir::HirVec<P<hir::Pat>>,
5653 let path = self.std_path(span, components, None, true);
5654 let qpath = hir::QPath::Resolved(None, P(path));
5655 let pt = if subpats.is_empty() {
5656 hir::PatKind::Path(qpath)
5658 hir::PatKind::TupleStruct(qpath, subpats, None)
5663 fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<hir::Pat>, hir::HirId) {
5664 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
5667 fn pat_ident_binding_mode(
5671 bm: hir::BindingAnnotation,
5672 ) -> (P<hir::Pat>, hir::HirId) {
5673 let hir_id = self.next_id();
5678 node: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
5685 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
5686 self.pat(span, hir::PatKind::Wild)
5689 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
5691 hir_id: self.next_id(),
5697 /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when
5698 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
5699 /// The path is also resolved according to `is_value`.
5703 components: &[Symbol],
5704 params: Option<P<hir::GenericArgs>>,
5707 let (path, res) = self.resolver
5708 .resolve_str_path(span, self.crate_root, components, is_value);
5710 let mut segments: Vec<_> = path.segments.iter().map(|segment| {
5711 let res = self.expect_full_res(segment.id);
5713 ident: segment.ident,
5714 hir_id: Some(self.lower_node_id(segment.id)),
5715 res: Some(self.lower_res(res)),
5720 segments.last_mut().unwrap().args = params;
5724 res: res.map_id(|_| panic!("unexpected node_id")),
5725 segments: segments.into(),
5729 fn ty_path(&mut self, mut hir_id: hir::HirId, span: Span, qpath: hir::QPath) -> hir::Ty {
5730 let node = match qpath {
5731 hir::QPath::Resolved(None, path) => {
5732 // Turn trait object paths into `TyKind::TraitObject` instead.
5734 Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
5735 let principal = hir::PolyTraitRef {
5736 bound_generic_params: hir::HirVec::new(),
5737 trait_ref: hir::TraitRef {
5744 // The original ID is taken by the `PolyTraitRef`,
5745 // so the `Ty` itself needs a different one.
5746 hir_id = self.next_id();
5747 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
5749 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
5752 _ => hir::TyKind::Path(qpath),
5761 /// Invoked to create the lifetime argument for a type `&T`
5762 /// with no explicit lifetime.
5763 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
5764 match self.anonymous_lifetime_mode {
5765 // Intercept when we are in an impl header or async fn and introduce an in-band
5767 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
5769 AnonymousLifetimeMode::CreateParameter => {
5770 let fresh_name = self.collect_fresh_in_band_lifetime(span);
5772 hir_id: self.next_id(),
5774 name: hir::LifetimeName::Param(fresh_name),
5778 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5780 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5782 AnonymousLifetimeMode::Replace(replacement) => {
5783 self.new_replacement_lifetime(replacement, span)
5788 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
5789 /// return a "error lifetime".
5790 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
5791 let (id, msg, label) = match id {
5792 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
5795 self.sess.next_node_id(),
5796 "`&` without an explicit lifetime name cannot be used here",
5797 "explicit lifetime name needed here",
5801 let mut err = struct_span_err!(
5808 err.span_label(span, label);
5811 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5814 /// Invoked to create the lifetime argument(s) for a path like
5815 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
5816 /// sorts of cases are deprecated. This may therefore report a warning or an
5817 /// error, depending on the mode.
5818 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
5820 .map(|_| self.elided_path_lifetime(span))
5824 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
5825 match self.anonymous_lifetime_mode {
5826 AnonymousLifetimeMode::CreateParameter => {
5827 // We should have emitted E0726 when processing this path above
5828 self.sess.delay_span_bug(
5830 "expected 'implicit elided lifetime not allowed' error",
5832 let id = self.sess.next_node_id();
5833 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5835 // This is the normal case.
5836 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5838 AnonymousLifetimeMode::Replace(replacement) => {
5839 self.new_replacement_lifetime(replacement, span)
5842 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5846 /// Invoked to create the lifetime argument(s) for an elided trait object
5847 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
5848 /// when the bound is written, even if it is written with `'_` like in
5849 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
5850 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
5851 match self.anonymous_lifetime_mode {
5852 // NB. We intentionally ignore the create-parameter mode here.
5853 // and instead "pass through" to resolve-lifetimes, which will apply
5854 // the object-lifetime-defaulting rules. Elided object lifetime defaults
5855 // do not act like other elided lifetimes. In other words, given this:
5857 // impl Foo for Box<dyn Debug>
5859 // we do not introduce a fresh `'_` to serve as the bound, but instead
5860 // ultimately translate to the equivalent of:
5862 // impl Foo for Box<dyn Debug + 'static>
5864 // `resolve_lifetime` has the code to make that happen.
5865 AnonymousLifetimeMode::CreateParameter => {}
5867 AnonymousLifetimeMode::ReportError => {
5868 // ReportError applies to explicit use of `'_`.
5871 // This is the normal case.
5872 AnonymousLifetimeMode::PassThrough => {}
5874 // We don't need to do any replacement here as this lifetime
5875 // doesn't refer to an elided lifetime elsewhere in the function
5877 AnonymousLifetimeMode::Replace(_) => {}
5880 self.new_implicit_lifetime(span)
5883 fn new_replacement_lifetime(
5885 replacement: LtReplacement,
5887 ) -> hir::Lifetime {
5888 let hir_id = self.next_id();
5889 self.replace_elided_lifetime(hir_id, span, replacement)
5892 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
5894 hir_id: self.next_id(),
5896 name: hir::LifetimeName::Implicit,
5900 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
5901 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
5902 // call site which do not have a macro backtrace. See #61963.
5903 let is_macro_callsite = self.sess.source_map()
5904 .span_to_snippet(span)
5905 .map(|snippet| snippet.starts_with("#["))
5907 if !is_macro_callsite {
5908 self.sess.buffer_lint_with_diagnostic(
5909 builtin::BARE_TRAIT_OBJECTS,
5912 "trait objects without an explicit `dyn` are deprecated",
5913 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
5918 fn wrap_in_try_constructor(
5922 unstable_span: Span,
5924 let path = &[sym::ops, sym::Try, method];
5925 let from_err = P(self.expr_std_path(unstable_span, path, None,
5927 P(self.expr_call(e.span, from_err, hir_vec![e]))
5934 ) -> hir::ExprKind {
5938 // let mut pinned = <expr>;
5940 // match ::std::future::poll_with_tls_context(unsafe {
5941 // ::std::pin::Pin::new_unchecked(&mut pinned)
5943 // ::std::task::Poll::Ready(result) => break result,
5944 // ::std::task::Poll::Pending => {},
5949 match self.generator_kind {
5950 Some(hir::GeneratorKind::Async) => {},
5951 Some(hir::GeneratorKind::Gen) |
5953 let mut err = struct_span_err!(
5957 "`await` is only allowed inside `async` functions and blocks"
5959 err.span_label(await_span, "only allowed inside `async` functions and blocks");
5960 if let Some(item_sp) = self.current_item {
5961 err.span_label(item_sp, "this is not `async`");
5966 let span = self.mark_span_with_reason(
5967 DesugaringKind::Await,
5971 let gen_future_span = self.mark_span_with_reason(
5972 DesugaringKind::Await,
5974 self.allow_gen_future.clone(),
5977 // let mut pinned = <expr>;
5978 let expr = P(self.lower_expr(expr));
5979 let pinned_ident = Ident::with_empty_ctxt(sym::pinned);
5980 let (pinned_pat, pinned_pat_hid) = self.pat_ident_binding_mode(
5983 hir::BindingAnnotation::Mutable,
5985 let pinned_let = self.stmt_let_pat(
5990 hir::LocalSource::AwaitDesugar,
5993 // ::std::future::poll_with_tls_context(unsafe {
5994 // ::std::pin::Pin::new_unchecked(&mut pinned)
5997 let pinned = P(self.expr_ident(span, pinned_ident, pinned_pat_hid));
5998 let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
5999 let pin_ty_id = self.next_id();
6000 let new_unchecked_expr_kind = self.expr_call_std_assoc_fn(
6003 &[sym::pin, sym::Pin],
6005 hir_vec![ref_mut_pinned],
6007 let new_unchecked = P(self.expr(span, new_unchecked_expr_kind, ThinVec::new()));
6008 let unsafe_expr = self.expr_unsafe(new_unchecked);
6009 P(self.expr_call_std_path(
6011 &[sym::future, sym::poll_with_tls_context],
6012 hir_vec![unsafe_expr],
6016 // `::std::task::Poll::Ready(result) => break result`
6017 let loop_node_id = self.sess.next_node_id();
6018 let loop_hir_id = self.lower_node_id(loop_node_id);
6020 let x_ident = Ident::with_empty_ctxt(sym::result);
6021 let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
6022 let x_expr = P(self.expr_ident(span, x_ident, x_pat_hid));
6023 let ready_pat = self.pat_std_enum(
6025 &[sym::task, sym::Poll, sym::Ready],
6028 let break_x = self.with_loop_scope(loop_node_id, |this| {
6029 let expr_break = hir::ExprKind::Break(
6030 this.lower_loop_destination(None),
6033 P(this.expr(await_span, expr_break, ThinVec::new()))
6035 self.arm(hir_vec![ready_pat], break_x)
6038 // `::std::task::Poll::Pending => {}`
6040 let pending_pat = self.pat_std_enum(
6042 &[sym::task, sym::Poll, sym::Pending],
6045 let empty_block = P(self.expr_block_empty(span));
6046 self.arm(hir_vec![pending_pat], empty_block)
6050 let match_expr = P(self.expr_match(
6053 hir_vec![ready_arm, pending_arm],
6054 hir::MatchSource::AwaitDesugar,
6056 self.stmt(span, hir::StmtKind::Expr(match_expr))
6060 let unit = self.expr_unit(span);
6061 let yield_expr = P(self.expr(
6063 hir::ExprKind::Yield(P(unit), hir::YieldSource::Await),
6066 self.stmt(span, hir::StmtKind::Expr(yield_expr))
6069 let loop_block = P(self.block_all(
6071 hir_vec![match_stmt, yield_stmt],
6075 let loop_expr = P(hir::Expr {
6076 hir_id: loop_hir_id,
6077 node: hir::ExprKind::Loop(
6080 hir::LoopSource::Loop,
6083 attrs: ThinVec::new(),
6086 hir::ExprKind::Block(
6087 P(self.block_all(span, hir_vec![pinned_let], Some(loop_expr))),
6093 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
6094 // Sorting by span ensures that we get things in order within a
6095 // file, and also puts the files in a sensible order.
6096 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
6097 body_ids.sort_by_key(|b| bodies[b].value.span);
6101 /// Checks if the specified expression is a built-in range literal.
6102 /// (See: `LoweringContext::lower_expr()`).
6103 pub fn is_range_literal(sess: &Session, expr: &hir::Expr) -> bool {
6104 use hir::{Path, QPath, ExprKind, TyKind};
6106 // Returns whether the given path represents a (desugared) range,
6107 // either in std or core, i.e. has either a `::std::ops::Range` or
6108 // `::core::ops::Range` prefix.
6109 fn is_range_path(path: &Path) -> bool {
6110 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.as_str().to_string()).collect();
6111 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
6113 // "{{root}}" is the equivalent of `::` prefix in `Path`.
6114 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
6115 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
6121 // Check whether a span corresponding to a range expression is a
6122 // range literal, rather than an explicit struct or `new()` call.
6123 fn is_lit(sess: &Session, span: &Span) -> bool {
6124 let source_map = sess.source_map();
6125 let end_point = source_map.end_point(*span);
6127 if let Ok(end_string) = source_map.span_to_snippet(end_point) {
6128 !(end_string.ends_with("}") || end_string.ends_with(")"))
6135 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
6136 ExprKind::Struct(ref qpath, _, _) => {
6137 if let QPath::Resolved(None, ref path) = **qpath {
6138 return is_range_path(&path) && is_lit(sess, &expr.span);
6142 // `..` desugars to its struct path.
6143 ExprKind::Path(QPath::Resolved(None, ref path)) => {
6144 return is_range_path(&path) && is_lit(sess, &expr.span);
6147 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
6148 ExprKind::Call(ref func, _) => {
6149 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.node {
6150 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.node {
6151 let new_call = segment.ident.as_str() == "new";
6152 return is_range_path(&path) && is_lit(sess, &expr.span) && new_call;