1 // ignore-tidy-filelength
3 //! Lowers the AST to the HIR.
5 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
6 //! much like a fold. Where lowering involves a bit more work things get more
7 //! interesting and there are some invariants you should know about. These mostly
8 //! concern spans and IDs.
10 //! Spans are assigned to AST nodes during parsing and then are modified during
11 //! expansion to indicate the origin of a node and the process it went through
12 //! being expanded. IDs are assigned to AST nodes just before lowering.
14 //! For the simpler lowering steps, IDs and spans should be preserved. Unlike
15 //! expansion we do not preserve the process of lowering in the spans, so spans
16 //! should not be modified here. When creating a new node (as opposed to
17 //! 'folding' an existing one), then you create a new ID using `next_id()`.
19 //! You must ensure that IDs are unique. That means that you should only use the
20 //! ID from an AST node in a single HIR node (you can assume that AST node-IDs
21 //! are unique). Every new node must have a unique ID. Avoid cloning HIR nodes.
22 //! If you do, you must then set the new node's ID to a fresh one.
24 //! Spans are used for error messages and for tools to map semantics back to
25 //! source code. It is therefore not as important with spans as IDs to be strict
26 //! about use (you can't break the compiler by screwing up a span). Obviously, a
27 //! HIR node can only have a single span. But multiple nodes can have the same
28 //! span and spans don't need to be kept in order, etc. Where code is preserved
29 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
30 //! new it is probably best to give a span for the whole AST node being lowered.
31 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
32 //! get confused if the spans from leaf AST nodes occur in multiple places
33 //! in the HIR, especially for multiple identifiers.
35 use crate::dep_graph::DepGraph;
36 use crate::hir::{self, ParamName};
37 use crate::hir::HirVec;
38 use crate::hir::map::{DefKey, DefPathData, Definitions};
39 use crate::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
40 use crate::hir::def::{Res, DefKind, PartialRes, PerNS};
41 use crate::hir::{GenericArg, ConstArg};
42 use crate::lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
43 ELIDED_LIFETIMES_IN_PATHS};
44 use crate::middle::cstore::CrateStore;
45 use crate::session::Session;
46 use crate::session::config::nightly_options;
47 use crate::util::common::FN_OUTPUT_NAME;
48 use crate::util::nodemap::{DefIdMap, NodeMap};
49 use errors::Applicability;
50 use rustc_data_structures::fx::FxHashSet;
51 use rustc_data_structures::indexed_vec::IndexVec;
52 use rustc_data_structures::thin_vec::ThinVec;
53 use rustc_data_structures::sync::Lrc;
55 use std::collections::{BTreeSet, BTreeMap};
57 use smallvec::SmallVec;
62 use syntax::ext::hygiene::{Mark, SyntaxContext};
63 use syntax::print::pprust;
65 use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned};
66 use syntax::source_map::CompilerDesugaringKind::IfTemporary;
67 use syntax::std_inject;
68 use syntax::symbol::{kw, sym, Symbol};
69 use syntax::tokenstream::{TokenStream, TokenTree};
70 use syntax::parse::token::{self, TokenKind};
71 use syntax::visit::{self, Visitor};
72 use syntax_pos::{DUMMY_SP, edition, Span};
74 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
76 pub struct LoweringContext<'a> {
77 crate_root: Option<Symbol>,
79 /// Used to assign ids to HIR nodes that do not directly correspond to an AST node.
82 cstore: &'a dyn CrateStore,
84 resolver: &'a mut dyn Resolver,
86 /// The items being lowered are collected here.
87 items: BTreeMap<hir::HirId, hir::Item>,
89 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
90 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
91 bodies: BTreeMap<hir::BodyId, hir::Body>,
92 exported_macros: Vec<hir::MacroDef>,
94 trait_impls: BTreeMap<DefId, Vec<hir::HirId>>,
96 modules: BTreeMap<NodeId, hir::ModuleItems>,
101 /// Used to get the current `fn`'s def span to point to when using `await`
102 /// outside of an `async fn`.
103 current_item: Option<Span>,
105 catch_scopes: Vec<NodeId>,
106 loop_scopes: Vec<NodeId>,
107 is_in_loop_condition: bool,
108 is_in_trait_impl: bool,
109 is_in_dyn_type: bool,
111 /// What to do when we encounter either an "anonymous lifetime
112 /// reference". The term "anonymous" is meant to encompass both
113 /// `'_` lifetimes as well as fully elided cases where nothing is
114 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
115 anonymous_lifetime_mode: AnonymousLifetimeMode,
117 /// Used to create lifetime definitions from in-band lifetime usages.
118 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
119 /// When a named lifetime is encountered in a function or impl header and
120 /// has not been defined
121 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
122 /// to this list. The results of this list are then added to the list of
123 /// lifetime definitions in the corresponding impl or function generics.
124 lifetimes_to_define: Vec<(Span, ParamName)>,
126 /// Whether or not in-band lifetimes are being collected. This is used to
127 /// indicate whether or not we're in a place where new lifetimes will result
128 /// in in-band lifetime definitions, such a function or an impl header,
129 /// including implicit lifetimes from `impl_header_lifetime_elision`.
130 is_collecting_in_band_lifetimes: bool,
132 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
133 /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
134 /// against this list to see if it is already in-scope, or if a definition
135 /// needs to be created for it.
136 in_scope_lifetimes: Vec<Ident>,
138 current_module: NodeId,
140 type_def_lifetime_params: DefIdMap<usize>,
142 current_hir_id_owner: Vec<(DefIndex, u32)>,
143 item_local_id_counters: NodeMap<u32>,
144 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
148 /// Resolve a path generated by the lowerer when expanding `for`, `if let`, etc.
155 /// Obtain resolution for a `NodeId` with a single resolution.
156 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
158 /// Obtain per-namespace resolutions for `use` statement with the given `NoedId`.
159 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
161 /// Obtain resolution for a label with the given `NodeId`.
162 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
164 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
165 /// This should only return `None` during testing.
166 fn definitions(&mut self) -> &mut Definitions;
168 /// Given suffix `["b", "c", "d"]`, creates a HIR path for `[::crate_root]::b::c::d` and
169 /// resolves it based on `is_value`.
173 crate_root: Option<Symbol>,
174 components: &[Symbol],
179 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
180 /// and if so, what meaning it has.
182 enum ImplTraitContext<'a> {
183 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
184 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
185 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
187 /// Newly generated parameters should be inserted into the given `Vec`.
188 Universal(&'a mut Vec<hir::GenericParam>),
190 /// Treat `impl Trait` as shorthand for a new existential parameter.
191 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
192 /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
194 /// We optionally store a `DefId` for the parent item here so we can look up necessary
195 /// information later. It is `None` when no information about the context should be stored
196 /// (e.g., for consts and statics).
197 Existential(Option<DefId> /* fn def-ID */),
199 /// `impl Trait` is not accepted in this position.
200 Disallowed(ImplTraitPosition),
203 /// Position in which `impl Trait` is disallowed.
204 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
205 enum ImplTraitPosition {
206 /// Disallowed in `let` / `const` / `static` bindings.
209 /// All other posiitons.
213 impl<'a> ImplTraitContext<'a> {
215 fn disallowed() -> Self {
216 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
219 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
220 use self::ImplTraitContext::*;
222 Universal(params) => Universal(params),
223 Existential(fn_def_id) => Existential(*fn_def_id),
224 Disallowed(pos) => Disallowed(*pos),
231 cstore: &dyn CrateStore,
232 dep_graph: &DepGraph,
234 resolver: &mut dyn Resolver,
236 // We're constructing the HIR here; we don't care what we will
237 // read, since we haven't even constructed the *input* to
239 dep_graph.assert_ignored();
242 crate_root: std_inject::injected_crate_name().map(Symbol::intern),
246 items: BTreeMap::new(),
247 trait_items: BTreeMap::new(),
248 impl_items: BTreeMap::new(),
249 bodies: BTreeMap::new(),
250 trait_impls: BTreeMap::new(),
251 modules: BTreeMap::new(),
252 exported_macros: Vec::new(),
253 catch_scopes: Vec::new(),
254 loop_scopes: Vec::new(),
255 is_in_loop_condition: false,
256 is_in_trait_impl: false,
257 is_in_dyn_type: false,
258 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
259 type_def_lifetime_params: Default::default(),
260 current_module: CRATE_NODE_ID,
261 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
262 item_local_id_counters: Default::default(),
263 node_id_to_hir_id: IndexVec::new(),
265 is_async_body: false,
267 lifetimes_to_define: Vec::new(),
268 is_collecting_in_band_lifetimes: false,
269 in_scope_lifetimes: Vec::new(),
273 #[derive(Copy, Clone, PartialEq)]
275 /// Any path in a type context.
277 /// The `module::Type` in `module::Type::method` in an expression.
281 enum ParenthesizedGenericArgs {
287 /// What to do when we encounter an **anonymous** lifetime
288 /// reference. Anonymous lifetime references come in two flavors. You
289 /// have implicit, or fully elided, references to lifetimes, like the
290 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
291 /// or `Ref<'_, T>`. These often behave the same, but not always:
293 /// - certain usages of implicit references are deprecated, like
294 /// `Ref<T>`, and we sometimes just give hard errors in those cases
296 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
297 /// the same as `Box<dyn Foo + '_>`.
299 /// We describe the effects of the various modes in terms of three cases:
301 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
302 /// of a `&` (e.g., the missing lifetime in something like `&T`)
303 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
304 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
305 /// elided bounds follow special rules. Note that this only covers
306 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
307 /// '_>` is a case of "modern" elision.
308 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
309 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
310 /// non-deprecated equivalent.
312 /// Currently, the handling of lifetime elision is somewhat spread out
313 /// between HIR lowering and -- as described below -- the
314 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
315 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
316 /// everything into HIR lowering.
317 #[derive(Copy, Clone)]
318 enum AnonymousLifetimeMode {
319 /// For **Modern** cases, create a new anonymous region parameter
320 /// and reference that.
322 /// For **Dyn Bound** cases, pass responsibility to
323 /// `resolve_lifetime` code.
325 /// For **Deprecated** cases, report an error.
328 /// Give a hard error when either `&` or `'_` is written. Used to
329 /// rule out things like `where T: Foo<'_>`. Does not imply an
330 /// error on default object bounds (e.g., `Box<dyn Foo>`).
333 /// Pass responsibility to `resolve_lifetime` code for all cases.
336 /// Used in the return types of `async fn` where there exists
337 /// exactly one argument-position elided lifetime.
339 /// In `async fn`, we lower the arguments types using the `CreateParameter`
340 /// mode, meaning that non-`dyn` elided lifetimes are assigned a fresh name.
341 /// If any corresponding elided lifetimes appear in the output, we need to
342 /// replace them with references to the fresh name assigned to the corresponding
343 /// elided lifetime in the arguments.
345 /// For **Modern cases**, replace the anonymous parameter with a
346 /// reference to a specific freshly-named lifetime that was
347 /// introduced in argument
349 /// For **Dyn Bound** cases, pass responsibility to
350 /// `resole_lifetime` code.
351 Replace(LtReplacement),
354 /// The type of elided lifetime replacement to perform on `async fn` return types.
355 #[derive(Copy, Clone)]
357 /// Fresh name introduced by the single non-dyn elided lifetime
358 /// in the arguments of the async fn.
361 /// There is no single non-dyn elided lifetime because no lifetimes
362 /// appeared in the arguments.
365 /// There is no single non-dyn elided lifetime because multiple
366 /// lifetimes appeared in the arguments.
370 /// Calculates the `LtReplacement` to use for elided lifetimes in the return
371 /// type based on the fresh elided lifetimes introduced in argument position.
372 fn get_elided_lt_replacement(arg_position_lifetimes: &[(Span, ParamName)]) -> LtReplacement {
373 match arg_position_lifetimes {
374 [] => LtReplacement::NoLifetimes,
375 [(_span, param)] => LtReplacement::Some(*param),
376 _ => LtReplacement::MultipleLifetimes,
380 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[NodeId; 1]> }
382 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
383 fn visit_ty(&mut self, ty: &'a Ty) {
389 TyKind::ImplTrait(id, _) => self.ids.push(id),
392 visit::walk_ty(self, ty);
395 fn visit_path_segment(
398 path_segment: &'v PathSegment,
400 if let Some(ref p) = path_segment.args {
401 if let GenericArgs::Parenthesized(_) = **p {
405 visit::walk_path_segment(self, path_span, path_segment)
409 impl<'a> LoweringContext<'a> {
410 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
411 /// Full-crate AST visitor that inserts into a fresh
412 /// `LoweringContext` any information that may be
413 /// needed from arbitrary locations in the crate,
414 /// e.g., the number of lifetime generic parameters
415 /// declared for every type and trait definition.
416 struct MiscCollector<'lcx, 'interner: 'lcx> {
417 lctx: &'lcx mut LoweringContext<'interner>,
418 hir_id_owner: Option<NodeId>,
421 impl MiscCollector<'_, '_> {
422 fn allocate_use_tree_hir_id_counters(
428 UseTreeKind::Simple(_, id1, id2) => {
429 for &id in &[id1, id2] {
430 self.lctx.resolver.definitions().create_def_with_parent(
437 self.lctx.allocate_hir_id_counter(id);
440 UseTreeKind::Glob => (),
441 UseTreeKind::Nested(ref trees) => {
442 for &(ref use_tree, id) in trees {
443 let hir_id = self.lctx.allocate_hir_id_counter(id);
444 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
450 fn with_hir_id_owner<F, T>(&mut self, owner: Option<NodeId>, f: F) -> T
452 F: FnOnce(&mut Self) -> T,
454 let old = mem::replace(&mut self.hir_id_owner, owner);
456 self.hir_id_owner = old;
461 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
462 fn visit_pat(&mut self, p: &'lcx Pat) {
464 // Doesn't generate a HIR node
465 PatKind::Paren(..) => {},
467 if let Some(owner) = self.hir_id_owner {
468 self.lctx.lower_node_id_with_owner(p.id, owner);
473 visit::walk_pat(self, p)
476 fn visit_item(&mut self, item: &'lcx Item) {
477 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
480 ItemKind::Struct(_, ref generics)
481 | ItemKind::Union(_, ref generics)
482 | ItemKind::Enum(_, ref generics)
483 | ItemKind::Ty(_, ref generics)
484 | ItemKind::Existential(_, ref generics)
485 | ItemKind::Trait(_, _, ref generics, ..) => {
486 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
490 .filter(|param| match param.kind {
491 ast::GenericParamKind::Lifetime { .. } => true,
495 self.lctx.type_def_lifetime_params.insert(def_id, count);
497 ItemKind::Use(ref use_tree) => {
498 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
503 self.with_hir_id_owner(Some(item.id), |this| {
504 visit::walk_item(this, item);
508 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
509 self.lctx.allocate_hir_id_counter(item.id);
512 TraitItemKind::Method(_, None) => {
513 // Ignore patterns in trait methods without bodies
514 self.with_hir_id_owner(None, |this| {
515 visit::walk_trait_item(this, item)
518 _ => self.with_hir_id_owner(Some(item.id), |this| {
519 visit::walk_trait_item(this, item);
524 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
525 self.lctx.allocate_hir_id_counter(item.id);
526 self.with_hir_id_owner(Some(item.id), |this| {
527 visit::walk_impl_item(this, item);
531 fn visit_foreign_item(&mut self, i: &'lcx ForeignItem) {
532 // Ignore patterns in foreign items
533 self.with_hir_id_owner(None, |this| {
534 visit::walk_foreign_item(this, i)
538 fn visit_ty(&mut self, t: &'lcx Ty) {
540 // Mirrors the case in visit::walk_ty
541 TyKind::BareFn(ref f) => {
547 // Mirrors visit::walk_fn_decl
548 for argument in &f.decl.inputs {
549 // We don't lower the ids of argument patterns
550 self.with_hir_id_owner(None, |this| {
551 this.visit_pat(&argument.pat);
553 self.visit_ty(&argument.ty)
555 self.visit_fn_ret_ty(&f.decl.output)
557 _ => visit::walk_ty(self, t),
562 struct ItemLowerer<'lcx, 'interner: 'lcx> {
563 lctx: &'lcx mut LoweringContext<'interner>,
566 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
567 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
569 F: FnOnce(&mut Self),
571 let old = self.lctx.is_in_trait_impl;
572 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
578 self.lctx.is_in_trait_impl = old;
582 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
583 fn visit_mod(&mut self, m: &'lcx Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
584 self.lctx.modules.insert(n, hir::ModuleItems {
585 items: BTreeSet::new(),
586 trait_items: BTreeSet::new(),
587 impl_items: BTreeSet::new(),
590 let old = self.lctx.current_module;
591 self.lctx.current_module = n;
592 visit::walk_mod(self, m);
593 self.lctx.current_module = old;
596 fn visit_item(&mut self, item: &'lcx Item) {
597 let mut item_hir_id = None;
598 self.lctx.with_hir_id_owner(item.id, |lctx| {
599 if let Some(hir_item) = lctx.lower_item(item) {
600 item_hir_id = Some(hir_item.hir_id);
601 lctx.insert_item(hir_item);
605 if let Some(hir_id) = item_hir_id {
606 let item_generics = match self.lctx.items.get(&hir_id).unwrap().node {
607 hir::ItemKind::Impl(_, _, _, ref generics, ..)
608 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
609 generics.params.clone()
614 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
615 let this = &mut ItemLowerer { lctx: this };
616 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
617 this.with_trait_impl_ref(opt_trait_ref, |this| {
618 visit::walk_item(this, item)
621 visit::walk_item(this, item);
627 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
628 self.lctx.with_hir_id_owner(item.id, |lctx| {
629 let hir_item = lctx.lower_trait_item(item);
630 let id = hir::TraitItemId { hir_id: hir_item.hir_id };
631 lctx.trait_items.insert(id, hir_item);
632 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
635 visit::walk_trait_item(self, item);
638 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
639 self.lctx.with_hir_id_owner(item.id, |lctx| {
640 let hir_item = lctx.lower_impl_item(item);
641 let id = hir::ImplItemId { hir_id: hir_item.hir_id };
642 lctx.impl_items.insert(id, hir_item);
643 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
645 visit::walk_impl_item(self, item);
649 self.lower_node_id(CRATE_NODE_ID);
650 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
652 visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
653 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
655 let module = self.lower_mod(&c.module);
656 let attrs = self.lower_attrs(&c.attrs);
657 let body_ids = body_ids(&self.bodies);
661 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
667 exported_macros: hir::HirVec::from(self.exported_macros),
669 trait_items: self.trait_items,
670 impl_items: self.impl_items,
673 trait_impls: self.trait_impls,
674 modules: self.modules,
678 fn insert_item(&mut self, item: hir::Item) {
679 let id = item.hir_id;
680 // FIXME: Use `debug_asset-rt`.
681 assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
682 self.items.insert(id, item);
683 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
686 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
687 // Set up the counter if needed.
688 self.item_local_id_counters.entry(owner).or_insert(0);
689 // Always allocate the first `HirId` for the owner itself.
690 let lowered = self.lower_node_id_with_owner(owner, owner);
691 debug_assert_eq!(lowered.local_id.as_u32(), 0);
695 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> hir::HirId
697 F: FnOnce(&mut Self) -> hir::HirId,
699 if ast_node_id == DUMMY_NODE_ID {
700 return hir::DUMMY_HIR_ID;
703 let min_size = ast_node_id.as_usize() + 1;
705 if min_size > self.node_id_to_hir_id.len() {
706 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
709 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
711 if existing_hir_id == hir::DUMMY_HIR_ID {
712 // Generate a new `HirId`.
713 let hir_id = alloc_hir_id(self);
714 self.node_id_to_hir_id[ast_node_id] = hir_id;
722 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
724 F: FnOnce(&mut Self) -> T,
726 let counter = self.item_local_id_counters
727 .insert(owner, HIR_ID_COUNTER_LOCKED)
728 .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
729 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
730 self.current_hir_id_owner.push((def_index, counter));
732 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
734 debug_assert!(def_index == new_def_index);
735 debug_assert!(new_counter >= counter);
737 let prev = self.item_local_id_counters
738 .insert(owner, new_counter)
740 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
744 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
745 /// the `LoweringContext`'s `NodeId => HirId` map.
746 /// Take care not to call this method if the resulting `HirId` is then not
747 /// actually used in the HIR, as that would trigger an assertion in the
748 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
749 /// properly. Calling the method twice with the same `NodeId` is fine though.
750 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
751 self.lower_node_id_generic(ast_node_id, |this| {
752 let &mut (def_index, ref mut local_id_counter) =
753 this.current_hir_id_owner.last_mut().unwrap();
754 let local_id = *local_id_counter;
755 *local_id_counter += 1;
758 local_id: hir::ItemLocalId::from_u32(local_id),
763 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
764 self.lower_node_id_generic(ast_node_id, |this| {
765 let local_id_counter = this
766 .item_local_id_counters
768 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
769 let local_id = *local_id_counter;
771 // We want to be sure not to modify the counter in the map while it
772 // is also on the stack. Otherwise we'll get lost updates when writing
773 // back from the stack to the map.
774 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
776 *local_id_counter += 1;
780 .opt_def_index(owner)
781 .expect("you forgot to call `create_def_with_parent` or are lowering node-IDs \
782 that do not belong to the current owner");
786 local_id: hir::ItemLocalId::from_u32(local_id),
791 fn record_body(&mut self, arguments: HirVec<hir::Arg>, value: hir::Expr) -> hir::BodyId {
792 if self.is_generator && self.is_async_body {
797 "`async` generators are not yet supported",
799 self.sess.abort_if_errors();
801 let body = hir::Body {
802 is_generator: self.is_generator || self.is_async_body,
807 self.bodies.insert(id, body);
811 fn next_id(&mut self) -> hir::HirId {
812 self.lower_node_id(self.sess.next_node_id())
815 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
817 self.lower_node_id_generic(id, |_| {
818 panic!("expected node_id to be lowered already for res {:#?}", res)
823 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
824 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
825 if pr.unresolved_segments() != 0 {
826 bug!("path not fully resolved: {:?}", pr);
832 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
833 self.resolver.get_import_res(id).present_items()
836 fn diagnostic(&self) -> &errors::Handler {
837 self.sess.diagnostic()
840 /// Reuses the span but adds information like the kind of the desugaring and features that are
841 /// allowed inside this span.
842 fn mark_span_with_reason(
844 reason: CompilerDesugaringKind,
846 allow_internal_unstable: Option<Lrc<[Symbol]>>,
848 let mark = Mark::fresh(Mark::root());
849 mark.set_expn_info(source_map::ExpnInfo {
851 def_site: Some(span),
852 format: source_map::CompilerDesugaring(reason),
853 allow_internal_unstable,
854 allow_internal_unsafe: false,
855 local_inner_macros: false,
856 edition: edition::Edition::from_session(),
858 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
861 fn with_anonymous_lifetime_mode<R>(
863 anonymous_lifetime_mode: AnonymousLifetimeMode,
864 op: impl FnOnce(&mut Self) -> R,
866 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
867 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
868 let result = op(self);
869 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
873 /// Creates a new `hir::GenericParam` for every new lifetime and
874 /// type parameter encountered while evaluating `f`. Definitions
875 /// are created with the parent provided. If no `parent_id` is
876 /// provided, no definitions will be returned.
878 /// Presuming that in-band lifetimes are enabled, then
879 /// `self.anonymous_lifetime_mode` will be updated to match the
880 /// argument while `f` is running (and restored afterwards).
881 fn collect_in_band_defs<T, F>(
884 anonymous_lifetime_mode: AnonymousLifetimeMode,
886 ) -> (Vec<hir::GenericParam>, T)
888 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
890 assert!(!self.is_collecting_in_band_lifetimes);
891 assert!(self.lifetimes_to_define.is_empty());
892 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
894 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
895 self.is_collecting_in_band_lifetimes = true;
897 let (in_band_ty_params, res) = f(self);
899 self.is_collecting_in_band_lifetimes = false;
900 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
902 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
904 let params = lifetimes_to_define
906 .map(|(span, hir_name)| self.lifetime_to_generic_param(
907 span, hir_name, parent_id.index,
909 .chain(in_band_ty_params.into_iter())
915 /// Converts a lifetime into a new generic parameter.
916 fn lifetime_to_generic_param(
920 parent_index: DefIndex,
921 ) -> hir::GenericParam {
922 let node_id = self.sess.next_node_id();
924 // Get the name we'll use to make the def-path. Note
925 // that collisions are ok here and this shouldn't
926 // really show up for end-user.
927 let (str_name, kind) = match hir_name {
928 ParamName::Plain(ident) => (
929 ident.as_interned_str(),
930 hir::LifetimeParamKind::InBand,
932 ParamName::Fresh(_) => (
933 kw::UnderscoreLifetime.as_interned_str(),
934 hir::LifetimeParamKind::Elided,
936 ParamName::Error => (
937 kw::UnderscoreLifetime.as_interned_str(),
938 hir::LifetimeParamKind::Error,
942 // Add a definition for the in-band lifetime def.
943 self.resolver.definitions().create_def_with_parent(
946 DefPathData::LifetimeNs(str_name),
952 hir_id: self.lower_node_id(node_id),
957 pure_wrt_drop: false,
958 kind: hir::GenericParamKind::Lifetime { kind }
962 /// When there is a reference to some lifetime `'a`, and in-band
963 /// lifetimes are enabled, then we want to push that lifetime into
964 /// the vector of names to define later. In that case, it will get
965 /// added to the appropriate generics.
966 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
967 if !self.is_collecting_in_band_lifetimes {
971 if !self.sess.features_untracked().in_band_lifetimes {
975 if self.in_scope_lifetimes.contains(&ident.modern()) {
979 let hir_name = ParamName::Plain(ident);
981 if self.lifetimes_to_define.iter()
982 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
986 self.lifetimes_to_define.push((ident.span, hir_name));
989 /// When we have either an elided or `'_` lifetime in an impl
990 /// header, we convert it to an in-band lifetime.
991 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
992 assert!(self.is_collecting_in_band_lifetimes);
993 let index = self.lifetimes_to_define.len();
994 let hir_name = ParamName::Fresh(index);
995 self.lifetimes_to_define.push((span, hir_name));
999 // Evaluates `f` with the lifetimes in `params` in-scope.
1000 // This is used to track which lifetimes have already been defined, and
1001 // which are new in-band lifetimes that need to have a definition created
1003 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
1005 F: FnOnce(&mut LoweringContext<'_>) -> T,
1007 let old_len = self.in_scope_lifetimes.len();
1008 let lt_def_names = params.iter().filter_map(|param| match param.kind {
1009 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
1012 self.in_scope_lifetimes.extend(lt_def_names);
1016 self.in_scope_lifetimes.truncate(old_len);
1020 // Same as the method above, but accepts `hir::GenericParam`s
1021 // instead of `ast::GenericParam`s.
1022 // This should only be used with generics that have already had their
1023 // in-band lifetimes added. In practice, this means that this function is
1024 // only used when lowering a child item of a trait or impl.
1025 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
1026 params: &HirVec<hir::GenericParam>,
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 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
1036 self.in_scope_lifetimes.extend(lt_def_names);
1040 self.in_scope_lifetimes.truncate(old_len);
1044 /// Appends in-band lifetime defs and argument-position `impl
1045 /// Trait` defs to the existing set of generics.
1047 /// Presuming that in-band lifetimes are enabled, then
1048 /// `self.anonymous_lifetime_mode` will be updated to match the
1049 /// argument while `f` is running (and restored afterwards).
1050 fn add_in_band_defs<F, T>(
1052 generics: &Generics,
1054 anonymous_lifetime_mode: AnonymousLifetimeMode,
1056 ) -> (hir::Generics, T)
1058 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
1060 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
1063 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
1064 let mut params = Vec::new();
1065 // Note: it is necessary to lower generics *before* calling `f`.
1066 // When lowering `async fn`, there's a final step when lowering
1067 // the return type that assumes that all in-scope lifetimes have
1068 // already been added to either `in_scope_lifetimes` or
1069 // `lifetimes_to_define`. If we swapped the order of these two,
1070 // in-band-lifetimes introduced by generics or where-clauses
1071 // wouldn't have been added yet.
1072 let generics = this.lower_generics(
1074 ImplTraitContext::Universal(&mut params),
1076 let res = f(this, &mut params);
1077 (params, (generics, res))
1082 lowered_generics.params = lowered_generics
1086 .chain(in_band_defs)
1089 // FIXME(const_generics): the compiler doesn't always cope with
1090 // unsorted generic parameters at the moment, so we make sure
1091 // that they're ordered correctly here for now. (When we chain
1092 // the `in_band_defs`, we might make the order unsorted.)
1093 lowered_generics.params.sort_by_key(|param| {
1095 hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime,
1096 hir::GenericParamKind::Type { .. } => ParamKindOrd::Type,
1097 hir::GenericParamKind::Const { .. } => ParamKindOrd::Const,
1101 (lowered_generics, res)
1104 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
1106 F: FnOnce(&mut LoweringContext<'_>) -> T,
1108 let len = self.catch_scopes.len();
1109 self.catch_scopes.push(catch_id);
1111 let result = f(self);
1114 self.catch_scopes.len(),
1115 "catch scopes should be added and removed in stack order"
1118 self.catch_scopes.pop().unwrap();
1125 capture_clause: CaptureBy,
1126 closure_node_id: NodeId,
1127 ret_ty: Option<&Ty>,
1129 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1130 ) -> hir::ExprKind {
1131 let capture_clause = self.lower_capture_clause(capture_clause);
1132 let output = match ret_ty {
1133 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
1134 None => FunctionRetTy::Default(span),
1136 let ast_decl = FnDecl {
1141 let decl = self.lower_fn_decl(&ast_decl, None, /* impl trait allowed */ false, None);
1142 let body_id = self.lower_fn_body(&ast_decl, |this| {
1143 this.is_async_body = true;
1146 let generator = hir::Expr {
1147 hir_id: self.lower_node_id(closure_node_id),
1148 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
1149 Some(hir::GeneratorMovability::Static)),
1151 attrs: ThinVec::new(),
1154 let unstable_span = self.mark_span_with_reason(
1155 CompilerDesugaringKind::Async,
1157 Some(vec![sym::gen_future].into()),
1159 let gen_future = self.expr_std_path(
1160 unstable_span, &[sym::future, sym::from_generator], None, ThinVec::new());
1161 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
1166 f: impl FnOnce(&mut LoweringContext<'_>) -> (HirVec<hir::Arg>, hir::Expr),
1168 let prev_is_generator = mem::replace(&mut self.is_generator, false);
1169 let prev_is_async_body = mem::replace(&mut self.is_async_body, false);
1170 let (arguments, result) = f(self);
1171 let body_id = self.record_body(arguments, result);
1172 self.is_generator = prev_is_generator;
1173 self.is_async_body = prev_is_async_body;
1180 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1182 self.lower_body(|this| (
1183 decl.inputs.iter().map(|x| this.lower_arg(x)).collect(),
1188 fn lower_const_body(&mut self, expr: &Expr) -> hir::BodyId {
1189 self.lower_body(|this| (hir_vec![], this.lower_expr(expr)))
1192 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
1194 F: FnOnce(&mut LoweringContext<'_>) -> T,
1196 // We're no longer in the base loop's condition; we're in another loop.
1197 let was_in_loop_condition = self.is_in_loop_condition;
1198 self.is_in_loop_condition = false;
1200 let len = self.loop_scopes.len();
1201 self.loop_scopes.push(loop_id);
1203 let result = f(self);
1206 self.loop_scopes.len(),
1207 "loop scopes should be added and removed in stack order"
1210 self.loop_scopes.pop().unwrap();
1212 self.is_in_loop_condition = was_in_loop_condition;
1217 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
1219 F: FnOnce(&mut LoweringContext<'_>) -> T,
1221 let was_in_loop_condition = self.is_in_loop_condition;
1222 self.is_in_loop_condition = true;
1224 let result = f(self);
1226 self.is_in_loop_condition = was_in_loop_condition;
1231 fn with_dyn_type_scope<T, F>(&mut self, in_scope: bool, f: F) -> T
1233 F: FnOnce(&mut LoweringContext<'_>) -> T,
1235 let was_in_dyn_type = self.is_in_dyn_type;
1236 self.is_in_dyn_type = in_scope;
1238 let result = f(self);
1240 self.is_in_dyn_type = was_in_dyn_type;
1245 fn with_new_scopes<T, F>(&mut self, f: F) -> T
1247 F: FnOnce(&mut LoweringContext<'_>) -> T,
1249 let was_in_loop_condition = self.is_in_loop_condition;
1250 self.is_in_loop_condition = false;
1252 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
1253 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
1255 self.catch_scopes = catch_scopes;
1256 self.loop_scopes = loop_scopes;
1258 self.is_in_loop_condition = was_in_loop_condition;
1263 fn def_key(&mut self, id: DefId) -> DefKey {
1265 self.resolver.definitions().def_key(id.index)
1267 self.cstore.def_key(id)
1271 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1272 label.map(|label| hir::Label {
1277 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1278 let target_id = match destination {
1280 if let Some(loop_id) = self.resolver.get_label_res(id) {
1281 Ok(self.lower_node_id(loop_id))
1283 Err(hir::LoopIdError::UnresolvedLabel)
1290 .map(|id| Ok(self.lower_node_id(id)))
1291 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1296 label: self.lower_label(destination.map(|(_, label)| label)),
1301 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1304 .map(|a| self.lower_attr(a))
1308 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1309 // Note that we explicitly do not walk the path. Since we don't really
1310 // lower attributes (we use the AST version) there is nowhere to keep
1311 // the `HirId`s. We don't actually need HIR version of attributes anyway.
1315 path: attr.path.clone(),
1316 tokens: self.lower_token_stream(attr.tokens.clone()),
1317 is_sugared_doc: attr.is_sugared_doc,
1322 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1325 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1329 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1331 TokenTree::Token(span, token) => self.lower_token(token, span),
1332 TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1335 self.lower_token_stream(tts),
1340 fn lower_token(&mut self, token: TokenKind, span: Span) -> TokenStream {
1342 token::Interpolated(nt) => {
1343 let tts = nt.to_tokenstream(&self.sess.parse_sess, span);
1344 self.lower_token_stream(tts)
1346 other => TokenTree::Token(span, other).into(),
1350 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1352 hir_id: self.next_id(),
1353 attrs: self.lower_attrs(&arm.attrs),
1354 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1355 guard: match arm.guard {
1356 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1359 body: P(self.lower_expr(&arm.body)),
1364 /// Given an associated type constraint like one of these:
1367 /// T: Iterator<Item: Debug>
1369 /// T: Iterator<Item = Debug>
1373 /// returns a `hir::TypeBinding` representing `Item`.
1374 fn lower_assoc_ty_constraint(&mut self,
1375 c: &AssocTyConstraint,
1376 itctx: ImplTraitContext<'_>)
1377 -> hir::TypeBinding {
1378 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", c, itctx);
1380 let kind = match c.kind {
1381 AssocTyConstraintKind::Equality { ref ty } => hir::TypeBindingKind::Equality {
1382 ty: self.lower_ty(ty, itctx)
1384 AssocTyConstraintKind::Bound { ref bounds } => {
1385 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1386 let (desugar_to_impl_trait, itctx) = match itctx {
1387 // We are in the return position:
1389 // fn foo() -> impl Iterator<Item: Debug>
1393 // fn foo() -> impl Iterator<Item = impl Debug>
1394 ImplTraitContext::Existential(_) => (true, itctx),
1396 // We are in the argument position, but within a dyn type:
1398 // fn foo(x: dyn Iterator<Item: Debug>)
1402 // fn foo(x: dyn Iterator<Item = impl Debug>)
1403 ImplTraitContext::Universal(_) if self.is_in_dyn_type => (true, itctx),
1405 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1406 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1407 // "impl trait context" to permit `impl Debug` in this position (it desugars
1408 // then to an existential type).
1410 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1411 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type =>
1412 (true, ImplTraitContext::Existential(None)),
1414 // We are in the argument position, but not within a dyn type:
1416 // fn foo(x: impl Iterator<Item: Debug>)
1418 // so we leave it as is and this gets expanded in astconv to a bound like
1419 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1421 _ => (false, itctx),
1424 if desugar_to_impl_trait {
1425 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1426 // constructing the HIR for `impl bounds...` and then lowering that.
1428 let impl_trait_node_id = self.sess.next_node_id();
1429 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
1430 self.resolver.definitions().create_def_with_parent(
1433 DefPathData::ImplTrait,
1438 self.with_dyn_type_scope(false, |this| {
1439 let ty = this.lower_ty(
1441 id: this.sess.next_node_id(),
1442 node: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1448 hir::TypeBindingKind::Equality {
1453 // Desugar `AssocTy: Bounds` into a type binding where the
1454 // later desugars into a trait predicate.
1455 let bounds = self.lower_param_bounds(bounds, itctx);
1457 hir::TypeBindingKind::Constraint {
1465 hir_id: self.lower_node_id(c.id),
1472 fn lower_generic_arg(&mut self,
1473 arg: &ast::GenericArg,
1474 itctx: ImplTraitContext<'_>)
1475 -> hir::GenericArg {
1477 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1478 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1479 ast::GenericArg::Const(ct) => {
1480 GenericArg::Const(ConstArg {
1481 value: self.lower_anon_const(&ct),
1482 span: ct.value.span,
1488 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1489 P(self.lower_ty_direct(t, itctx))
1492 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1493 let kind = match t.node {
1494 TyKind::Infer => hir::TyKind::Infer,
1495 TyKind::Err => hir::TyKind::Err,
1496 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1497 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1498 TyKind::Rptr(ref region, ref mt) => {
1499 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1500 let lifetime = match *region {
1501 Some(ref lt) => self.lower_lifetime(lt),
1502 None => self.elided_ref_lifetime(span),
1504 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1506 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1509 this.with_anonymous_lifetime_mode(
1510 AnonymousLifetimeMode::PassThrough,
1512 hir::TyKind::BareFn(P(hir::BareFnTy {
1513 generic_params: this.lower_generic_params(
1515 &NodeMap::default(),
1516 ImplTraitContext::disallowed(),
1518 unsafety: this.lower_unsafety(f.unsafety),
1520 decl: this.lower_fn_decl(&f.decl, None, false, None),
1521 arg_names: this.lower_fn_args_to_names(&f.decl),
1527 TyKind::Never => hir::TyKind::Never,
1528 TyKind::Tup(ref tys) => {
1529 hir::TyKind::Tup(tys.iter().map(|ty| {
1530 self.lower_ty_direct(ty, itctx.reborrow())
1533 TyKind::Paren(ref ty) => {
1534 return self.lower_ty_direct(ty, itctx);
1536 TyKind::Path(ref qself, ref path) => {
1537 let id = self.lower_node_id(t.id);
1538 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1539 let ty = self.ty_path(id, t.span, qpath);
1540 if let hir::TyKind::TraitObject(..) = ty.node {
1541 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1545 TyKind::ImplicitSelf => {
1546 let res = self.expect_full_res(t.id);
1547 let res = self.lower_res(res);
1548 hir::TyKind::Path(hir::QPath::Resolved(
1552 segments: hir_vec![hir::PathSegment::from_ident(
1553 Ident::with_empty_ctxt(kw::SelfUpper)
1559 TyKind::Array(ref ty, ref length) => {
1560 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1562 TyKind::Typeof(ref expr) => {
1563 hir::TyKind::Typeof(self.lower_anon_const(expr))
1565 TyKind::TraitObject(ref bounds, kind) => {
1566 let mut lifetime_bound = None;
1567 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1570 .filter_map(|bound| match *bound {
1571 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1572 Some(this.lower_poly_trait_ref(ty, itctx.reborrow()))
1574 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1575 GenericBound::Outlives(ref lifetime) => {
1576 if lifetime_bound.is_none() {
1577 lifetime_bound = Some(this.lower_lifetime(lifetime));
1583 let lifetime_bound =
1584 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1585 (bounds, lifetime_bound)
1587 if kind != TraitObjectSyntax::Dyn {
1588 self.maybe_lint_bare_trait(t.span, t.id, false);
1590 hir::TyKind::TraitObject(bounds, lifetime_bound)
1592 TyKind::ImplTrait(def_node_id, ref bounds) => {
1595 ImplTraitContext::Existential(fn_def_id) => {
1596 self.lower_existential_impl_trait(
1597 span, fn_def_id, def_node_id,
1598 |this| this.lower_param_bounds(bounds, itctx),
1601 ImplTraitContext::Universal(in_band_ty_params) => {
1602 // Add a definition for the in-band `Param`.
1603 let def_index = self
1606 .opt_def_index(def_node_id)
1609 let hir_bounds = self.lower_param_bounds(
1611 ImplTraitContext::Universal(in_band_ty_params),
1613 // Set the name to `impl Bound1 + Bound2`.
1614 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1615 in_band_ty_params.push(hir::GenericParam {
1616 hir_id: self.lower_node_id(def_node_id),
1617 name: ParamName::Plain(ident),
1618 pure_wrt_drop: false,
1622 kind: hir::GenericParamKind::Type {
1624 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1628 hir::TyKind::Path(hir::QPath::Resolved(
1632 res: Res::Def(DefKind::TyParam, DefId::local(def_index)),
1633 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1637 ImplTraitContext::Disallowed(pos) => {
1638 let allowed_in = if self.sess.features_untracked()
1639 .impl_trait_in_bindings {
1640 "bindings or function and inherent method return types"
1642 "function and inherent method return types"
1644 let mut err = struct_span_err!(
1648 "`impl Trait` not allowed outside of {}",
1651 if pos == ImplTraitPosition::Binding &&
1652 nightly_options::is_nightly_build() {
1654 "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1662 TyKind::Mac(_) => bug!("`TyMac` should have been expanded by now."),
1663 TyKind::CVarArgs => {
1664 // Create the implicit lifetime of the "spoofed" `VaList`.
1665 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1666 let lt = self.new_implicit_lifetime(span);
1667 hir::TyKind::CVarArgs(lt)
1674 hir_id: self.lower_node_id(t.id),
1678 fn lower_existential_impl_trait(
1681 fn_def_id: Option<DefId>,
1682 exist_ty_node_id: NodeId,
1683 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1685 // Make sure we know that some funky desugaring has been going on here.
1686 // This is a first: there is code in other places like for loop
1687 // desugaring that explicitly states that we don't want to track that.
1688 // Not tracking it makes lints in rustc and clippy very fragile, as
1689 // frequently opened issues show.
1690 let exist_ty_span = self.mark_span_with_reason(
1691 CompilerDesugaringKind::ExistentialType,
1696 let exist_ty_def_index = self
1699 .opt_def_index(exist_ty_node_id)
1702 self.allocate_hir_id_counter(exist_ty_node_id);
1704 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1706 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1712 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1713 let exist_ty_item = hir::ExistTy {
1714 generics: hir::Generics {
1715 params: lifetime_defs,
1716 where_clause: hir::WhereClause {
1717 hir_id: lctx.next_id(),
1718 predicates: hir_vec![],
1723 impl_trait_fn: fn_def_id,
1724 origin: hir::ExistTyOrigin::ReturnImplTrait,
1727 trace!("exist ty from impl trait def-index: {:#?}", exist_ty_def_index);
1728 let exist_ty_id = lctx.generate_existential_type(
1735 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1736 hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, lifetimes)
1740 /// Registers a new existential type with the proper `NodeId`s and
1741 /// returns the lowered node-ID for the existential type.
1742 fn generate_existential_type(
1744 exist_ty_node_id: NodeId,
1745 exist_ty_item: hir::ExistTy,
1747 exist_ty_span: Span,
1749 let exist_ty_item_kind = hir::ItemKind::Existential(exist_ty_item);
1750 let exist_ty_id = self.lower_node_id(exist_ty_node_id);
1751 // Generate an `existential type Foo: Trait;` declaration.
1752 trace!("registering existential type with id {:#?}", exist_ty_id);
1753 let exist_ty_item = hir::Item {
1754 hir_id: exist_ty_id,
1755 ident: Ident::invalid(),
1756 attrs: Default::default(),
1757 node: exist_ty_item_kind,
1758 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1759 span: exist_ty_span,
1762 // Insert the item into the global item list. This usually happens
1763 // automatically for all AST items. But this existential type item
1764 // does not actually exist in the AST.
1765 self.insert_item(exist_ty_item);
1769 fn lifetimes_from_impl_trait_bounds(
1771 exist_ty_id: NodeId,
1772 parent_index: DefIndex,
1773 bounds: &hir::GenericBounds,
1774 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1775 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1776 // appear in the bounds, excluding lifetimes that are created within the bounds.
1777 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1778 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1779 context: &'r mut LoweringContext<'a>,
1781 exist_ty_id: NodeId,
1782 collect_elided_lifetimes: bool,
1783 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1784 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1785 output_lifetimes: Vec<hir::GenericArg>,
1786 output_lifetime_params: Vec<hir::GenericParam>,
1789 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1790 fn nested_visit_map<'this>(
1792 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1793 hir::intravisit::NestedVisitorMap::None
1796 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1797 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1798 if parameters.parenthesized {
1799 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1800 self.collect_elided_lifetimes = false;
1801 hir::intravisit::walk_generic_args(self, span, parameters);
1802 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1804 hir::intravisit::walk_generic_args(self, span, parameters);
1808 fn visit_ty(&mut self, t: &'v hir::Ty) {
1809 // Don't collect elided lifetimes used inside of `fn()` syntax.
1810 if let hir::TyKind::BareFn(_) = t.node {
1811 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1812 self.collect_elided_lifetimes = false;
1814 // Record the "stack height" of `for<'a>` lifetime bindings
1815 // to be able to later fully undo their introduction.
1816 let old_len = self.currently_bound_lifetimes.len();
1817 hir::intravisit::walk_ty(self, t);
1818 self.currently_bound_lifetimes.truncate(old_len);
1820 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1822 hir::intravisit::walk_ty(self, t)
1826 fn visit_poly_trait_ref(
1828 trait_ref: &'v hir::PolyTraitRef,
1829 modifier: hir::TraitBoundModifier,
1831 // Record the "stack height" of `for<'a>` lifetime bindings
1832 // to be able to later fully undo their introduction.
1833 let old_len = self.currently_bound_lifetimes.len();
1834 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1835 self.currently_bound_lifetimes.truncate(old_len);
1838 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1839 // Record the introduction of 'a in `for<'a> ...`.
1840 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1841 // Introduce lifetimes one at a time so that we can handle
1842 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1843 let lt_name = hir::LifetimeName::Param(param.name);
1844 self.currently_bound_lifetimes.push(lt_name);
1847 hir::intravisit::walk_generic_param(self, param);
1850 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1851 let name = match lifetime.name {
1852 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1853 if self.collect_elided_lifetimes {
1854 // Use `'_` for both implicit and underscore lifetimes in
1855 // `abstract type Foo<'_>: SomeTrait<'_>;`.
1856 hir::LifetimeName::Underscore
1861 hir::LifetimeName::Param(_) => lifetime.name,
1862 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1865 if !self.currently_bound_lifetimes.contains(&name)
1866 && !self.already_defined_lifetimes.contains(&name) {
1867 self.already_defined_lifetimes.insert(name);
1869 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1870 hir_id: self.context.next_id(),
1871 span: lifetime.span,
1875 let def_node_id = self.context.sess.next_node_id();
1877 self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1878 self.context.resolver.definitions().create_def_with_parent(
1881 DefPathData::LifetimeNs(name.ident().as_interned_str()),
1885 let (name, kind) = match name {
1886 hir::LifetimeName::Underscore => (
1887 hir::ParamName::Plain(Ident::with_empty_ctxt(kw::UnderscoreLifetime)),
1888 hir::LifetimeParamKind::Elided,
1890 hir::LifetimeName::Param(param_name) => (
1892 hir::LifetimeParamKind::Explicit,
1894 _ => bug!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1897 self.output_lifetime_params.push(hir::GenericParam {
1900 span: lifetime.span,
1901 pure_wrt_drop: false,
1904 kind: hir::GenericParamKind::Lifetime { kind }
1910 let mut lifetime_collector = ImplTraitLifetimeCollector {
1912 parent: parent_index,
1914 collect_elided_lifetimes: true,
1915 currently_bound_lifetimes: Vec::new(),
1916 already_defined_lifetimes: FxHashSet::default(),
1917 output_lifetimes: Vec::new(),
1918 output_lifetime_params: Vec::new(),
1921 for bound in bounds {
1922 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1926 lifetime_collector.output_lifetimes.into(),
1927 lifetime_collector.output_lifetime_params.into(),
1931 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1936 .map(|x| self.lower_foreign_item(x))
1941 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1948 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1950 node: hir::VariantKind {
1951 ident: v.node.ident,
1952 id: self.lower_node_id(v.node.id),
1953 attrs: self.lower_attrs(&v.node.attrs),
1954 data: self.lower_variant_data(&v.node.data),
1955 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1964 qself: &Option<QSelf>,
1966 param_mode: ParamMode,
1967 mut itctx: ImplTraitContext<'_>,
1969 let qself_position = qself.as_ref().map(|q| q.position);
1970 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1972 let partial_res = self.resolver
1973 .get_partial_res(id)
1974 .unwrap_or_else(|| PartialRes::new(Res::Err));
1976 let proj_start = p.segments.len() - partial_res.unresolved_segments();
1977 let path = P(hir::Path {
1978 res: self.lower_res(partial_res.base_res()),
1979 segments: p.segments[..proj_start]
1982 .map(|(i, segment)| {
1983 let param_mode = match (qself_position, param_mode) {
1984 (Some(j), ParamMode::Optional) if i < j => {
1985 // This segment is part of the trait path in a
1986 // qualified path - one of `a`, `b` or `Trait`
1987 // in `<X as a::b::Trait>::T::U::method`.
1993 // Figure out if this is a type/trait segment,
1994 // which may need lifetime elision performed.
1995 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1996 krate: def_id.krate,
1997 index: this.def_key(def_id).parent.expect("missing parent"),
1999 let type_def_id = match partial_res.base_res() {
2000 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2001 Some(parent_def_id(self, def_id))
2003 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
2004 Some(parent_def_id(self, def_id))
2006 Res::Def(DefKind::Struct, def_id)
2007 | Res::Def(DefKind::Union, def_id)
2008 | Res::Def(DefKind::Enum, def_id)
2009 | Res::Def(DefKind::TyAlias, def_id)
2010 | Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start =>
2016 let parenthesized_generic_args = match partial_res.base_res() {
2017 // `a::b::Trait(Args)`
2018 Res::Def(DefKind::Trait, _)
2019 if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
2020 // `a::b::Trait(Args)::TraitItem`
2021 Res::Def(DefKind::Method, _)
2022 | Res::Def(DefKind::AssocConst, _)
2023 | Res::Def(DefKind::AssocTy, _)
2024 if i + 2 == proj_start =>
2026 ParenthesizedGenericArgs::Ok
2028 // Avoid duplicated errors.
2029 Res::Err => ParenthesizedGenericArgs::Ok,
2031 Res::Def(DefKind::Struct, _)
2032 | Res::Def(DefKind::Enum, _)
2033 | Res::Def(DefKind::Union, _)
2034 | Res::Def(DefKind::TyAlias, _)
2035 | Res::Def(DefKind::Variant, _) if i + 1 == proj_start =>
2037 ParenthesizedGenericArgs::Err
2039 // A warning for now, for compatibility reasons.
2040 _ => ParenthesizedGenericArgs::Warn,
2043 let num_lifetimes = type_def_id.map_or(0, |def_id| {
2044 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
2047 assert!(!def_id.is_local());
2049 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
2050 let n = item_generics.own_counts().lifetimes;
2051 self.type_def_lifetime_params.insert(def_id, n);
2054 self.lower_path_segment(
2059 parenthesized_generic_args,
2068 // Simple case, either no projections, or only fully-qualified.
2069 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
2070 if partial_res.unresolved_segments() == 0 {
2071 return hir::QPath::Resolved(qself, path);
2074 // Create the innermost type that we're projecting from.
2075 let mut ty = if path.segments.is_empty() {
2076 // If the base path is empty that means there exists a
2077 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
2078 qself.expect("missing QSelf for <T>::...")
2080 // Otherwise, the base path is an implicit `Self` type path,
2081 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
2082 // `<I as Iterator>::Item::default`.
2083 let new_id = self.next_id();
2084 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
2087 // Anything after the base path are associated "extensions",
2088 // out of which all but the last one are associated types,
2089 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
2090 // * base path is `std::vec::Vec<T>`
2091 // * "extensions" are `IntoIter`, `Item` and `clone`
2092 // * type nodes are:
2093 // 1. `std::vec::Vec<T>` (created above)
2094 // 2. `<std::vec::Vec<T>>::IntoIter`
2095 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
2096 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
2097 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
2098 let segment = P(self.lower_path_segment(
2103 ParenthesizedGenericArgs::Warn,
2107 let qpath = hir::QPath::TypeRelative(ty, segment);
2109 // It's finished, return the extension of the right node type.
2110 if i == p.segments.len() - 1 {
2114 // Wrap the associated extension in another type node.
2115 let new_id = self.next_id();
2116 ty = P(self.ty_path(new_id, p.span, qpath));
2119 // We should've returned in the for loop above.
2122 "lower_qpath: no final extension segment in {}..{}",
2128 fn lower_path_extra(
2132 param_mode: ParamMode,
2133 explicit_owner: Option<NodeId>,
2137 segments: p.segments
2140 self.lower_path_segment(
2145 ParenthesizedGenericArgs::Err,
2146 ImplTraitContext::disallowed(),
2155 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
2156 let res = self.expect_full_res(id);
2157 let res = self.lower_res(res);
2158 self.lower_path_extra(res, p, param_mode, None)
2161 fn lower_path_segment(
2164 segment: &PathSegment,
2165 param_mode: ParamMode,
2166 expected_lifetimes: usize,
2167 parenthesized_generic_args: ParenthesizedGenericArgs,
2168 itctx: ImplTraitContext<'_>,
2169 explicit_owner: Option<NodeId>,
2170 ) -> hir::PathSegment {
2171 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
2172 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
2173 match **generic_args {
2174 GenericArgs::AngleBracketed(ref data) => {
2175 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
2177 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
2178 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
2179 ParenthesizedGenericArgs::Warn => {
2180 self.sess.buffer_lint(
2181 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
2186 (hir::GenericArgs::none(), true)
2188 ParenthesizedGenericArgs::Err => {
2189 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
2190 err.span_label(data.span, "only `Fn` traits may use parentheses");
2191 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
2192 // Do not suggest going from `Trait()` to `Trait<>`
2193 if data.inputs.len() > 0 {
2194 err.span_suggestion(
2196 "use angle brackets instead",
2197 format!("<{}>", &snippet[1..snippet.len() - 1]),
2198 Applicability::MaybeIncorrect,
2204 self.lower_angle_bracketed_parameter_data(
2205 &data.as_angle_bracketed_args(),
2215 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
2218 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
2219 GenericArg::Lifetime(_) => true,
2222 let first_generic_span = generic_args.args.iter().map(|a| a.span())
2223 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
2224 if !generic_args.parenthesized && !has_lifetimes {
2226 self.elided_path_lifetimes(path_span, expected_lifetimes)
2228 .map(|lt| GenericArg::Lifetime(lt))
2229 .chain(generic_args.args.into_iter())
2231 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
2232 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
2233 let no_ty_args = generic_args.args.len() == expected_lifetimes;
2234 let no_bindings = generic_args.bindings.is_empty();
2235 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
2236 // If there are no (non-implicit) generic args or associated type
2237 // bindings, our suggestion includes the angle brackets.
2238 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
2240 // Otherwise (sorry, this is kind of gross) we need to infer the
2241 // place to splice in the `'_, ` from the generics that do exist.
2242 let first_generic_span = first_generic_span
2243 .expect("already checked that type args or bindings exist");
2244 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
2246 match self.anonymous_lifetime_mode {
2247 // In create-parameter mode we error here because we don't want to support
2248 // deprecated impl elision in new features like impl elision and `async fn`,
2249 // both of which work using the `CreateParameter` mode:
2251 // impl Foo for std::cell::Ref<u32> // note lack of '_
2252 // async fn foo(_: std::cell::Ref<u32>) { ... }
2253 AnonymousLifetimeMode::CreateParameter => {
2254 let mut err = struct_span_err!(
2258 "implicit elided lifetime not allowed here"
2260 crate::lint::builtin::add_elided_lifetime_in_path_suggestion(
2271 AnonymousLifetimeMode::PassThrough |
2272 AnonymousLifetimeMode::ReportError |
2273 AnonymousLifetimeMode::Replace(_) => {
2274 self.sess.buffer_lint_with_diagnostic(
2275 ELIDED_LIFETIMES_IN_PATHS,
2278 "hidden lifetime parameters in types are deprecated",
2279 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
2292 let res = self.expect_full_res(segment.id);
2293 let id = if let Some(owner) = explicit_owner {
2294 self.lower_node_id_with_owner(segment.id, owner)
2296 self.lower_node_id(segment.id)
2299 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
2300 segment.ident, segment.id, id,
2303 hir::PathSegment::new(
2306 Some(self.lower_res(res)),
2312 fn lower_angle_bracketed_parameter_data(
2314 data: &AngleBracketedArgs,
2315 param_mode: ParamMode,
2316 mut itctx: ImplTraitContext<'_>,
2317 ) -> (hir::GenericArgs, bool) {
2318 let &AngleBracketedArgs { ref args, ref constraints, .. } = data;
2319 let has_types = args.iter().any(|arg| match arg {
2320 ast::GenericArg::Type(_) => true,
2325 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
2326 bindings: constraints.iter()
2327 .map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow()))
2329 parenthesized: false,
2331 !has_types && param_mode == ParamMode::Optional
2335 fn lower_parenthesized_parameter_data(
2337 data: &ParenthesizedArgs,
2338 ) -> (hir::GenericArgs, bool) {
2339 // Switch to `PassThrough` mode for anonymous lifetimes; this
2340 // means that we permit things like `&Ref<T>`, where `Ref` has
2341 // a hidden lifetime parameter. This is needed for backwards
2342 // compatibility, even in contexts like an impl header where
2343 // we generally don't permit such things (see #51008).
2344 self.with_anonymous_lifetime_mode(
2345 AnonymousLifetimeMode::PassThrough,
2347 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2350 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
2352 let mk_tup = |this: &mut Self, tys, span| {
2353 hir::Ty { node: hir::TyKind::Tup(tys), hir_id: this.next_id(), span }
2357 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
2360 hir_id: this.next_id(),
2361 ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
2362 kind: hir::TypeBindingKind::Equality {
2365 .map(|ty| this.lower_ty(
2367 ImplTraitContext::disallowed()
2370 P(mk_tup(this, hir::HirVec::new(), span))
2373 span: output.as_ref().map_or(span, |ty| ty.span),
2376 parenthesized: true,
2384 fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) {
2385 let mut ids = SmallVec::<[NodeId; 1]>::new();
2386 if self.sess.features_untracked().impl_trait_in_bindings {
2387 if let Some(ref ty) = l.ty {
2388 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2389 visitor.visit_ty(ty);
2392 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2394 hir_id: self.lower_node_id(l.id),
2397 .map(|t| self.lower_ty(t,
2398 if self.sess.features_untracked().impl_trait_in_bindings {
2399 ImplTraitContext::Existential(Some(parent_def_id))
2401 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2404 pat: self.lower_pat(&l.pat),
2405 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2407 attrs: l.attrs.clone(),
2408 source: hir::LocalSource::Normal,
2412 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
2414 Mutability::Mutable => hir::MutMutable,
2415 Mutability::Immutable => hir::MutImmutable,
2419 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
2421 hir_id: self.lower_node_id(arg.id),
2422 pat: self.lower_pat(&arg.pat),
2426 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2429 .map(|arg| match arg.pat.node {
2430 PatKind::Ident(_, ident, _) => ident,
2431 _ => Ident::new(kw::Invalid, arg.pat.span),
2436 // Lowers a function declaration.
2438 // `decl`: the unlowered (AST) function declaration.
2439 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
2440 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2441 // `make_ret_async` is also `Some`.
2442 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
2443 // This guards against trait declarations and implementations where `impl Trait` is
2445 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2446 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
2447 // return type `impl Trait` item.
2451 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2452 impl_trait_return_allow: bool,
2453 make_ret_async: Option<NodeId>,
2454 ) -> P<hir::FnDecl> {
2455 let lt_mode = if make_ret_async.is_some() {
2456 // In `async fn`, argument-position elided lifetimes
2457 // must be transformed into fresh generic parameters so that
2458 // they can be applied to the existential return type.
2459 AnonymousLifetimeMode::CreateParameter
2461 self.anonymous_lifetime_mode
2464 // Remember how many lifetimes were already around so that we can
2465 // only look at the lifetime parameters introduced by the arguments.
2466 let lifetime_count_before_args = self.lifetimes_to_define.len();
2467 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2471 if let Some((_, ibty)) = &mut in_band_ty_params {
2472 this.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2474 this.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2477 .collect::<HirVec<_>>()
2480 let output = if let Some(ret_id) = make_ret_async {
2481 // Calculate the `LtReplacement` to use for any return-position elided
2482 // lifetimes based on the elided lifetime parameters introduced in the args.
2483 let lt_replacement = get_elided_lt_replacement(
2484 &self.lifetimes_to_define[lifetime_count_before_args..]
2486 self.lower_async_fn_ret_ty(
2488 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
2494 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2495 Some((def_id, _)) if impl_trait_return_allow => {
2496 hir::Return(self.lower_ty(ty,
2497 ImplTraitContext::Existential(Some(def_id))
2501 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2504 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2511 c_variadic: decl.c_variadic,
2512 implicit_self: decl.inputs.get(0).map_or(
2513 hir::ImplicitSelfKind::None,
2515 let is_mutable_pat = match arg.pat.node {
2516 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2517 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2518 mt == Mutability::Mutable,
2523 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2524 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2525 // Given we are only considering `ImplicitSelf` types, we needn't consider
2526 // the case where we have a mutable pattern to a reference as that would
2527 // no longer be an `ImplicitSelf`.
2528 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2529 mt.mutbl == ast::Mutability::Mutable =>
2530 hir::ImplicitSelfKind::MutRef,
2531 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2532 hir::ImplicitSelfKind::ImmRef,
2533 _ => hir::ImplicitSelfKind::None,
2540 // Transforms `-> T` for `async fn` into `-> ExistTy { .. }`
2541 // combined with the following definition of `ExistTy`:
2543 // existential type ExistTy<generics_from_parent_fn>: Future<Output = T>;
2545 // `inputs`: lowered types of arguments to the function (used to collect lifetimes)
2546 // `output`: unlowered output type (`T` in `-> T`)
2547 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
2548 // `exist_ty_node_id`: `NodeId` of the existential type that should be created
2549 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
2550 fn lower_async_fn_ret_ty(
2552 output: &FunctionRetTy,
2554 exist_ty_node_id: NodeId,
2555 elided_lt_replacement: LtReplacement,
2556 ) -> hir::FunctionRetTy {
2557 let span = output.span();
2559 let exist_ty_span = self.mark_span_with_reason(
2560 CompilerDesugaringKind::Async,
2565 let exist_ty_def_index = self
2568 .opt_def_index(exist_ty_node_id)
2571 self.allocate_hir_id_counter(exist_ty_node_id);
2573 let (exist_ty_id, lifetime_params) = self.with_hir_id_owner(exist_ty_node_id, |this| {
2574 let future_bound = this.with_anonymous_lifetime_mode(
2575 AnonymousLifetimeMode::Replace(elided_lt_replacement),
2576 |this| this.lower_async_fn_output_type_to_future_bound(
2583 // Calculate all the lifetimes that should be captured
2584 // by the existential type. This should include all in-scope
2585 // lifetime parameters, including those defined in-band.
2587 // Note: this must be done after lowering the output type,
2588 // as the output type may introduce new in-band lifetimes.
2589 let lifetime_params: Vec<(Span, ParamName)> =
2590 this.in_scope_lifetimes
2592 .map(|ident| (ident.span, ParamName::Plain(ident)))
2593 .chain(this.lifetimes_to_define.iter().cloned())
2596 let generic_params =
2599 .map(|(span, hir_name)| {
2600 this.lifetime_to_generic_param(span, hir_name, exist_ty_def_index)
2604 let exist_ty_item = hir::ExistTy {
2605 generics: hir::Generics {
2606 params: generic_params,
2607 where_clause: hir::WhereClause {
2608 hir_id: this.next_id(),
2609 predicates: hir_vec![],
2613 bounds: hir_vec![future_bound],
2614 impl_trait_fn: Some(fn_def_id),
2615 origin: hir::ExistTyOrigin::AsyncFn,
2618 trace!("exist ty from async fn def index: {:#?}", exist_ty_def_index);
2619 let exist_ty_id = this.generate_existential_type(
2626 (exist_ty_id, lifetime_params)
2632 .map(|(span, hir_name)| {
2633 GenericArg::Lifetime(hir::Lifetime {
2634 hir_id: self.next_id(),
2636 name: hir::LifetimeName::Param(hir_name),
2641 let exist_ty_ref = hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, generic_args);
2643 hir::FunctionRetTy::Return(P(hir::Ty {
2646 hir_id: self.next_id(),
2650 /// Transforms `-> T` into `Future<Output = T>`
2651 fn lower_async_fn_output_type_to_future_bound(
2653 output: &FunctionRetTy,
2656 ) -> hir::GenericBound {
2657 // Compute the `T` in `Future<Output = T>` from the return type.
2658 let output_ty = match output {
2659 FunctionRetTy::Ty(ty) => {
2660 self.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2662 FunctionRetTy::Default(ret_ty_span) => {
2664 hir_id: self.next_id(),
2665 node: hir::TyKind::Tup(hir_vec![]),
2672 let future_params = P(hir::GenericArgs {
2674 bindings: hir_vec![hir::TypeBinding {
2675 ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
2676 kind: hir::TypeBindingKind::Equality {
2679 hir_id: self.next_id(),
2682 parenthesized: false,
2685 // ::std::future::Future<future_params>
2687 self.std_path(span, &[sym::future, sym::Future], Some(future_params), false);
2689 hir::GenericBound::Trait(
2691 trait_ref: hir::TraitRef {
2693 hir_ref_id: self.next_id(),
2695 bound_generic_params: hir_vec![],
2698 hir::TraitBoundModifier::None,
2702 fn lower_param_bound(
2705 itctx: ImplTraitContext<'_>,
2706 ) -> hir::GenericBound {
2708 GenericBound::Trait(ref ty, modifier) => {
2709 hir::GenericBound::Trait(
2710 self.lower_poly_trait_ref(ty, itctx),
2711 self.lower_trait_bound_modifier(modifier),
2714 GenericBound::Outlives(ref lifetime) => {
2715 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2720 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2721 let span = l.ident.span;
2723 ident if ident.name == kw::StaticLifetime =>
2724 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2725 ident if ident.name == kw::UnderscoreLifetime =>
2726 match self.anonymous_lifetime_mode {
2727 AnonymousLifetimeMode::CreateParameter => {
2728 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2729 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2732 AnonymousLifetimeMode::PassThrough => {
2733 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2736 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2738 AnonymousLifetimeMode::Replace(replacement) => {
2739 let hir_id = self.lower_node_id(l.id);
2740 self.replace_elided_lifetime(hir_id, span, replacement)
2744 self.maybe_collect_in_band_lifetime(ident);
2745 let param_name = ParamName::Plain(ident);
2746 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2751 fn new_named_lifetime(
2755 name: hir::LifetimeName,
2756 ) -> hir::Lifetime {
2758 hir_id: self.lower_node_id(id),
2764 /// Replace a return-position elided lifetime with the elided lifetime
2765 /// from the arguments.
2766 fn replace_elided_lifetime(
2770 replacement: LtReplacement,
2771 ) -> hir::Lifetime {
2772 let multiple_or_none = match replacement {
2773 LtReplacement::Some(name) => {
2774 return hir::Lifetime {
2777 name: hir::LifetimeName::Param(name),
2780 LtReplacement::MultipleLifetimes => "multiple",
2781 LtReplacement::NoLifetimes => "none",
2784 let mut err = crate::middle::resolve_lifetime::report_missing_lifetime_specifiers(
2790 "return-position elided lifetimes require exactly one \
2791 input-position elided lifetime, found {}.", multiple_or_none));
2794 hir::Lifetime { hir_id, span, name: hir::LifetimeName::Error }
2797 fn lower_generic_params(
2799 params: &[GenericParam],
2800 add_bounds: &NodeMap<Vec<GenericBound>>,
2801 mut itctx: ImplTraitContext<'_>,
2802 ) -> hir::HirVec<hir::GenericParam> {
2803 params.iter().map(|param| {
2804 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2808 fn lower_generic_param(&mut self,
2809 param: &GenericParam,
2810 add_bounds: &NodeMap<Vec<GenericBound>>,
2811 mut itctx: ImplTraitContext<'_>)
2812 -> hir::GenericParam {
2813 let mut bounds = self.with_anonymous_lifetime_mode(
2814 AnonymousLifetimeMode::ReportError,
2815 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2818 let (name, kind) = match param.kind {
2819 GenericParamKind::Lifetime => {
2820 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2821 self.is_collecting_in_band_lifetimes = false;
2823 let lt = self.with_anonymous_lifetime_mode(
2824 AnonymousLifetimeMode::ReportError,
2825 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2827 let param_name = match lt.name {
2828 hir::LifetimeName::Param(param_name) => param_name,
2829 hir::LifetimeName::Implicit
2830 | hir::LifetimeName::Underscore
2831 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2832 hir::LifetimeName::Error => ParamName::Error,
2835 let kind = hir::GenericParamKind::Lifetime {
2836 kind: hir::LifetimeParamKind::Explicit
2839 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2843 GenericParamKind::Type { ref default, .. } => {
2844 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2845 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2846 // Instead, use `gensym("Self")` to create a distinct name that looks the same.
2847 let ident = if param.ident.name == kw::SelfUpper {
2848 param.ident.gensym()
2853 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2854 if !add_bounds.is_empty() {
2855 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2856 bounds = bounds.into_iter()
2861 let kind = hir::GenericParamKind::Type {
2862 default: default.as_ref().map(|x| {
2863 self.lower_ty(x, ImplTraitContext::Existential(None))
2865 synthetic: param.attrs.iter()
2866 .filter(|attr| attr.check_name(sym::rustc_synthetic))
2867 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2871 (hir::ParamName::Plain(ident), kind)
2873 GenericParamKind::Const { ref ty } => {
2874 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const {
2875 ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2881 hir_id: self.lower_node_id(param.id),
2883 span: param.ident.span,
2884 pure_wrt_drop: attr::contains_name(¶m.attrs, sym::may_dangle),
2885 attrs: self.lower_attrs(¶m.attrs),
2893 generics: &Generics,
2894 itctx: ImplTraitContext<'_>)
2897 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2898 // FIXME: this could probably be done with less rightward drift. It also looks like two
2899 // control paths where `report_error` is called are the only paths that advance to after the
2900 // match statement, so the error reporting could probably just be moved there.
2901 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
2902 for pred in &generics.where_clause.predicates {
2903 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2904 'next_bound: for bound in &bound_pred.bounds {
2905 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2906 let report_error = |this: &mut Self| {
2907 this.diagnostic().span_err(
2908 bound_pred.bounded_ty.span,
2909 "`?Trait` bounds are only permitted at the \
2910 point where a type parameter is declared",
2913 // Check if the where clause type is a plain type parameter.
2914 match bound_pred.bounded_ty.node {
2915 TyKind::Path(None, ref path)
2916 if path.segments.len() == 1
2917 && bound_pred.bound_generic_params.is_empty() =>
2919 if let Some(Res::Def(DefKind::TyParam, def_id)) = self.resolver
2920 .get_partial_res(bound_pred.bounded_ty.id)
2921 .map(|d| d.base_res())
2923 if let Some(node_id) =
2924 self.resolver.definitions().as_local_node_id(def_id)
2926 for param in &generics.params {
2928 GenericParamKind::Type { .. } => {
2929 if node_id == param.id {
2930 add_bounds.entry(param.id)
2932 .push(bound.clone());
2933 continue 'next_bound;
2943 _ => report_error(self),
2951 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2952 where_clause: self.lower_where_clause(&generics.where_clause),
2953 span: generics.span,
2957 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2958 self.with_anonymous_lifetime_mode(
2959 AnonymousLifetimeMode::ReportError,
2962 hir_id: this.lower_node_id(wc.id),
2963 predicates: wc.predicates
2965 .map(|predicate| this.lower_where_predicate(predicate))
2972 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2974 WherePredicate::BoundPredicate(WhereBoundPredicate {
2975 ref bound_generic_params,
2980 self.with_in_scope_lifetime_defs(
2981 &bound_generic_params,
2983 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2984 bound_generic_params: this.lower_generic_params(
2985 bound_generic_params,
2986 &NodeMap::default(),
2987 ImplTraitContext::disallowed(),
2989 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
2992 .filter_map(|bound| match *bound {
2993 // Ignore `?Trait` bounds.
2994 // They were copied into type parameters already.
2995 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2996 _ => Some(this.lower_param_bound(
2998 ImplTraitContext::disallowed(),
3007 WherePredicate::RegionPredicate(WhereRegionPredicate {
3011 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
3013 lifetime: self.lower_lifetime(lifetime),
3014 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3016 WherePredicate::EqPredicate(WhereEqPredicate {
3022 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
3023 hir_id: self.lower_node_id(id),
3024 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
3025 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
3032 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
3034 VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
3035 fields.iter().enumerate().map(|f| self.lower_struct_field(f)).collect(),
3038 VariantData::Tuple(ref fields, id) => {
3039 hir::VariantData::Tuple(
3043 .map(|f| self.lower_struct_field(f))
3045 self.lower_node_id(id),
3048 VariantData::Unit(id) => {
3049 hir::VariantData::Unit(self.lower_node_id(id))
3054 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
3055 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
3056 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
3057 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
3061 hir_ref_id: self.lower_node_id(p.ref_id),
3065 fn lower_poly_trait_ref(
3068 mut itctx: ImplTraitContext<'_>,
3069 ) -> hir::PolyTraitRef {
3070 let bound_generic_params = self.lower_generic_params(
3071 &p.bound_generic_params,
3072 &NodeMap::default(),
3075 let trait_ref = self.with_parent_impl_lifetime_defs(
3076 &bound_generic_params,
3077 |this| this.lower_trait_ref(&p.trait_ref, itctx),
3081 bound_generic_params,
3087 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
3090 hir_id: self.lower_node_id(f.id),
3091 ident: match f.ident {
3092 Some(ident) => ident,
3093 // FIXME(jseyfried): positional field hygiene.
3094 None => Ident::new(sym::integer(index), f.span),
3096 vis: self.lower_visibility(&f.vis, None),
3097 ty: self.lower_ty(&f.ty, ImplTraitContext::disallowed()),
3098 attrs: self.lower_attrs(&f.attrs),
3102 fn lower_field(&mut self, f: &Field) -> hir::Field {
3104 hir_id: self.next_id(),
3106 expr: P(self.lower_expr(&f.expr)),
3108 is_shorthand: f.is_shorthand,
3112 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
3114 ty: self.lower_ty(&mt.ty, itctx),
3115 mutbl: self.lower_mutability(mt.mutbl),
3119 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
3120 -> hir::GenericBounds {
3121 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
3124 fn lower_block_with_stmts(
3127 targeted_by_break: bool,
3128 mut stmts: Vec<hir::Stmt>,
3129 ) -> P<hir::Block> {
3130 let mut expr = None;
3132 for (index, stmt) in b.stmts.iter().enumerate() {
3133 if index == b.stmts.len() - 1 {
3134 if let StmtKind::Expr(ref e) = stmt.node {
3135 expr = Some(P(self.lower_expr(e)));
3137 stmts.extend(self.lower_stmt(stmt));
3140 stmts.extend(self.lower_stmt(stmt));
3145 hir_id: self.lower_node_id(b.id),
3146 stmts: stmts.into(),
3148 rules: self.lower_block_check_mode(&b.rules),
3154 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
3155 self.lower_block_with_stmts(b, targeted_by_break, vec![])
3158 fn lower_maybe_async_body(
3164 let closure_id = match asyncness {
3165 IsAsync::Async { closure_id, .. } => closure_id,
3166 IsAsync::NotAsync => return self.lower_fn_body(&decl, |this| {
3167 let body = this.lower_block(body, false);
3168 this.expr_block(body, ThinVec::new())
3172 self.lower_body(|this| {
3173 let mut arguments: Vec<hir::Arg> = Vec::new();
3174 let mut statements: Vec<hir::Stmt> = Vec::new();
3176 // Async function arguments are lowered into the closure body so that they are
3177 // captured and so that the drop order matches the equivalent non-async functions.
3181 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
3188 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
3190 // let __arg2 = __arg2;
3191 // let <pattern> = __arg2;
3192 // let __arg1 = __arg1;
3193 // let <pattern> = __arg1;
3194 // let __arg0 = __arg0;
3195 // let <pattern> = __arg0;
3199 // If `<pattern>` is a simple ident, then it is lowered to a single
3200 // `let <pattern> = <pattern>;` statement as an optimization.
3201 for (index, argument) in decl.inputs.iter().enumerate() {
3202 let argument = this.lower_arg(argument);
3203 let span = argument.pat.span;
3205 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
3206 // `let <pat> = __argN;` statement. In this case, we do not rename the argument.
3207 let (ident, is_simple_argument) = match argument.pat.node {
3208 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _) =>
3211 // Replace the ident for bindings that aren't simple.
3212 let name = format!("__arg{}", index);
3213 let ident = Ident::from_str(&name);
3219 let desugared_span =
3220 this.mark_span_with_reason(CompilerDesugaringKind::Async, span, None);
3222 // Construct an argument representing `__argN: <ty>` to replace the argument of the
3225 // If this is the simple case, this argument will end up being the same as the
3226 // original argument, but with a different pattern id.
3227 let (new_argument_pat, new_argument_id) = this.pat_ident(desugared_span, ident);
3228 let new_argument = hir::Arg {
3229 hir_id: argument.hir_id,
3230 pat: new_argument_pat,
3233 if is_simple_argument {
3234 // If this is the simple case, then we only insert one statement that is
3235 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
3236 // `HirId`s are densely assigned.
3237 let expr = this.expr_ident(desugared_span, ident, new_argument_id);
3238 let stmt = this.stmt_let_pat(
3239 desugared_span, Some(P(expr)), argument.pat, hir::LocalSource::AsyncFn);
3240 statements.push(stmt);
3242 // If this is not the simple case, then we construct two statements:
3245 // let __argN = __argN;
3246 // let <pat> = __argN;
3249 // The first statement moves the argument into the closure and thus ensures
3250 // that the drop order is correct.
3252 // The second statement creates the bindings that the user wrote.
3254 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
3255 // because the user may have specified a `ref mut` binding in the next
3257 let (move_pat, move_id) = this.pat_ident_binding_mode(
3258 desugared_span, ident, hir::BindingAnnotation::Mutable);
3259 let move_expr = this.expr_ident(desugared_span, ident, new_argument_id);
3260 let move_stmt = this.stmt_let_pat(
3261 desugared_span, Some(P(move_expr)), move_pat, hir::LocalSource::AsyncFn);
3263 // Construct the `let <pat> = __argN;` statement. We re-use the original
3264 // argument's pattern so that `HirId`s are densely assigned.
3265 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
3266 let pattern_stmt = this.stmt_let_pat(
3267 desugared_span, Some(P(pattern_expr)), argument.pat,
3268 hir::LocalSource::AsyncFn);
3270 statements.push(move_stmt);
3271 statements.push(pattern_stmt);
3274 arguments.push(new_argument);
3277 let async_expr = this.make_async_expr(
3278 CaptureBy::Value, closure_id, None, body.span,
3280 let body = this.lower_block_with_stmts(body, false, statements);
3281 this.expr_block(body, ThinVec::new())
3283 (HirVec::from(arguments), this.expr(body.span, async_expr, ThinVec::new()))
3291 attrs: &hir::HirVec<Attribute>,
3292 vis: &mut hir::Visibility,
3294 ) -> hir::ItemKind {
3296 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
3297 ItemKind::Use(ref use_tree) => {
3298 // Start with an empty prefix.
3301 span: use_tree.span,
3304 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
3306 ItemKind::Static(ref t, m, ref e) => {
3307 hir::ItemKind::Static(
3310 if self.sess.features_untracked().impl_trait_in_bindings {
3311 ImplTraitContext::Existential(None)
3313 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3316 self.lower_mutability(m),
3317 self.lower_const_body(e),
3320 ItemKind::Const(ref t, ref e) => {
3321 hir::ItemKind::Const(
3324 if self.sess.features_untracked().impl_trait_in_bindings {
3325 ImplTraitContext::Existential(None)
3327 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3330 self.lower_const_body(e)
3333 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
3334 let fn_def_id = self.resolver.definitions().local_def_id(id);
3335 self.with_new_scopes(|this| {
3336 this.current_item = Some(ident.span);
3338 // Note: we don't need to change the return type from `T` to
3339 // `impl Future<Output = T>` here because lower_body
3340 // only cares about the input argument patterns in the function
3341 // declaration (decl), not the return types.
3342 let body_id = this.lower_maybe_async_body(&decl, header.asyncness.node, body);
3344 let (generics, fn_decl) = this.add_in_band_defs(
3347 AnonymousLifetimeMode::PassThrough,
3348 |this, idty| this.lower_fn_decl(
3350 Some((fn_def_id, idty)),
3352 header.asyncness.node.opt_return_id()
3358 this.lower_fn_header(header),
3364 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
3365 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
3366 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
3367 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
3368 self.lower_ty(t, ImplTraitContext::disallowed()),
3369 self.lower_generics(generics, ImplTraitContext::disallowed()),
3371 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(
3373 generics: self.lower_generics(generics,
3374 ImplTraitContext::Existential(None)),
3375 bounds: self.lower_param_bounds(b,
3376 ImplTraitContext::Existential(None)),
3377 impl_trait_fn: None,
3378 origin: hir::ExistTyOrigin::ExistentialType,
3381 ItemKind::Enum(ref enum_definition, ref generics) => {
3382 hir::ItemKind::Enum(
3384 variants: enum_definition
3387 .map(|x| self.lower_variant(x))
3390 self.lower_generics(generics, ImplTraitContext::disallowed()),
3393 ItemKind::Struct(ref struct_def, ref generics) => {
3394 let struct_def = self.lower_variant_data(struct_def);
3395 hir::ItemKind::Struct(
3397 self.lower_generics(generics, ImplTraitContext::disallowed()),
3400 ItemKind::Union(ref vdata, ref generics) => {
3401 let vdata = self.lower_variant_data(vdata);
3402 hir::ItemKind::Union(
3404 self.lower_generics(generics, ImplTraitContext::disallowed()),
3416 let def_id = self.resolver.definitions().local_def_id(id);
3418 // Lower the "impl header" first. This ordering is important
3419 // for in-band lifetimes! Consider `'a` here:
3421 // impl Foo<'a> for u32 {
3422 // fn method(&'a self) { .. }
3425 // Because we start by lowering the `Foo<'a> for u32`
3426 // part, we will add `'a` to the list of generics on
3427 // the impl. When we then encounter it later in the
3428 // method, it will not be considered an in-band
3429 // lifetime to be added, but rather a reference to a
3431 let lowered_trait_impl_id = self.lower_node_id(id);
3432 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
3435 AnonymousLifetimeMode::CreateParameter,
3437 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
3438 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
3441 if let Some(ref trait_ref) = trait_ref {
3442 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
3443 this.trait_impls.entry(def_id).or_default().push(
3444 lowered_trait_impl_id);
3448 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
3450 (trait_ref, lowered_ty)
3454 let new_impl_items = self.with_in_scope_lifetime_defs(
3455 &ast_generics.params,
3459 .map(|item| this.lower_impl_item_ref(item))
3464 hir::ItemKind::Impl(
3465 self.lower_unsafety(unsafety),
3466 self.lower_impl_polarity(polarity),
3467 self.lower_defaultness(defaultness, true /* [1] */),
3474 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
3475 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
3478 .map(|item| self.lower_trait_item_ref(item))
3480 hir::ItemKind::Trait(
3481 self.lower_is_auto(is_auto),
3482 self.lower_unsafety(unsafety),
3483 self.lower_generics(generics, ImplTraitContext::disallowed()),
3488 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
3489 self.lower_generics(generics, ImplTraitContext::disallowed()),
3490 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3492 ItemKind::MacroDef(..)
3493 | ItemKind::Mac(..) => bug!("`TyMac` should have been expanded by now"),
3496 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
3497 // not cause an assertion failure inside the `lower_defaultness` function.
3505 vis: &mut hir::Visibility,
3507 attrs: &hir::HirVec<Attribute>,
3508 ) -> hir::ItemKind {
3509 debug!("lower_use_tree(tree={:?})", tree);
3510 debug!("lower_use_tree: vis = {:?}", vis);
3512 let path = &tree.prefix;
3513 let segments = prefix
3516 .chain(path.segments.iter())
3521 UseTreeKind::Simple(rename, id1, id2) => {
3522 *ident = tree.ident();
3524 // First, apply the prefix to the path.
3525 let mut path = Path {
3530 // Correctly resolve `self` imports.
3531 if path.segments.len() > 1
3532 && path.segments.last().unwrap().ident.name == kw::SelfLower
3534 let _ = path.segments.pop();
3535 if rename.is_none() {
3536 *ident = path.segments.last().unwrap().ident;
3540 let mut resolutions = self.expect_full_res_from_use(id);
3541 // We want to return *something* from this function, so hold onto the first item
3543 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
3545 // Here, we are looping over namespaces, if they exist for the definition
3546 // being imported. We only handle type and value namespaces because we
3547 // won't be dealing with macros in the rest of the compiler.
3548 // Essentially a single `use` which imports two names is desugared into
3550 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
3551 let vis = vis.clone();
3552 let ident = ident.clone();
3553 let mut path = path.clone();
3554 for seg in &mut path.segments {
3555 seg.id = self.sess.next_node_id();
3557 let span = path.span;
3559 self.with_hir_id_owner(new_node_id, |this| {
3560 let new_id = this.lower_node_id(new_node_id);
3561 let res = this.lower_res(res);
3563 this.lower_path_extra(res, &path, ParamMode::Explicit, None);
3564 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
3565 let vis_kind = match vis.node {
3566 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3567 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3568 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3569 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
3570 let path = this.renumber_segment_ids(path);
3571 hir::VisibilityKind::Restricted {
3573 hir_id: this.next_id(),
3577 let vis = respan(vis.span, vis_kind);
3583 attrs: attrs.clone(),
3593 P(self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None));
3594 hir::ItemKind::Use(path, hir::UseKind::Single)
3596 UseTreeKind::Glob => {
3597 let path = P(self.lower_path(
3603 ParamMode::Explicit,
3605 hir::ItemKind::Use(path, hir::UseKind::Glob)
3607 UseTreeKind::Nested(ref trees) => {
3608 // Nested imports are desugared into simple imports.
3609 // So, if we start with
3612 // pub(x) use foo::{a, b};
3615 // we will create three items:
3618 // pub(x) use foo::a;
3619 // pub(x) use foo::b;
3620 // pub(x) use foo::{}; // <-- this is called the `ListStem`
3623 // The first two are produced by recursively invoking
3624 // `lower_use_tree` (and indeed there may be things
3625 // like `use foo::{a::{b, c}}` and so forth). They
3626 // wind up being directly added to
3627 // `self.items`. However, the structure of this
3628 // function also requires us to return one item, and
3629 // for that we return the `{}` import (called the
3634 span: prefix.span.to(path.span),
3637 // Add all the nested `PathListItem`s to the HIR.
3638 for &(ref use_tree, id) in trees {
3639 let new_hir_id = self.lower_node_id(id);
3641 let mut vis = vis.clone();
3642 let mut ident = ident.clone();
3643 let mut prefix = prefix.clone();
3645 // Give the segments new node-ids since they are being cloned.
3646 for seg in &mut prefix.segments {
3647 seg.id = self.sess.next_node_id();
3650 // Each `use` import is an item and thus are owners of the
3651 // names in the path. Up to this point the nested import is
3652 // the current owner, since we want each desugared import to
3653 // own its own names, we have to adjust the owner before
3654 // lowering the rest of the import.
3655 self.with_hir_id_owner(id, |this| {
3656 let item = this.lower_use_tree(use_tree,
3663 let vis_kind = match vis.node {
3664 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3665 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3666 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3667 hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
3668 let path = this.renumber_segment_ids(path);
3669 hir::VisibilityKind::Restricted {
3671 hir_id: this.next_id(),
3675 let vis = respan(vis.span, vis_kind);
3681 attrs: attrs.clone(),
3684 span: use_tree.span,
3690 // Subtle and a bit hacky: we lower the privacy level
3691 // of the list stem to "private" most of the time, but
3692 // not for "restricted" paths. The key thing is that
3693 // we don't want it to stay as `pub` (with no caveats)
3694 // because that affects rustdoc and also the lints
3695 // about `pub` items. But we can't *always* make it
3696 // private -- particularly not for restricted paths --
3697 // because it contains node-ids that would then be
3698 // unused, failing the check that HirIds are "densely
3701 hir::VisibilityKind::Public |
3702 hir::VisibilityKind::Crate(_) |
3703 hir::VisibilityKind::Inherited => {
3704 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3706 hir::VisibilityKind::Restricted { .. } => {
3707 // Do nothing here, as described in the comment on the match.
3711 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
3712 let res = self.lower_res(res);
3713 let path = P(self.lower_path_extra(res, &prefix, ParamMode::Explicit, None));
3714 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3719 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
3720 /// many times in the HIR tree; for each occurrence, we need to assign distinct
3721 /// `NodeId`s. (See, e.g., #56128.)
3722 fn renumber_segment_ids(&mut self, path: &P<hir::Path>) -> P<hir::Path> {
3723 debug!("renumber_segment_ids(path = {:?})", path);
3724 let mut path = path.clone();
3725 for seg in path.segments.iter_mut() {
3726 if seg.hir_id.is_some() {
3727 seg.hir_id = Some(self.next_id());
3733 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3734 let trait_item_def_id = self.resolver.definitions().local_def_id(i.id);
3736 let (generics, node) = match i.node {
3737 TraitItemKind::Const(ref ty, ref default) => (
3738 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3739 hir::TraitItemKind::Const(
3740 self.lower_ty(ty, ImplTraitContext::disallowed()),
3743 .map(|x| self.lower_const_body(x)),
3746 TraitItemKind::Method(ref sig, None) => {
3747 let names = self.lower_fn_args_to_names(&sig.decl);
3748 let (generics, sig) = self.lower_method_sig(
3755 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3757 TraitItemKind::Method(ref sig, Some(ref body)) => {
3758 let body_id = self.lower_fn_body(&sig.decl, |this| {
3759 let body = this.lower_block(body, false);
3760 this.expr_block(body, ThinVec::new())
3762 let (generics, sig) = self.lower_method_sig(
3769 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3771 TraitItemKind::Type(ref bounds, ref default) => {
3772 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
3773 let node = hir::TraitItemKind::Type(
3774 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3777 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3782 TraitItemKind::Macro(..) => bug!("macro item shouldn't exist at this point"),
3786 hir_id: self.lower_node_id(i.id),
3788 attrs: self.lower_attrs(&i.attrs),
3795 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3796 let (kind, has_default) = match i.node {
3797 TraitItemKind::Const(_, ref default) => {
3798 (hir::AssocItemKind::Const, default.is_some())
3800 TraitItemKind::Type(_, ref default) => {
3801 (hir::AssocItemKind::Type, default.is_some())
3803 TraitItemKind::Method(ref sig, ref default) => (
3804 hir::AssocItemKind::Method {
3805 has_self: sig.decl.has_self(),
3809 TraitItemKind::Macro(..) => unimplemented!(),
3812 id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) },
3815 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3820 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3821 let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
3823 let (generics, node) = match i.node {
3824 ImplItemKind::Const(ref ty, ref expr) => (
3825 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3826 hir::ImplItemKind::Const(
3827 self.lower_ty(ty, ImplTraitContext::disallowed()),
3828 self.lower_const_body(expr),
3831 ImplItemKind::Method(ref sig, ref body) => {
3832 self.current_item = Some(i.span);
3833 let body_id = self.lower_maybe_async_body(
3834 &sig.decl, sig.header.asyncness.node, body
3836 let impl_trait_return_allow = !self.is_in_trait_impl;
3837 let (generics, sig) = self.lower_method_sig(
3841 impl_trait_return_allow,
3842 sig.header.asyncness.node.opt_return_id(),
3845 (generics, hir::ImplItemKind::Method(sig, body_id))
3847 ImplItemKind::Type(ref ty) => (
3848 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3849 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3851 ImplItemKind::Existential(ref bounds) => (
3852 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3853 hir::ImplItemKind::Existential(
3854 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3857 ImplItemKind::Macro(..) => bug!("`TyMac` should have been expanded by now"),
3861 hir_id: self.lower_node_id(i.id),
3863 attrs: self.lower_attrs(&i.attrs),
3865 vis: self.lower_visibility(&i.vis, None),
3866 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3871 // [1] since `default impl` is not yet implemented, this is always true in impls
3874 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3876 id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
3879 vis: self.lower_visibility(&i.vis, Some(i.id)),
3880 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3881 kind: match i.node {
3882 ImplItemKind::Const(..) => hir::AssocItemKind::Const,
3883 ImplItemKind::Type(..) => hir::AssocItemKind::Type,
3884 ImplItemKind::Existential(..) => hir::AssocItemKind::Existential,
3885 ImplItemKind::Method(ref sig, _) => hir::AssocItemKind::Method {
3886 has_self: sig.decl.has_self(),
3888 ImplItemKind::Macro(..) => unimplemented!(),
3892 // [1] since `default impl` is not yet implemented, this is always true in impls
3895 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3898 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3902 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3903 let node_ids = match i.node {
3904 ItemKind::Use(ref use_tree) => {
3905 let mut vec = smallvec![i.id];
3906 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3909 ItemKind::MacroDef(..) => SmallVec::new(),
3911 ItemKind::Impl(.., None, _, _) => smallvec![i.id],
3912 ItemKind::Static(ref ty, ..) => {
3913 let mut ids = smallvec![i.id];
3914 if self.sess.features_untracked().impl_trait_in_bindings {
3915 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3916 visitor.visit_ty(ty);
3920 ItemKind::Const(ref ty, ..) => {
3921 let mut ids = smallvec![i.id];
3922 if self.sess.features_untracked().impl_trait_in_bindings {
3923 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3924 visitor.visit_ty(ty);
3928 _ => smallvec![i.id],
3931 node_ids.into_iter().map(|node_id| hir::ItemId {
3932 id: self.allocate_hir_id_counter(node_id)
3936 fn lower_item_id_use_tree(&mut self,
3939 vec: &mut SmallVec<[NodeId; 1]>)
3942 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3944 self.lower_item_id_use_tree(nested, id, vec);
3946 UseTreeKind::Glob => {}
3947 UseTreeKind::Simple(_, id1, id2) => {
3948 for (_, &id) in self.expect_full_res_from_use(base_id)
3950 .zip([id1, id2].iter())
3958 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3959 let mut ident = i.ident;
3960 let mut vis = self.lower_visibility(&i.vis, None);
3961 let attrs = self.lower_attrs(&i.attrs);
3962 if let ItemKind::MacroDef(ref def) = i.node {
3963 if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) ||
3964 attr::contains_name(&i.attrs, sym::rustc_doc_only_macro) {
3965 let body = self.lower_token_stream(def.stream());
3966 let hir_id = self.lower_node_id(i.id);
3967 self.exported_macros.push(hir::MacroDef {
3980 let node = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.node);
3983 hir_id: self.lower_node_id(i.id),
3992 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3993 let def_id = self.resolver.definitions().local_def_id(i.id);
3995 hir_id: self.lower_node_id(i.id),
3997 attrs: self.lower_attrs(&i.attrs),
3998 node: match i.node {
3999 ForeignItemKind::Fn(ref fdec, ref generics) => {
4000 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
4003 AnonymousLifetimeMode::PassThrough,
4006 // Disallow impl Trait in foreign items
4007 this.lower_fn_decl(fdec, None, false, None),
4008 this.lower_fn_args_to_names(fdec),
4013 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
4015 ForeignItemKind::Static(ref t, m) => {
4016 hir::ForeignItemKind::Static(
4017 self.lower_ty(t, ImplTraitContext::disallowed()), self.lower_mutability(m))
4019 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
4020 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
4022 vis: self.lower_visibility(&i.vis, None),
4027 fn lower_method_sig(
4029 generics: &Generics,
4032 impl_trait_return_allow: bool,
4033 is_async: Option<NodeId>,
4034 ) -> (hir::Generics, hir::MethodSig) {
4035 let header = self.lower_fn_header(sig.header);
4036 let (generics, decl) = self.add_in_band_defs(
4039 AnonymousLifetimeMode::PassThrough,
4040 |this, idty| this.lower_fn_decl(
4042 Some((fn_def_id, idty)),
4043 impl_trait_return_allow,
4047 (generics, hir::MethodSig { header, decl })
4050 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
4052 IsAuto::Yes => hir::IsAuto::Yes,
4053 IsAuto::No => hir::IsAuto::No,
4057 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
4059 unsafety: self.lower_unsafety(h.unsafety),
4060 asyncness: self.lower_asyncness(h.asyncness.node),
4061 constness: self.lower_constness(h.constness),
4066 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
4068 Unsafety::Unsafe => hir::Unsafety::Unsafe,
4069 Unsafety::Normal => hir::Unsafety::Normal,
4073 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
4075 Constness::Const => hir::Constness::Const,
4076 Constness::NotConst => hir::Constness::NotConst,
4080 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
4082 IsAsync::Async { .. } => hir::IsAsync::Async,
4083 IsAsync::NotAsync => hir::IsAsync::NotAsync,
4087 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
4089 UnOp::Deref => hir::UnDeref,
4090 UnOp::Not => hir::UnNot,
4091 UnOp::Neg => hir::UnNeg,
4095 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
4097 node: match b.node {
4098 BinOpKind::Add => hir::BinOpKind::Add,
4099 BinOpKind::Sub => hir::BinOpKind::Sub,
4100 BinOpKind::Mul => hir::BinOpKind::Mul,
4101 BinOpKind::Div => hir::BinOpKind::Div,
4102 BinOpKind::Rem => hir::BinOpKind::Rem,
4103 BinOpKind::And => hir::BinOpKind::And,
4104 BinOpKind::Or => hir::BinOpKind::Or,
4105 BinOpKind::BitXor => hir::BinOpKind::BitXor,
4106 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
4107 BinOpKind::BitOr => hir::BinOpKind::BitOr,
4108 BinOpKind::Shl => hir::BinOpKind::Shl,
4109 BinOpKind::Shr => hir::BinOpKind::Shr,
4110 BinOpKind::Eq => hir::BinOpKind::Eq,
4111 BinOpKind::Lt => hir::BinOpKind::Lt,
4112 BinOpKind::Le => hir::BinOpKind::Le,
4113 BinOpKind::Ne => hir::BinOpKind::Ne,
4114 BinOpKind::Ge => hir::BinOpKind::Ge,
4115 BinOpKind::Gt => hir::BinOpKind::Gt,
4121 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
4122 let node = match p.node {
4123 PatKind::Wild => hir::PatKind::Wild,
4124 PatKind::Ident(ref binding_mode, ident, ref sub) => {
4125 match self.resolver.get_partial_res(p.id).map(|d| d.base_res()) {
4126 // `None` can occur in body-less function signatures
4127 res @ None | res @ Some(Res::Local(_)) => {
4128 let canonical_id = match res {
4129 Some(Res::Local(id)) => id,
4133 hir::PatKind::Binding(
4134 self.lower_binding_mode(binding_mode),
4135 self.lower_node_id(canonical_id),
4137 sub.as_ref().map(|x| self.lower_pat(x)),
4140 Some(res) => hir::PatKind::Path(hir::QPath::Resolved(
4144 res: self.lower_res(res),
4145 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4150 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
4151 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
4152 let qpath = self.lower_qpath(
4156 ParamMode::Optional,
4157 ImplTraitContext::disallowed(),
4159 hir::PatKind::TupleStruct(
4161 pats.iter().map(|x| self.lower_pat(x)).collect(),
4165 PatKind::Path(ref qself, ref path) => {
4166 let qpath = self.lower_qpath(
4170 ParamMode::Optional,
4171 ImplTraitContext::disallowed(),
4173 hir::PatKind::Path(qpath)
4175 PatKind::Struct(ref path, ref fields, etc) => {
4176 let qpath = self.lower_qpath(
4180 ParamMode::Optional,
4181 ImplTraitContext::disallowed(),
4189 node: hir::FieldPat {
4190 hir_id: self.next_id(),
4191 ident: f.node.ident,
4192 pat: self.lower_pat(&f.node.pat),
4193 is_shorthand: f.node.is_shorthand,
4198 hir::PatKind::Struct(qpath, fs, etc)
4200 PatKind::Tuple(ref elts, ddpos) => {
4201 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
4203 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
4204 PatKind::Ref(ref inner, mutbl) => {
4205 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
4207 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
4208 P(self.lower_expr(e1)),
4209 P(self.lower_expr(e2)),
4210 self.lower_range_end(end),
4212 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
4213 before.iter().map(|x| self.lower_pat(x)).collect(),
4214 slice.as_ref().map(|x| self.lower_pat(x)),
4215 after.iter().map(|x| self.lower_pat(x)).collect(),
4217 PatKind::Paren(ref inner) => return self.lower_pat(inner),
4218 PatKind::Mac(_) => panic!("Shouldn't exist here"),
4222 hir_id: self.lower_node_id(p.id),
4228 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
4230 RangeEnd::Included(_) => hir::RangeEnd::Included,
4231 RangeEnd::Excluded => hir::RangeEnd::Excluded,
4235 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
4236 self.with_new_scopes(|this| {
4238 hir_id: this.lower_node_id(c.id),
4239 body: this.lower_const_body(&c.value),
4244 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
4245 let kind = match e.node {
4246 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
4247 ExprKind::Array(ref exprs) => {
4248 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
4250 ExprKind::Repeat(ref expr, ref count) => {
4251 let expr = P(self.lower_expr(expr));
4252 let count = self.lower_anon_const(count);
4253 hir::ExprKind::Repeat(expr, count)
4255 ExprKind::Tup(ref elts) => {
4256 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
4258 ExprKind::Call(ref f, ref args) => {
4259 let f = P(self.lower_expr(f));
4260 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
4262 ExprKind::MethodCall(ref seg, ref args) => {
4263 let hir_seg = P(self.lower_path_segment(
4266 ParamMode::Optional,
4268 ParenthesizedGenericArgs::Err,
4269 ImplTraitContext::disallowed(),
4272 let args = args.iter().map(|x| self.lower_expr(x)).collect();
4273 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
4275 ExprKind::Binary(binop, ref lhs, ref rhs) => {
4276 let binop = self.lower_binop(binop);
4277 let lhs = P(self.lower_expr(lhs));
4278 let rhs = P(self.lower_expr(rhs));
4279 hir::ExprKind::Binary(binop, lhs, rhs)
4281 ExprKind::Unary(op, ref ohs) => {
4282 let op = self.lower_unop(op);
4283 let ohs = P(self.lower_expr(ohs));
4284 hir::ExprKind::Unary(op, ohs)
4286 ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.node.clone())),
4287 ExprKind::Cast(ref expr, ref ty) => {
4288 let expr = P(self.lower_expr(expr));
4289 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4291 ExprKind::Type(ref expr, ref ty) => {
4292 let expr = P(self.lower_expr(expr));
4293 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4295 ExprKind::AddrOf(m, ref ohs) => {
4296 let m = self.lower_mutability(m);
4297 let ohs = P(self.lower_expr(ohs));
4298 hir::ExprKind::AddrOf(m, ohs)
4300 // More complicated than you might expect because the else branch
4301 // might be `if let`.
4302 ExprKind::If(ref cond, ref then, ref else_opt) => {
4304 let then_pat = self.pat_bool(e.span, true);
4305 let then_blk = self.lower_block(then, false);
4306 let then_expr = self.expr_block(then_blk, ThinVec::new());
4307 let then_arm = self.arm(hir_vec![then_pat], P(then_expr));
4309 // `_ => else_block` where `else_block` is `{}` if there's `None`:
4310 let else_pat = self.pat_wild(e.span);
4311 let else_expr = match else_opt {
4312 None => self.expr_block_empty(e.span),
4313 Some(els) => match els.node {
4314 ExprKind::IfLet(..) => {
4315 // Wrap the `if let` expr in a block.
4316 let els = self.lower_expr(els);
4317 let blk = self.block_all(els.span, hir_vec![], Some(P(els)));
4318 self.expr_block(P(blk), ThinVec::new())
4320 _ => self.lower_expr(els),
4323 let else_arm = self.arm(hir_vec![else_pat], P(else_expr));
4326 let span_block = self.mark_span_with_reason(IfTemporary, cond.span, None);
4327 let cond = self.lower_expr(cond);
4328 // Wrap in a construct equivalent to `{ let _t = $cond; _t }` to preserve drop
4329 // semantics since `if cond { ... }` don't let temporaries live outside of `cond`.
4330 let cond = self.expr_drop_temps(span_block, P(cond), ThinVec::new());
4332 hir::ExprKind::Match(
4334 vec![then_arm, else_arm].into(),
4335 hir::MatchSource::IfDesugar {
4336 contains_else_clause: else_opt.is_some()
4340 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4341 hir::ExprKind::While(
4342 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
4343 this.lower_block(body, false),
4344 this.lower_label(opt_label),
4347 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4348 hir::ExprKind::Loop(
4349 this.lower_block(body, false),
4350 this.lower_label(opt_label),
4351 hir::LoopSource::Loop,
4354 ExprKind::TryBlock(ref body) => {
4355 self.with_catch_scope(body.id, |this| {
4356 let unstable_span = this.mark_span_with_reason(
4357 CompilerDesugaringKind::TryBlock,
4359 Some(vec![sym::try_trait].into()),
4361 let mut block = this.lower_block(body, true).into_inner();
4362 let tail = block.expr.take().map_or_else(
4364 let span = this.sess.source_map().end_point(unstable_span);
4367 node: hir::ExprKind::Tup(hir_vec![]),
4368 attrs: ThinVec::new(),
4369 hir_id: this.next_id(),
4372 |x: P<hir::Expr>| x.into_inner(),
4374 block.expr = Some(this.wrap_in_try_constructor(
4375 sym::from_ok, tail, unstable_span));
4376 hir::ExprKind::Block(P(block), None)
4379 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
4380 P(self.lower_expr(expr)),
4381 arms.iter().map(|x| self.lower_arm(x)).collect(),
4382 hir::MatchSource::Normal,
4384 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
4385 self.make_async_expr(capture_clause, closure_node_id, None, block.span, |this| {
4386 this.with_new_scopes(|this| {
4387 let block = this.lower_block(block, false);
4388 this.expr_block(block, ThinVec::new())
4392 ExprKind::Await(_origin, ref expr) => self.lower_await(e.span, expr),
4394 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
4396 if let IsAsync::Async { closure_id, .. } = asyncness {
4397 let outer_decl = FnDecl {
4398 inputs: decl.inputs.clone(),
4399 output: FunctionRetTy::Default(fn_decl_span),
4402 // We need to lower the declaration outside the new scope, because we
4403 // have to conserve the state of being inside a loop condition for the
4404 // closure argument types.
4405 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
4407 self.with_new_scopes(|this| {
4408 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
4409 if capture_clause == CaptureBy::Ref &&
4410 !decl.inputs.is_empty()
4416 "`async` non-`move` closures with arguments \
4417 are not currently supported",
4419 .help("consider using `let` statements to manually capture \
4420 variables by reference before entering an \
4421 `async move` closure")
4425 // Transform `async |x: u8| -> X { ... }` into
4426 // `|x: u8| future_from_generator(|| -> X { ... })`.
4427 let body_id = this.lower_fn_body(&outer_decl, |this| {
4428 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
4431 let async_body = this.make_async_expr(
4432 capture_clause, closure_id, async_ret_ty, body.span,
4434 this.with_new_scopes(|this| this.lower_expr(body))
4436 this.expr(fn_decl_span, async_body, ThinVec::new())
4438 hir::ExprKind::Closure(
4439 this.lower_capture_clause(capture_clause),
4447 // Lower outside new scope to preserve `is_in_loop_condition`.
4448 let fn_decl = self.lower_fn_decl(decl, None, false, None);
4450 self.with_new_scopes(|this| {
4451 this.current_item = Some(fn_decl_span);
4452 let mut is_generator = false;
4453 let body_id = this.lower_fn_body(decl, |this| {
4454 let e = this.lower_expr(body);
4455 is_generator = this.is_generator;
4458 let generator_option = if is_generator {
4459 if !decl.inputs.is_empty() {
4464 "generators cannot have explicit arguments"
4466 this.sess.abort_if_errors();
4468 Some(match movability {
4469 Movability::Movable => hir::GeneratorMovability::Movable,
4470 Movability::Static => hir::GeneratorMovability::Static,
4473 if movability == Movability::Static {
4478 "closures cannot be static"
4483 hir::ExprKind::Closure(
4484 this.lower_capture_clause(capture_clause),
4493 ExprKind::Block(ref blk, opt_label) => {
4494 hir::ExprKind::Block(self.lower_block(blk,
4495 opt_label.is_some()),
4496 self.lower_label(opt_label))
4498 ExprKind::Assign(ref el, ref er) => {
4499 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
4501 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
4502 self.lower_binop(op),
4503 P(self.lower_expr(el)),
4504 P(self.lower_expr(er)),
4506 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
4507 ExprKind::Index(ref el, ref er) => {
4508 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
4510 // Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
4511 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
4512 let id = self.next_id();
4513 let e1 = self.lower_expr(e1);
4514 let e2 = self.lower_expr(e2);
4515 self.expr_call_std_assoc_fn(
4518 &[sym::ops, sym::RangeInclusive],
4523 ExprKind::Range(ref e1, ref e2, lims) => {
4524 use syntax::ast::RangeLimits::*;
4526 let path = match (e1, e2, lims) {
4527 (&None, &None, HalfOpen) => sym::RangeFull,
4528 (&Some(..), &None, HalfOpen) => sym::RangeFrom,
4529 (&None, &Some(..), HalfOpen) => sym::RangeTo,
4530 (&Some(..), &Some(..), HalfOpen) => sym::Range,
4531 (&None, &Some(..), Closed) => sym::RangeToInclusive,
4532 (&Some(..), &Some(..), Closed) => unreachable!(),
4533 (_, &None, Closed) => self.diagnostic()
4534 .span_fatal(e.span, "inclusive range with no end")
4538 let fields = e1.iter()
4539 .map(|e| ("start", e))
4540 .chain(e2.iter().map(|e| ("end", e)))
4542 let expr = P(self.lower_expr(&e));
4543 let ident = Ident::new(Symbol::intern(s), e.span);
4544 self.field(ident, expr, e.span)
4546 .collect::<P<[hir::Field]>>();
4548 let is_unit = fields.is_empty();
4549 let struct_path = [sym::ops, path];
4550 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
4551 let struct_path = hir::QPath::Resolved(None, P(struct_path));
4554 hir_id: self.lower_node_id(e.id),
4556 hir::ExprKind::Path(struct_path)
4558 hir::ExprKind::Struct(P(struct_path), fields, None)
4561 attrs: e.attrs.clone(),
4564 ExprKind::Path(ref qself, ref path) => {
4565 let qpath = self.lower_qpath(
4569 ParamMode::Optional,
4570 ImplTraitContext::disallowed(),
4572 hir::ExprKind::Path(qpath)
4574 ExprKind::Break(opt_label, ref opt_expr) => {
4575 let destination = if self.is_in_loop_condition && opt_label.is_none() {
4578 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4581 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4583 hir::ExprKind::Break(
4585 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
4588 ExprKind::Continue(opt_label) => {
4589 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
4592 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4595 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4598 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
4599 ExprKind::InlineAsm(ref asm) => {
4600 let hir_asm = hir::InlineAsm {
4601 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
4602 outputs: asm.outputs
4604 .map(|out| hir::InlineAsmOutput {
4605 constraint: out.constraint.clone(),
4607 is_indirect: out.is_indirect,
4608 span: out.expr.span,
4611 asm: asm.asm.clone(),
4612 asm_str_style: asm.asm_str_style,
4613 clobbers: asm.clobbers.clone().into(),
4614 volatile: asm.volatile,
4615 alignstack: asm.alignstack,
4616 dialect: asm.dialect,
4619 let outputs = asm.outputs
4621 .map(|out| self.lower_expr(&out.expr))
4623 let inputs = asm.inputs
4625 .map(|&(_, ref input)| self.lower_expr(input))
4627 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
4629 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4634 ParamMode::Optional,
4635 ImplTraitContext::disallowed(),
4637 fields.iter().map(|x| self.lower_field(x)).collect(),
4638 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4640 ExprKind::Paren(ref ex) => {
4641 let mut ex = self.lower_expr(ex);
4642 // Include parens in span, but only if it is a super-span.
4643 if e.span.contains(ex.span) {
4646 // Merge attributes into the inner expression.
4647 let mut attrs = e.attrs.clone();
4648 attrs.extend::<Vec<_>>(ex.attrs.into());
4653 ExprKind::Yield(ref opt_expr) => {
4654 self.is_generator = true;
4657 .map(|x| self.lower_expr(x))
4658 .unwrap_or_else(|| self.expr_unit(e.span));
4659 hir::ExprKind::Yield(P(expr))
4662 ExprKind::Err => hir::ExprKind::Err,
4664 // Desugar `ExprIfLet`
4665 // from: `if let <pat> = <sub_expr> <body> [<else_opt>]`
4666 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4669 // match <sub_expr> {
4671 // _ => [<else_opt> | ()]
4674 let mut arms = vec![];
4676 // `<pat> => <body>`
4678 let body = self.lower_block(body, false);
4679 let body_expr = P(self.expr_block(body, ThinVec::new()));
4680 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4681 arms.push(self.arm(pats, body_expr));
4684 // _ => [<else_opt>|{}]
4686 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4687 let wildcard_pattern = self.pat_wild(e.span);
4688 let body = if let Some(else_expr) = wildcard_arm {
4689 self.lower_expr(else_expr)
4691 self.expr_block_empty(e.span)
4693 arms.push(self.arm(hir_vec![wildcard_pattern], P(body)));
4696 let contains_else_clause = else_opt.is_some();
4698 let sub_expr = P(self.lower_expr(sub_expr));
4700 hir::ExprKind::Match(
4703 hir::MatchSource::IfLetDesugar {
4704 contains_else_clause,
4709 // Desugar `ExprWhileLet`
4710 // from: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4711 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4714 // [opt_ident]: loop {
4715 // match <sub_expr> {
4721 // Note that the block AND the condition are evaluated in the loop scope.
4722 // This is done to allow `break` from inside the condition of the loop.
4723 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4725 this.lower_block(body, false),
4726 this.expr_break(e.span, ThinVec::new()),
4727 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4731 // `<pat> => <body>`
4733 let body_expr = P(self.expr_block(body, ThinVec::new()));
4734 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4735 self.arm(pats, body_expr)
4740 let pat_under = self.pat_wild(e.span);
4741 self.arm(hir_vec![pat_under], break_expr)
4744 // `match <sub_expr> { ... }`
4745 let arms = hir_vec![pat_arm, break_arm];
4746 let match_expr = self.expr(
4748 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4752 // `[opt_ident]: loop { ... }`
4753 let loop_block = P(self.block_expr(P(match_expr)));
4754 let loop_expr = hir::ExprKind::Loop(
4756 self.lower_label(opt_label),
4757 hir::LoopSource::WhileLet,
4759 // Add attributes to the outer returned expr node.
4763 // Desugar `ExprForLoop`
4764 // from: `[opt_ident]: for <pat> in <head> <body>`
4765 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4769 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4771 // [opt_ident]: loop {
4773 // match ::std::iter::Iterator::next(&mut iter) {
4774 // ::std::option::Option::Some(val) => __next = val,
4775 // ::std::option::Option::None => break
4777 // let <pat> = __next;
4778 // StmtKind::Expr(<body>);
4786 let mut head = self.lower_expr(head);
4787 let head_sp = head.span;
4788 let desugared_span = self.mark_span_with_reason(
4789 CompilerDesugaringKind::ForLoop,
4793 head.span = desugared_span;
4795 let iter = Ident::with_empty_ctxt(sym::iter);
4797 let next_ident = Ident::with_empty_ctxt(sym::__next);
4798 let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
4801 hir::BindingAnnotation::Mutable,
4804 // `::std::option::Option::Some(val) => __next = val`
4806 let val_ident = Ident::with_empty_ctxt(sym::val);
4807 let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
4808 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat_hid));
4809 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat_hid));
4810 let assign = P(self.expr(
4812 hir::ExprKind::Assign(next_expr, val_expr),
4815 let some_pat = self.pat_some(pat.span, val_pat);
4816 self.arm(hir_vec![some_pat], assign)
4819 // `::std::option::Option::None => break`
4822 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4823 let pat = self.pat_none(e.span);
4824 self.arm(hir_vec![pat], break_expr)
4828 let (iter_pat, iter_pat_nid) = self.pat_ident_binding_mode(
4831 hir::BindingAnnotation::Mutable
4834 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4836 let iter = P(self.expr_ident(head_sp, iter, iter_pat_nid));
4837 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4838 let next_path = &[sym::iter, sym::Iterator, sym::next];
4839 let next_expr = P(self.expr_call_std_path(
4842 hir_vec![ref_mut_iter],
4844 let arms = hir_vec![pat_arm, break_arm];
4848 hir::ExprKind::Match(
4851 hir::MatchSource::ForLoopDesugar
4856 let match_stmt = self.stmt(head_sp, hir::StmtKind::Expr(match_expr));
4858 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat_hid));
4861 let next_let = self.stmt_let_pat(
4865 hir::LocalSource::ForLoopDesugar,
4868 // `let <pat> = __next`
4869 let pat = self.lower_pat(pat);
4870 let pat_let = self.stmt_let_pat(
4874 hir::LocalSource::ForLoopDesugar,
4877 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4878 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4879 let body_stmt = self.stmt(body.span, hir::StmtKind::Expr(body_expr));
4881 let loop_block = P(self.block_all(
4883 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4887 // `[opt_ident]: loop { ... }`
4888 let loop_expr = hir::ExprKind::Loop(
4890 self.lower_label(opt_label),
4891 hir::LoopSource::ForLoop,
4893 let loop_expr = P(hir::Expr {
4894 hir_id: self.lower_node_id(e.id),
4897 attrs: ThinVec::new(),
4900 // `mut iter => { ... }`
4901 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4903 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4904 let into_iter_expr = {
4905 let into_iter_path =
4906 &[sym::iter, sym::IntoIterator, sym::into_iter];
4907 P(self.expr_call_std_path(
4914 let match_expr = P(self.expr_match(
4918 hir::MatchSource::ForLoopDesugar,
4921 // This is effectively `{ let _result = ...; _result }`.
4922 // The construct was introduced in #21984.
4923 // FIXME(60253): Is this still necessary?
4924 // Also, add the attributes to the outer returned expr node.
4925 return self.expr_drop_temps(head_sp, match_expr, e.attrs.clone())
4928 // Desugar `ExprKind::Try`
4930 ExprKind::Try(ref sub_expr) => {
4933 // match Try::into_result(<expr>) {
4934 // Ok(val) => #[allow(unreachable_code)] val,
4935 // Err(err) => #[allow(unreachable_code)]
4936 // // If there is an enclosing `catch {...}`
4937 // break 'catch_target Try::from_error(From::from(err)),
4939 // return Try::from_error(From::from(err)),
4942 let unstable_span = self.mark_span_with_reason(
4943 CompilerDesugaringKind::QuestionMark,
4945 Some(vec![sym::try_trait].into()),
4947 let try_span = self.sess.source_map().end_point(e.span);
4948 let try_span = self.mark_span_with_reason(
4949 CompilerDesugaringKind::QuestionMark,
4951 Some(vec![sym::try_trait].into()),
4954 // `Try::into_result(<expr>)`
4957 let sub_expr = self.lower_expr(sub_expr);
4959 let path = &[sym::ops, sym::Try, sym::into_result];
4960 P(self.expr_call_std_path(
4967 // `#[allow(unreachable_code)]`
4969 // `allow(unreachable_code)`
4971 let allow_ident = Ident::with_empty_ctxt(sym::allow).with_span_pos(e.span);
4972 let uc_ident = Ident::with_empty_ctxt(sym::unreachable_code)
4973 .with_span_pos(e.span);
4974 let uc_nested = attr::mk_nested_word_item(uc_ident);
4975 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4977 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4979 let attrs = vec![attr];
4981 // `Ok(val) => #[allow(unreachable_code)] val,`
4983 let val_ident = Ident::with_empty_ctxt(sym::val);
4984 let (val_pat, val_pat_nid) = self.pat_ident(e.span, val_ident);
4985 let val_expr = P(self.expr_ident_with_attrs(
4989 ThinVec::from(attrs.clone()),
4991 let ok_pat = self.pat_ok(e.span, val_pat);
4993 self.arm(hir_vec![ok_pat], val_expr)
4996 // `Err(err) => #[allow(unreachable_code)]
4997 // return Try::from_error(From::from(err)),`
4999 let err_ident = Ident::with_empty_ctxt(sym::err);
5000 let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
5002 let from_path = &[sym::convert, sym::From, sym::from];
5003 let err_expr = self.expr_ident(try_span, err_ident, err_local_nid);
5004 self.expr_call_std_path(try_span, from_path, hir_vec![err_expr])
5007 self.wrap_in_try_constructor(sym::from_error, from_expr, unstable_span);
5008 let thin_attrs = ThinVec::from(attrs);
5009 let catch_scope = self.catch_scopes.last().map(|x| *x);
5010 let ret_expr = if let Some(catch_node) = catch_scope {
5011 let target_id = Ok(self.lower_node_id(catch_node));
5014 hir::ExprKind::Break(
5019 Some(from_err_expr),
5024 P(self.expr(try_span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
5027 let err_pat = self.pat_err(try_span, err_local);
5028 self.arm(hir_vec![err_pat], ret_expr)
5031 hir::ExprKind::Match(
5033 hir_vec![err_arm, ok_arm],
5034 hir::MatchSource::TryDesugar,
5038 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
5042 hir_id: self.lower_node_id(e.id),
5045 attrs: e.attrs.clone(),
5049 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
5050 smallvec![match s.node {
5051 StmtKind::Local(ref l) => {
5052 let (l, item_ids) = self.lower_local(l);
5053 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
5056 let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
5057 self.stmt(s.span, hir::StmtKind::Item(item_id))
5062 hir_id: self.lower_node_id(s.id),
5063 node: hir::StmtKind::Local(P(l)),
5069 StmtKind::Item(ref it) => {
5070 // Can only use the ID once.
5071 let mut id = Some(s.id);
5072 return self.lower_item_id(it)
5075 let hir_id = id.take()
5076 .map(|id| self.lower_node_id(id))
5077 .unwrap_or_else(|| self.next_id());
5081 node: hir::StmtKind::Item(item_id),
5087 StmtKind::Expr(ref e) => {
5089 hir_id: self.lower_node_id(s.id),
5090 node: hir::StmtKind::Expr(P(self.lower_expr(e))),
5094 StmtKind::Semi(ref e) => {
5096 hir_id: self.lower_node_id(s.id),
5097 node: hir::StmtKind::Semi(P(self.lower_expr(e))),
5101 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
5105 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
5107 CaptureBy::Value => hir::CaptureByValue,
5108 CaptureBy::Ref => hir::CaptureByRef,
5112 /// If an `explicit_owner` is given, this method allocates the `HirId` in
5113 /// the address space of that item instead of the item currently being
5114 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
5115 /// lower a `Visibility` value although we haven't lowered the owning
5116 /// `ImplItem` in question yet.
5117 fn lower_visibility(
5120 explicit_owner: Option<NodeId>,
5121 ) -> hir::Visibility {
5122 let node = match v.node {
5123 VisibilityKind::Public => hir::VisibilityKind::Public,
5124 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
5125 VisibilityKind::Restricted { ref path, id } => {
5126 debug!("lower_visibility: restricted path id = {:?}", id);
5127 let lowered_id = if let Some(owner) = explicit_owner {
5128 self.lower_node_id_with_owner(id, owner)
5130 self.lower_node_id(id)
5132 let res = self.expect_full_res(id);
5133 let res = self.lower_res(res);
5134 hir::VisibilityKind::Restricted {
5135 path: P(self.lower_path_extra(
5138 ParamMode::Explicit,
5144 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
5146 respan(v.span, node)
5149 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
5151 Defaultness::Default => hir::Defaultness::Default {
5152 has_value: has_value,
5154 Defaultness::Final => {
5156 hir::Defaultness::Final
5161 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
5163 BlockCheckMode::Default => hir::DefaultBlock,
5164 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
5168 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
5170 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
5171 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
5172 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
5173 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
5177 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
5179 CompilerGenerated => hir::CompilerGenerated,
5180 UserProvided => hir::UserProvided,
5184 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
5186 ImplPolarity::Positive => hir::ImplPolarity::Positive,
5187 ImplPolarity::Negative => hir::ImplPolarity::Negative,
5191 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
5193 TraitBoundModifier::None => hir::TraitBoundModifier::None,
5194 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
5198 // Helper methods for building HIR.
5200 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
5202 hir_id: self.next_id(),
5211 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
5213 hir_id: self.next_id(),
5217 is_shorthand: false,
5221 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
5222 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
5223 P(self.expr(span, expr_break, attrs))
5230 args: hir::HirVec<hir::Expr>,
5232 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
5235 // Note: associated functions must use `expr_call_std_path`.
5236 fn expr_call_std_path(
5239 path_components: &[Symbol],
5240 args: hir::HirVec<hir::Expr>,
5242 let path = P(self.expr_std_path(span, path_components, None, ThinVec::new()));
5243 self.expr_call(span, path, args)
5246 // Create an expression calling an associated function of an std type.
5248 // Associated functions cannot be resolved through the normal `std_path` function,
5249 // as they are resolved differently and so cannot use `expr_call_std_path`.
5251 // This function accepts the path component (`ty_path_components`) separately from
5252 // the name of the associated function (`assoc_fn_name`) in order to facilitate
5253 // separate resolution of the type and creation of a path referring to its associated
5255 fn expr_call_std_assoc_fn(
5257 ty_path_id: hir::HirId,
5259 ty_path_components: &[Symbol],
5260 assoc_fn_name: &str,
5261 args: hir::HirVec<hir::Expr>,
5262 ) -> hir::ExprKind {
5263 let ty_path = P(self.std_path(span, ty_path_components, None, false));
5264 let ty = P(self.ty_path(ty_path_id, span, hir::QPath::Resolved(None, ty_path)));
5265 let fn_seg = P(hir::PathSegment::from_ident(Ident::from_str(assoc_fn_name)));
5266 let fn_path = hir::QPath::TypeRelative(ty, fn_seg);
5267 let fn_expr = P(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
5268 hir::ExprKind::Call(fn_expr, args)
5271 fn expr_ident(&mut self, span: Span, ident: Ident, binding: hir::HirId) -> hir::Expr {
5272 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
5275 fn expr_ident_with_attrs(
5279 binding: hir::HirId,
5280 attrs: ThinVec<Attribute>,
5282 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
5286 res: Res::Local(binding),
5287 segments: hir_vec![hir::PathSegment::from_ident(ident)],
5291 self.expr(span, expr_path, attrs)
5294 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
5295 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
5301 components: &[Symbol],
5302 params: Option<P<hir::GenericArgs>>,
5303 attrs: ThinVec<Attribute>,
5305 let path = self.std_path(span, components, params, true);
5308 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
5313 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
5315 /// In terms of drop order, it has the same effect as wrapping `expr` in
5316 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
5318 /// The drop order can be important in e.g. `if expr { .. }`.
5323 attrs: ThinVec<Attribute>
5325 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
5332 arms: hir::HirVec<hir::Arm>,
5333 source: hir::MatchSource,
5335 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
5338 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
5339 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
5342 fn expr_unit(&mut self, sp: Span) -> hir::Expr {
5343 self.expr_tuple(sp, hir_vec![])
5346 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> hir::Expr {
5347 self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new())
5350 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
5352 hir_id: self.next_id(),
5359 fn stmt(&mut self, span: Span, node: hir::StmtKind) -> hir::Stmt {
5360 hir::Stmt { span, node, hir_id: self.next_id() }
5366 init: Option<P<hir::Expr>>,
5368 source: hir::LocalSource,
5370 let local = hir::Local {
5374 hir_id: self.next_id(),
5377 attrs: ThinVec::new()
5379 self.stmt(span, hir::StmtKind::Local(P(local)))
5382 fn expr_block_empty(&mut self, span: Span) -> hir::Expr {
5383 let blk = self.block_all(span, hir_vec![], None);
5384 self.expr_block(P(blk), ThinVec::new())
5387 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
5388 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
5394 stmts: hir::HirVec<hir::Stmt>,
5395 expr: Option<P<hir::Expr>>,
5400 hir_id: self.next_id(),
5401 rules: hir::DefaultBlock,
5403 targeted_by_break: false,
5407 fn expr_unsafe(&mut self, expr: P<hir::Expr>) -> hir::Expr {
5408 let hir_id = self.next_id();
5409 let span = expr.span;
5412 hir::ExprKind::Block(P(hir::Block {
5416 rules: hir::UnsafeBlock(hir::CompilerGenerated),
5418 targeted_by_break: false,
5424 /// Constructs a `true` or `false` literal pattern.
5425 fn pat_bool(&mut self, span: Span, val: bool) -> P<hir::Pat> {
5426 let lit = Spanned { span, node: LitKind::Bool(val) };
5427 let expr = self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new());
5428 self.pat(span, hir::PatKind::Lit(P(expr)))
5431 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5432 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![pat])
5435 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5436 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![pat])
5439 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5440 self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![pat])
5443 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
5444 self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], hir_vec![])
5450 components: &[Symbol],
5451 subpats: hir::HirVec<P<hir::Pat>>,
5453 let path = self.std_path(span, components, None, true);
5454 let qpath = hir::QPath::Resolved(None, P(path));
5455 let pt = if subpats.is_empty() {
5456 hir::PatKind::Path(qpath)
5458 hir::PatKind::TupleStruct(qpath, subpats, None)
5463 fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<hir::Pat>, hir::HirId) {
5464 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
5467 fn pat_ident_binding_mode(
5471 bm: hir::BindingAnnotation,
5472 ) -> (P<hir::Pat>, hir::HirId) {
5473 let hir_id = self.next_id();
5478 node: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
5485 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
5486 self.pat(span, hir::PatKind::Wild)
5489 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
5491 hir_id: self.next_id(),
5497 /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when
5498 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
5499 /// The path is also resolved according to `is_value`.
5503 components: &[Symbol],
5504 params: Option<P<hir::GenericArgs>>,
5507 let mut path = self.resolver
5508 .resolve_str_path(span, self.crate_root, components, is_value);
5509 path.segments.last_mut().unwrap().args = params;
5511 for seg in path.segments.iter_mut() {
5512 if seg.hir_id.is_some() {
5513 seg.hir_id = Some(self.next_id());
5519 fn ty_path(&mut self, mut hir_id: hir::HirId, span: Span, qpath: hir::QPath) -> hir::Ty {
5520 let node = match qpath {
5521 hir::QPath::Resolved(None, path) => {
5522 // Turn trait object paths into `TyKind::TraitObject` instead.
5524 Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
5525 let principal = hir::PolyTraitRef {
5526 bound_generic_params: hir::HirVec::new(),
5527 trait_ref: hir::TraitRef {
5528 path: path.and_then(|path| path),
5534 // The original ID is taken by the `PolyTraitRef`,
5535 // so the `Ty` itself needs a different one.
5536 hir_id = self.next_id();
5537 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
5539 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
5542 _ => hir::TyKind::Path(qpath),
5551 /// Invoked to create the lifetime argument for a type `&T`
5552 /// with no explicit lifetime.
5553 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
5554 match self.anonymous_lifetime_mode {
5555 // Intercept when we are in an impl header or async fn and introduce an in-band
5557 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
5559 AnonymousLifetimeMode::CreateParameter => {
5560 let fresh_name = self.collect_fresh_in_band_lifetime(span);
5562 hir_id: self.next_id(),
5564 name: hir::LifetimeName::Param(fresh_name),
5568 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5570 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5572 AnonymousLifetimeMode::Replace(replacement) => {
5573 self.new_replacement_lifetime(replacement, span)
5578 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
5579 /// return a "error lifetime".
5580 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
5581 let (id, msg, label) = match id {
5582 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
5585 self.sess.next_node_id(),
5586 "`&` without an explicit lifetime name cannot be used here",
5587 "explicit lifetime name needed here",
5591 let mut err = struct_span_err!(
5598 err.span_label(span, label);
5601 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5604 /// Invoked to create the lifetime argument(s) for a path like
5605 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
5606 /// sorts of cases are deprecated. This may therefore report a warning or an
5607 /// error, depending on the mode.
5608 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
5610 .map(|_| self.elided_path_lifetime(span))
5614 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
5615 match self.anonymous_lifetime_mode {
5616 AnonymousLifetimeMode::CreateParameter => {
5617 // We should have emitted E0726 when processing this path above
5618 self.sess.delay_span_bug(
5620 "expected 'implicit elided lifetime not allowed' error",
5622 let id = self.sess.next_node_id();
5623 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5625 // This is the normal case.
5626 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5628 AnonymousLifetimeMode::Replace(replacement) => {
5629 self.new_replacement_lifetime(replacement, span)
5632 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5636 /// Invoked to create the lifetime argument(s) for an elided trait object
5637 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
5638 /// when the bound is written, even if it is written with `'_` like in
5639 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
5640 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
5641 match self.anonymous_lifetime_mode {
5642 // NB. We intentionally ignore the create-parameter mode here.
5643 // and instead "pass through" to resolve-lifetimes, which will apply
5644 // the object-lifetime-defaulting rules. Elided object lifetime defaults
5645 // do not act like other elided lifetimes. In other words, given this:
5647 // impl Foo for Box<dyn Debug>
5649 // we do not introduce a fresh `'_` to serve as the bound, but instead
5650 // ultimately translate to the equivalent of:
5652 // impl Foo for Box<dyn Debug + 'static>
5654 // `resolve_lifetime` has the code to make that happen.
5655 AnonymousLifetimeMode::CreateParameter => {}
5657 AnonymousLifetimeMode::ReportError => {
5658 // ReportError applies to explicit use of `'_`.
5661 // This is the normal case.
5662 AnonymousLifetimeMode::PassThrough => {}
5664 // We don't need to do any replacement here as this lifetime
5665 // doesn't refer to an elided lifetime elsewhere in the function
5667 AnonymousLifetimeMode::Replace(_) => {}
5670 self.new_implicit_lifetime(span)
5673 fn new_replacement_lifetime(
5675 replacement: LtReplacement,
5677 ) -> hir::Lifetime {
5678 let hir_id = self.next_id();
5679 self.replace_elided_lifetime(hir_id, span, replacement)
5682 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
5684 hir_id: self.next_id(),
5686 name: hir::LifetimeName::Implicit,
5690 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
5691 self.sess.buffer_lint_with_diagnostic(
5692 builtin::BARE_TRAIT_OBJECTS,
5695 "trait objects without an explicit `dyn` are deprecated",
5696 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
5700 fn wrap_in_try_constructor(
5704 unstable_span: Span,
5706 let path = &[sym::ops, sym::Try, method];
5707 let from_err = P(self.expr_std_path(unstable_span, path, None,
5709 P(self.expr_call(e.span, from_err, hir_vec![e]))
5716 ) -> hir::ExprKind {
5720 // let mut pinned = <expr>;
5722 // match ::std::future::poll_with_tls_context(unsafe {
5723 // ::std::pin::Pin::new_unchecked(&mut pinned)
5725 // ::std::task::Poll::Ready(result) => break result,
5726 // ::std::task::Poll::Pending => {},
5731 if !self.is_async_body {
5732 let mut err = struct_span_err!(
5736 "`await` is only allowed inside `async` functions and blocks"
5738 err.span_label(await_span, "only allowed inside `async` functions and blocks");
5739 if let Some(item_sp) = self.current_item {
5740 err.span_label(item_sp, "this is not `async`");
5743 return hir::ExprKind::Err;
5745 let span = self.mark_span_with_reason(
5746 CompilerDesugaringKind::Await,
5750 let gen_future_span = self.mark_span_with_reason(
5751 CompilerDesugaringKind::Await,
5753 Some(vec![sym::gen_future].into()),
5756 // let mut pinned = <expr>;
5757 let expr = P(self.lower_expr(expr));
5758 let pinned_ident = Ident::with_empty_ctxt(sym::pinned);
5759 let (pinned_pat, pinned_pat_hid) = self.pat_ident_binding_mode(
5762 hir::BindingAnnotation::Mutable,
5764 let pinned_let = self.stmt_let_pat(
5768 hir::LocalSource::AwaitDesugar,
5771 // ::std::future::poll_with_tls_context(unsafe {
5772 // ::std::pin::Pin::new_unchecked(&mut pinned)
5775 let pinned = P(self.expr_ident(span, pinned_ident, pinned_pat_hid));
5776 let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
5777 let pin_ty_id = self.next_id();
5778 let new_unchecked_expr_kind = self.expr_call_std_assoc_fn(
5781 &[sym::pin, sym::Pin],
5783 hir_vec![ref_mut_pinned],
5785 let new_unchecked = P(self.expr(span, new_unchecked_expr_kind, ThinVec::new()));
5786 let unsafe_expr = self.expr_unsafe(new_unchecked);
5787 P(self.expr_call_std_path(
5789 &[sym::future, sym::poll_with_tls_context],
5790 hir_vec![unsafe_expr],
5794 // `::std::task::Poll::Ready(result) => break result`
5795 let loop_node_id = self.sess.next_node_id();
5796 let loop_hir_id = self.lower_node_id(loop_node_id);
5798 let x_ident = Ident::with_empty_ctxt(sym::result);
5799 let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
5800 let x_expr = P(self.expr_ident(span, x_ident, x_pat_hid));
5801 let ready_pat = self.pat_std_enum(
5803 &[sym::task, sym::Poll, sym::Ready],
5806 let break_x = self.with_loop_scope(loop_node_id, |this| {
5807 let expr_break = hir::ExprKind::Break(
5808 this.lower_loop_destination(None),
5811 P(this.expr(await_span, expr_break, ThinVec::new()))
5813 self.arm(hir_vec![ready_pat], break_x)
5816 // `::std::task::Poll::Pending => {}`
5818 let pending_pat = self.pat_std_enum(
5820 &[sym::task, sym::Poll, sym::Pending],
5823 let empty_block = P(self.expr_block_empty(span));
5824 self.arm(hir_vec![pending_pat], empty_block)
5828 let match_expr = P(self.expr_match(
5831 hir_vec![ready_arm, pending_arm],
5832 hir::MatchSource::AwaitDesugar,
5834 self.stmt(span, hir::StmtKind::Expr(match_expr))
5838 let unit = self.expr_unit(span);
5839 let yield_expr = P(self.expr(
5841 hir::ExprKind::Yield(P(unit)),
5844 self.stmt(span, hir::StmtKind::Expr(yield_expr))
5847 let loop_block = P(self.block_all(
5849 hir_vec![match_stmt, yield_stmt],
5853 let loop_expr = P(hir::Expr {
5854 hir_id: loop_hir_id,
5855 node: hir::ExprKind::Loop(
5858 hir::LoopSource::Loop,
5861 attrs: ThinVec::new(),
5864 hir::ExprKind::Block(
5865 P(self.block_all(span, hir_vec![pinned_let], Some(loop_expr))),
5871 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5872 // Sorting by span ensures that we get things in order within a
5873 // file, and also puts the files in a sensible order.
5874 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5875 body_ids.sort_by_key(|b| bodies[b].value.span);
5879 /// Checks if the specified expression is a built-in range literal.
5880 /// (See: `LoweringContext::lower_expr()`).
5881 pub fn is_range_literal(sess: &Session, expr: &hir::Expr) -> bool {
5882 use hir::{Path, QPath, ExprKind, TyKind};
5884 // Returns whether the given path represents a (desugared) range,
5885 // either in std or core, i.e. has either a `::std::ops::Range` or
5886 // `::core::ops::Range` prefix.
5887 fn is_range_path(path: &Path) -> bool {
5888 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.as_str().to_string()).collect();
5889 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
5891 // "{{root}}" is the equivalent of `::` prefix in `Path`.
5892 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
5893 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
5899 // Check whether a span corresponding to a range expression is a
5900 // range literal, rather than an explicit struct or `new()` call.
5901 fn is_lit(sess: &Session, span: &Span) -> bool {
5902 let source_map = sess.source_map();
5903 let end_point = source_map.end_point(*span);
5905 if let Ok(end_string) = source_map.span_to_snippet(end_point) {
5906 !(end_string.ends_with("}") || end_string.ends_with(")"))
5913 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
5914 ExprKind::Struct(ref qpath, _, _) => {
5915 if let QPath::Resolved(None, ref path) = **qpath {
5916 return is_range_path(&path) && is_lit(sess, &expr.span);
5920 // `..` desugars to its struct path.
5921 ExprKind::Path(QPath::Resolved(None, ref path)) => {
5922 return is_range_path(&path) && is_lit(sess, &expr.span);
5925 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
5926 ExprKind::Call(ref func, _) => {
5927 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.node {
5928 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.node {
5929 let new_call = segment.ident.as_str() == "new";
5930 return is_range_path(&path) && is_lit(sess, &expr.span) && new_call;