1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Lowers the AST to the HIR.
13 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
14 //! much like a fold. Where lowering involves a bit more work things get more
15 //! interesting and there are some invariants you should know about. These mostly
16 //! concern spans and ids.
18 //! Spans are assigned to AST nodes during parsing and then are modified during
19 //! expansion to indicate the origin of a node and the process it went through
20 //! being expanded. Ids are assigned to AST nodes just before lowering.
22 //! For the simpler lowering steps, ids and spans should be preserved. Unlike
23 //! expansion we do not preserve the process of lowering in the spans, so spans
24 //! should not be modified here. When creating a new node (as opposed to
25 //! 'folding' an existing one), then you create a new id using `next_id()`.
27 //! You must ensure that ids are unique. That means that you should only use the
28 //! id from an AST node in a single HIR node (you can assume that AST node ids
29 //! are unique). Every new node must have a unique id. Avoid cloning HIR nodes.
30 //! If you do, you must then set the new node's id to a fresh one.
32 //! Spans are used for error messages and for tools to map semantics back to
33 //! source code. It is therefore not as important with spans as ids to be strict
34 //! about use (you can't break the compiler by screwing up a span). Obviously, a
35 //! HIR node can only have a single span. But multiple nodes can have the same
36 //! span and spans don't need to be kept in order, etc. Where code is preserved
37 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
38 //! new it is probably best to give a span for the whole AST node being lowered.
39 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
40 //! get confused if the spans from leaf AST nodes occur in multiple places
41 //! in the HIR, especially for multiple identifiers.
43 use dep_graph::DepGraph;
44 use hir::{self, ParamName};
46 use hir::map::{DefKey, DefPathData, Definitions};
47 use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX};
48 use hir::def::{Def, PathResolution, PerNS};
50 use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
51 ELIDED_LIFETIMES_IN_PATHS};
52 use middle::cstore::CrateStore;
53 use rustc_data_structures::fx::FxHashSet;
54 use rustc_data_structures::indexed_vec::IndexVec;
55 use rustc_data_structures::thin_vec::ThinVec;
57 use session::config::nightly_options;
58 use util::common::FN_OUTPUT_NAME;
59 use util::nodemap::{DefIdMap, NodeMap};
61 use std::collections::BTreeMap;
64 use smallvec::SmallVec;
69 use syntax::ext::hygiene::{Mark, SyntaxContext};
70 use syntax::feature_gate::{emit_feature_err, GateIssue};
71 use syntax::print::pprust;
73 use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned};
74 use syntax::std_inject;
75 use syntax::symbol::{keywords, Symbol};
76 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
77 use syntax::parse::token::Token;
78 use syntax::visit::{self, Visitor};
79 use syntax_pos::{Span, MultiSpan};
81 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
83 pub struct LoweringContext<'a> {
84 crate_root: Option<&'static str>,
86 // Use to assign ids to hir nodes that do not directly correspond to an ast node
89 cstore: &'a dyn CrateStore,
91 resolver: &'a mut dyn Resolver,
93 /// The items being lowered are collected here.
94 items: BTreeMap<NodeId, hir::Item>,
96 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
97 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
98 bodies: BTreeMap<hir::BodyId, hir::Body>,
99 exported_macros: Vec<hir::MacroDef>,
101 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
102 trait_auto_impl: BTreeMap<DefId, NodeId>,
106 catch_scopes: Vec<NodeId>,
107 loop_scopes: Vec<NodeId>,
108 is_in_loop_condition: bool,
109 is_in_trait_impl: 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 // This will always be false unless the `in_band_lifetimes` or
130 // `impl_header_lifetime_elision` feature is enabled.
131 is_collecting_in_band_lifetimes: bool,
133 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
134 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
135 // against this list to see if it is already in-scope, or if a definition
136 // needs to be created for it.
137 in_scope_lifetimes: Vec<Ident>,
139 type_def_lifetime_params: DefIdMap<usize>,
141 current_hir_id_owner: Vec<(DefIndex, u32)>,
142 item_local_id_counters: NodeMap<u32>,
143 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
147 /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
148 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
150 /// Obtain the resolution for a node id
151 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
153 /// Obtain the possible resolutions for the given `use` statement.
154 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
156 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
157 /// This should only return `None` during testing.
158 fn definitions(&mut self) -> &mut Definitions;
160 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
161 /// it based on `is_value`.
165 crate_root: Option<&str>,
167 params: Option<P<hir::GenericArgs>>,
173 enum ImplTraitContext<'a> {
174 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
175 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
176 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
178 /// Newly generated parameters should be inserted into the given `Vec`.
179 Universal(&'a mut Vec<hir::GenericParam>),
181 /// Treat `impl Trait` as shorthand for a new existential parameter.
182 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
183 /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
185 /// We optionally store a `DefId` for the parent item here so we can look up necessary
186 /// information later. It is `None` when no information about the context should be stored,
187 /// e.g. for consts and statics.
188 Existential(Option<DefId>),
190 /// `impl Trait` is not accepted in this position.
191 Disallowed(ImplTraitPosition),
194 /// Position in which `impl Trait` is disallowed. Used for error reporting.
195 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
196 enum ImplTraitPosition {
201 impl<'a> ImplTraitContext<'a> {
203 fn disallowed() -> Self {
204 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
207 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
208 use self::ImplTraitContext::*;
210 Universal(params) => Universal(params),
211 Existential(did) => Existential(*did),
212 Disallowed(pos) => Disallowed(*pos),
219 cstore: &dyn CrateStore,
220 dep_graph: &DepGraph,
222 resolver: &mut dyn Resolver,
224 // We're constructing the HIR here; we don't care what we will
225 // read, since we haven't even constructed the *input* to
227 dep_graph.assert_ignored();
230 crate_root: std_inject::injected_crate_name(),
234 items: BTreeMap::new(),
235 trait_items: BTreeMap::new(),
236 impl_items: BTreeMap::new(),
237 bodies: BTreeMap::new(),
238 trait_impls: BTreeMap::new(),
239 trait_auto_impl: BTreeMap::new(),
240 exported_macros: Vec::new(),
241 catch_scopes: Vec::new(),
242 loop_scopes: Vec::new(),
243 is_in_loop_condition: false,
244 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
245 type_def_lifetime_params: DefIdMap(),
246 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
247 item_local_id_counters: NodeMap(),
248 node_id_to_hir_id: IndexVec::new(),
250 is_in_trait_impl: false,
251 lifetimes_to_define: Vec::new(),
252 is_collecting_in_band_lifetimes: false,
253 in_scope_lifetimes: Vec::new(),
257 #[derive(Copy, Clone, PartialEq)]
259 /// Any path in a type context.
261 /// The `module::Type` in `module::Type::method` in an expression.
266 struct LoweredNodeId {
271 enum ParenthesizedGenericArgs {
277 /// What to do when we encounter an **anonymous** lifetime
278 /// reference. Anonymous lifetime references come in two flavors. You
279 /// have implicit, or fully elided, references to lifetimes, like the
280 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
281 /// or `Ref<'_, T>`. These often behave the same, but not always:
283 /// - certain usages of implicit references are deprecated, like
284 /// `Ref<T>`, and we sometimes just give hard errors in those cases
286 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
287 /// the same as `Box<dyn Foo + '_>`.
289 /// We describe the effects of the various modes in terms of three cases:
291 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
292 /// of a `&` (e.g., the missing lifetime in something like `&T`)
293 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
294 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
295 /// elided bounds follow special rules. Note that this only covers
296 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
297 /// '_>` is a case of "modern" elision.
298 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
299 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
300 /// non-deprecated equivalent.
302 /// Currently, the handling of lifetime elision is somewhat spread out
303 /// between HIR lowering and -- as described below -- the
304 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
305 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
306 /// everything into HIR lowering.
307 #[derive(Copy, Clone)]
308 enum AnonymousLifetimeMode {
309 /// For **Modern** cases, create a new anonymous region parameter
310 /// and reference that.
312 /// For **Dyn Bound** cases, pass responsibility to
313 /// `resolve_lifetime` code.
315 /// For **Deprecated** cases, report an error.
318 /// Give a hard error when either `&` or `'_` is written. Used to
319 /// rule out things like `where T: Foo<'_>`. Does not imply an
320 /// error on default object bounds (e.g., `Box<dyn Foo>`).
323 /// Pass responsibility to `resolve_lifetime` code for all cases.
327 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[hir::ItemId; 1]> }
329 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
330 fn visit_ty(&mut self, ty: &'a Ty) {
336 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
339 visit::walk_ty(self, ty);
342 fn visit_path_segment(
345 path_segment: &'v PathSegment,
347 if let Some(ref p) = path_segment.args {
348 if let GenericArgs::Parenthesized(_) = **p {
352 visit::walk_path_segment(self, path_span, path_segment)
356 impl<'a> LoweringContext<'a> {
357 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
358 /// Full-crate AST visitor that inserts into a fresh
359 /// `LoweringContext` any information that may be
360 /// needed from arbitrary locations in the crate.
361 /// E.g. The number of lifetime generic parameters
362 /// declared for every type and trait definition.
363 struct MiscCollector<'lcx, 'interner: 'lcx> {
364 lctx: &'lcx mut LoweringContext<'interner>,
367 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
368 fn visit_item(&mut self, item: &'lcx Item) {
369 self.lctx.allocate_hir_id_counter(item.id, item);
372 ItemKind::Struct(_, ref generics)
373 | ItemKind::Union(_, ref generics)
374 | ItemKind::Enum(_, ref generics)
375 | ItemKind::Ty(_, ref generics)
376 | ItemKind::Existential(_, ref generics)
377 | ItemKind::Trait(_, _, ref generics, ..) => {
378 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
382 .filter(|param| match param.kind {
383 ast::GenericParamKind::Lifetime { .. } => true,
387 self.lctx.type_def_lifetime_params.insert(def_id, count);
391 visit::walk_item(self, item);
394 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
395 self.lctx.allocate_hir_id_counter(item.id, item);
396 visit::walk_trait_item(self, item);
399 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
400 self.lctx.allocate_hir_id_counter(item.id, item);
401 visit::walk_impl_item(self, item);
405 struct ItemLowerer<'lcx, 'interner: 'lcx> {
406 lctx: &'lcx mut LoweringContext<'interner>,
409 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
410 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
412 F: FnOnce(&mut Self),
414 let old = self.lctx.is_in_trait_impl;
415 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
421 self.lctx.is_in_trait_impl = old;
425 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
426 fn visit_item(&mut self, item: &'lcx Item) {
427 let mut item_lowered = true;
428 self.lctx.with_hir_id_owner(item.id, |lctx| {
429 if let Some(hir_item) = lctx.lower_item(item) {
430 lctx.items.insert(item.id, hir_item);
432 item_lowered = false;
437 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
438 hir::ItemKind::Impl(_, _, _, ref generics, ..)
439 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
440 generics.params.clone()
445 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
446 let this = &mut ItemLowerer { lctx: this };
447 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
448 this.with_trait_impl_ref(opt_trait_ref, |this| {
449 visit::walk_item(this, item)
452 visit::walk_item(this, item);
458 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
459 self.lctx.with_hir_id_owner(item.id, |lctx| {
460 let id = hir::TraitItemId { node_id: item.id };
461 let hir_item = lctx.lower_trait_item(item);
462 lctx.trait_items.insert(id, hir_item);
465 visit::walk_trait_item(self, item);
468 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
469 self.lctx.with_hir_id_owner(item.id, |lctx| {
470 let id = hir::ImplItemId { node_id: item.id };
471 let hir_item = lctx.lower_impl_item(item);
472 lctx.impl_items.insert(id, hir_item);
474 visit::walk_impl_item(self, item);
478 self.lower_node_id(CRATE_NODE_ID);
479 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
481 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
482 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
484 let module = self.lower_mod(&c.module);
485 let attrs = self.lower_attrs(&c.attrs);
486 let body_ids = body_ids(&self.bodies);
490 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
496 exported_macros: hir::HirVec::from(self.exported_macros),
498 trait_items: self.trait_items,
499 impl_items: self.impl_items,
502 trait_impls: self.trait_impls,
503 trait_auto_impl: self.trait_auto_impl,
507 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
508 if self.item_local_id_counters.insert(owner, 0).is_some() {
510 "Tried to allocate item_local_id_counter for {:?} twice",
514 // Always allocate the first HirId for the owner itself
515 self.lower_node_id_with_owner(owner, owner)
518 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
520 F: FnOnce(&mut Self) -> hir::HirId,
522 if ast_node_id == DUMMY_NODE_ID {
523 return LoweredNodeId {
524 node_id: DUMMY_NODE_ID,
525 hir_id: hir::DUMMY_HIR_ID,
529 let min_size = ast_node_id.as_usize() + 1;
531 if min_size > self.node_id_to_hir_id.len() {
532 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
535 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
537 if existing_hir_id == hir::DUMMY_HIR_ID {
538 // Generate a new HirId
539 let hir_id = alloc_hir_id(self);
540 self.node_id_to_hir_id[ast_node_id] = hir_id;
542 node_id: ast_node_id,
547 node_id: ast_node_id,
548 hir_id: existing_hir_id,
553 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
555 F: FnOnce(&mut Self) -> T,
557 let counter = self.item_local_id_counters
558 .insert(owner, HIR_ID_COUNTER_LOCKED)
559 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
560 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
561 self.current_hir_id_owner.push((def_index, counter));
563 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
565 debug_assert!(def_index == new_def_index);
566 debug_assert!(new_counter >= counter);
568 let prev = self.item_local_id_counters
569 .insert(owner, new_counter)
571 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
575 /// This method allocates a new HirId for the given NodeId and stores it in
576 /// the LoweringContext's NodeId => HirId map.
577 /// Take care not to call this method if the resulting HirId is then not
578 /// actually used in the HIR, as that would trigger an assertion in the
579 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
580 /// properly. Calling the method twice with the same NodeId is fine though.
581 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
582 self.lower_node_id_generic(ast_node_id, |this| {
583 let &mut (def_index, ref mut local_id_counter) =
584 this.current_hir_id_owner.last_mut().unwrap();
585 let local_id = *local_id_counter;
586 *local_id_counter += 1;
589 local_id: hir::ItemLocalId(local_id),
594 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
595 self.lower_node_id_generic(ast_node_id, |this| {
596 let local_id_counter = this
597 .item_local_id_counters
599 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
600 let local_id = *local_id_counter;
602 // We want to be sure not to modify the counter in the map while it
603 // is also on the stack. Otherwise we'll get lost updates when writing
604 // back from the stack to the map.
605 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
607 *local_id_counter += 1;
611 .opt_def_index(owner)
612 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
613 that do not belong to the current owner");
617 local_id: hir::ItemLocalId(local_id),
622 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
623 let body = hir::Body {
624 arguments: decl.map_or(hir_vec![], |decl| {
625 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
627 is_generator: self.is_generator,
631 self.bodies.insert(id, body);
635 fn next_id(&mut self) -> LoweredNodeId {
636 self.lower_node_id(self.sess.next_node_id())
639 fn expect_full_def(&mut self, id: NodeId) -> Def {
640 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
641 if pr.unresolved_segments() != 0 {
642 bug!("path not fully resolved: {:?}", pr);
648 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Def> {
649 self.resolver.get_import(id).present_items().map(|pr| {
650 if pr.unresolved_segments() != 0 {
651 bug!("path not fully resolved: {:?}", pr);
657 fn diagnostic(&self) -> &errors::Handler {
658 self.sess.diagnostic()
661 fn str_to_ident(&self, s: &'static str) -> Ident {
662 Ident::with_empty_ctxt(Symbol::gensym(s))
665 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
666 let mark = Mark::fresh(Mark::root());
667 mark.set_expn_info(source_map::ExpnInfo {
669 def_site: Some(span),
670 format: source_map::CompilerDesugaring(reason),
671 allow_internal_unstable: true,
672 allow_internal_unsafe: false,
673 local_inner_macros: false,
674 edition: source_map::hygiene::default_edition(),
676 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
679 fn with_anonymous_lifetime_mode<R>(
681 anonymous_lifetime_mode: AnonymousLifetimeMode,
682 op: impl FnOnce(&mut Self) -> R,
684 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
685 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
686 let result = op(self);
687 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
691 /// Creates a new hir::GenericParam for every new lifetime and
692 /// type parameter encountered while evaluating `f`. Definitions
693 /// are created with the parent provided. If no `parent_id` is
694 /// provided, no definitions will be returned.
696 /// Presuming that in-band lifetimes are enabled, then
697 /// `self.anonymous_lifetime_mode` will be updated to match the
698 /// argument while `f` is running (and restored afterwards).
699 fn collect_in_band_defs<T, F>(
702 anonymous_lifetime_mode: AnonymousLifetimeMode,
704 ) -> (Vec<hir::GenericParam>, T)
706 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
708 assert!(!self.is_collecting_in_band_lifetimes);
709 assert!(self.lifetimes_to_define.is_empty());
710 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
712 if self.sess.features_untracked().impl_header_lifetime_elision {
713 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
714 self.is_collecting_in_band_lifetimes = true;
715 } else if self.sess.features_untracked().in_band_lifetimes {
716 self.is_collecting_in_band_lifetimes = true;
719 let (in_band_ty_params, res) = f(self);
721 self.is_collecting_in_band_lifetimes = false;
722 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
724 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
726 let params = lifetimes_to_define
728 .map(|(span, hir_name)| {
729 let def_node_id = self.next_id().node_id;
731 // Get the name we'll use to make the def-path. Note
732 // that collisions are ok here and this shouldn't
733 // really show up for end-user.
734 let (str_name, kind) = match hir_name {
735 ParamName::Plain(ident) => (
736 ident.as_interned_str(),
737 hir::LifetimeParamKind::InBand,
739 ParamName::Fresh(_) => (
740 keywords::UnderscoreLifetime.name().as_interned_str(),
741 hir::LifetimeParamKind::Elided,
743 ParamName::Error => (
744 keywords::UnderscoreLifetime.name().as_interned_str(),
745 hir::LifetimeParamKind::Error,
749 // Add a definition for the in-band lifetime def
750 self.resolver.definitions().create_def_with_parent(
753 DefPathData::LifetimeParam(str_name),
754 DefIndexAddressSpace::High,
765 pure_wrt_drop: false,
766 kind: hir::GenericParamKind::Lifetime { kind }
769 .chain(in_band_ty_params.into_iter())
775 /// When there is a reference to some lifetime `'a`, and in-band
776 /// lifetimes are enabled, then we want to push that lifetime into
777 /// the vector of names to define later. In that case, it will get
778 /// added to the appropriate generics.
779 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
780 if !self.is_collecting_in_band_lifetimes {
784 if !self.sess.features_untracked().in_band_lifetimes {
788 if self.in_scope_lifetimes.contains(&ident.modern()) {
792 let hir_name = ParamName::Plain(ident);
794 if self.lifetimes_to_define.iter()
795 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
799 self.lifetimes_to_define.push((ident.span, hir_name));
802 /// When we have either an elided or `'_` lifetime in an impl
803 /// header, we convert it to an in-band lifetime.
804 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
805 assert!(self.is_collecting_in_band_lifetimes);
806 let index = self.lifetimes_to_define.len();
807 let hir_name = ParamName::Fresh(index);
808 self.lifetimes_to_define.push((span, hir_name));
812 // Evaluates `f` with the lifetimes in `params` in-scope.
813 // This is used to track which lifetimes have already been defined, and
814 // which are new in-band lifetimes that need to have a definition created
816 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
818 F: FnOnce(&mut LoweringContext<'_>) -> T,
820 let old_len = self.in_scope_lifetimes.len();
821 let lt_def_names = params.iter().filter_map(|param| match param.kind {
822 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
825 self.in_scope_lifetimes.extend(lt_def_names);
829 self.in_scope_lifetimes.truncate(old_len);
833 // Same as the method above, but accepts `hir::GenericParam`s
834 // instead of `ast::GenericParam`s.
835 // This should only be used with generics that have already had their
836 // in-band lifetimes added. In practice, this means that this function is
837 // only used when lowering a child item of a trait or impl.
838 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
839 params: &HirVec<hir::GenericParam>,
842 F: FnOnce(&mut LoweringContext<'_>) -> T,
844 let old_len = self.in_scope_lifetimes.len();
845 let lt_def_names = params.iter().filter_map(|param| match param.kind {
846 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
849 self.in_scope_lifetimes.extend(lt_def_names);
853 self.in_scope_lifetimes.truncate(old_len);
857 /// Appends in-band lifetime defs and argument-position `impl
858 /// Trait` defs to the existing set of generics.
860 /// Presuming that in-band lifetimes are enabled, then
861 /// `self.anonymous_lifetime_mode` will be updated to match the
862 /// argument while `f` is running (and restored afterwards).
863 fn add_in_band_defs<F, T>(
867 anonymous_lifetime_mode: AnonymousLifetimeMode,
869 ) -> (hir::Generics, T)
871 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
873 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
876 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
877 let mut params = Vec::new();
878 let generics = this.lower_generics(
880 ImplTraitContext::Universal(&mut params),
882 let res = f(this, &mut params);
883 (params, (generics, res))
888 lowered_generics.params = lowered_generics
895 (lowered_generics, res)
898 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
900 F: FnOnce(&mut LoweringContext<'_>) -> T,
902 let len = self.catch_scopes.len();
903 self.catch_scopes.push(catch_id);
905 let result = f(self);
908 self.catch_scopes.len(),
909 "catch scopes should be added and removed in stack order"
912 self.catch_scopes.pop().unwrap();
919 capture_clause: CaptureBy,
920 closure_node_id: NodeId,
922 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
924 let prev_is_generator = mem::replace(&mut self.is_generator, true);
925 let body_expr = body(self);
926 let span = body_expr.span;
927 let output = match ret_ty {
928 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
929 None => FunctionRetTy::Default(span),
936 let body_id = self.record_body(body_expr, Some(&decl));
937 self.is_generator = prev_is_generator;
939 let capture_clause = self.lower_capture_clause(capture_clause);
940 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
941 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
942 let generator = hir::Expr {
944 hir_id: closure_hir_id,
945 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
946 Some(hir::GeneratorMovability::Static)),
948 attrs: ThinVec::new(),
951 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
952 let gen_future = self.expr_std_path(
953 unstable_span, &["future", "from_generator"], None, ThinVec::new());
954 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
957 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
959 F: FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
961 let prev = mem::replace(&mut self.is_generator, false);
962 let result = f(self);
963 let r = self.record_body(result, decl);
964 self.is_generator = prev;
968 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
970 F: FnOnce(&mut LoweringContext<'_>) -> T,
972 // We're no longer in the base loop's condition; we're in another loop.
973 let was_in_loop_condition = self.is_in_loop_condition;
974 self.is_in_loop_condition = false;
976 let len = self.loop_scopes.len();
977 self.loop_scopes.push(loop_id);
979 let result = f(self);
982 self.loop_scopes.len(),
983 "Loop scopes should be added and removed in stack order"
986 self.loop_scopes.pop().unwrap();
988 self.is_in_loop_condition = was_in_loop_condition;
993 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
995 F: FnOnce(&mut LoweringContext<'_>) -> T,
997 let was_in_loop_condition = self.is_in_loop_condition;
998 self.is_in_loop_condition = true;
1000 let result = f(self);
1002 self.is_in_loop_condition = was_in_loop_condition;
1007 fn with_new_scopes<T, F>(&mut self, f: F) -> T
1009 F: FnOnce(&mut LoweringContext<'_>) -> T,
1011 let was_in_loop_condition = self.is_in_loop_condition;
1012 self.is_in_loop_condition = false;
1014 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
1015 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
1017 self.catch_scopes = catch_scopes;
1018 self.loop_scopes = loop_scopes;
1020 self.is_in_loop_condition = was_in_loop_condition;
1025 fn def_key(&mut self, id: DefId) -> DefKey {
1027 self.resolver.definitions().def_key(id.index)
1029 self.cstore.def_key(id)
1033 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1034 label.map(|label| hir::Label {
1039 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1040 let target_id = match destination {
1042 if let Def::Label(loop_id) = self.expect_full_def(id) {
1043 Ok(self.lower_node_id(loop_id).node_id)
1045 Err(hir::LoopIdError::UnresolvedLabel)
1052 .map(|id| Ok(self.lower_node_id(id).node_id))
1053 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1058 label: self.lower_label(destination.map(|(_, label)| label)),
1063 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1066 .map(|a| self.lower_attr(a))
1067 .collect::<Vec<_>>()
1071 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1075 path: attr.path.clone(),
1076 tokens: self.lower_token_stream(attr.tokens.clone()),
1077 is_sugared_doc: attr.is_sugared_doc,
1082 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1085 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1089 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1091 TokenTree::Token(span, token) => self.lower_token(token, span),
1092 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1095 delim: delimited.delim,
1096 tts: self.lower_token_stream(delimited.tts.into()).into(),
1102 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1104 Token::Interpolated(_) => {}
1105 other => return TokenTree::Token(span, other).into(),
1108 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1109 self.lower_token_stream(tts)
1112 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1114 attrs: self.lower_attrs(&arm.attrs),
1115 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1116 guard: match arm.guard {
1117 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1120 body: P(self.lower_expr(&arm.body)),
1124 fn lower_ty_binding(&mut self, b: &TypeBinding,
1125 itctx: ImplTraitContext<'_>) -> hir::TypeBinding {
1127 id: self.lower_node_id(b.id).node_id,
1129 ty: self.lower_ty(&b.ty, itctx),
1134 fn lower_generic_arg(&mut self,
1135 arg: &ast::GenericArg,
1136 itctx: ImplTraitContext<'_>)
1137 -> hir::GenericArg {
1139 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1140 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1144 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1145 P(self.lower_ty_direct(t, itctx))
1148 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1149 let kind = match t.node {
1150 TyKind::Infer => hir::TyKind::Infer,
1151 TyKind::Err => hir::TyKind::Err,
1152 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1153 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1154 TyKind::Rptr(ref region, ref mt) => {
1155 let span = t.span.shrink_to_lo();
1156 let lifetime = match *region {
1157 Some(ref lt) => self.lower_lifetime(lt),
1158 None => self.elided_ref_lifetime(span),
1160 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1162 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1165 this.with_anonymous_lifetime_mode(
1166 AnonymousLifetimeMode::PassThrough,
1168 hir::TyKind::BareFn(P(hir::BareFnTy {
1169 generic_params: this.lower_generic_params(
1172 ImplTraitContext::disallowed(),
1174 unsafety: this.lower_unsafety(f.unsafety),
1176 decl: this.lower_fn_decl(&f.decl, None, false, None),
1177 arg_names: this.lower_fn_args_to_names(&f.decl),
1183 TyKind::Never => hir::TyKind::Never,
1184 TyKind::Tup(ref tys) => {
1185 hir::TyKind::Tup(tys.iter().map(|ty| {
1186 self.lower_ty_direct(ty, itctx.reborrow())
1189 TyKind::Paren(ref ty) => {
1190 return self.lower_ty_direct(ty, itctx);
1192 TyKind::Path(ref qself, ref path) => {
1193 let id = self.lower_node_id(t.id);
1194 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1195 let ty = self.ty_path(id, t.span, qpath);
1196 if let hir::TyKind::TraitObject(..) = ty.node {
1197 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1201 TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1204 def: self.expect_full_def(t.id),
1205 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1209 TyKind::Array(ref ty, ref length) => {
1210 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1212 TyKind::Typeof(ref expr) => {
1213 hir::TyKind::Typeof(self.lower_anon_const(expr))
1215 TyKind::TraitObject(ref bounds, kind) => {
1216 let mut lifetime_bound = None;
1219 .filter_map(|bound| match *bound {
1220 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1221 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1223 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1224 GenericBound::Outlives(ref lifetime) => {
1225 if lifetime_bound.is_none() {
1226 lifetime_bound = Some(self.lower_lifetime(lifetime));
1232 let lifetime_bound =
1233 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1234 if kind != TraitObjectSyntax::Dyn {
1235 self.maybe_lint_bare_trait(t.span, t.id, false);
1237 hir::TyKind::TraitObject(bounds, lifetime_bound)
1239 TyKind::ImplTrait(def_node_id, ref bounds) => {
1242 ImplTraitContext::Existential(fn_def_id) => {
1243 self.lower_existential_impl_trait(
1244 span, fn_def_id, def_node_id,
1245 |this| this.lower_param_bounds(bounds, itctx),
1248 ImplTraitContext::Universal(in_band_ty_params) => {
1249 self.lower_node_id(def_node_id);
1250 // Add a definition for the in-band Param
1251 let def_index = self
1254 .opt_def_index(def_node_id)
1257 let hir_bounds = self.lower_param_bounds(
1259 ImplTraitContext::Universal(in_band_ty_params),
1261 // Set the name to `impl Bound1 + Bound2`
1262 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1263 in_band_ty_params.push(hir::GenericParam {
1265 name: ParamName::Plain(ident),
1266 pure_wrt_drop: false,
1270 kind: hir::GenericParamKind::Type {
1272 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1276 hir::TyKind::Path(hir::QPath::Resolved(
1280 def: Def::TyParam(DefId::local(def_index)),
1281 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1285 ImplTraitContext::Disallowed(pos) => {
1286 let allowed_in = if self.sess.features_untracked()
1287 .impl_trait_in_bindings {
1288 "bindings or function and inherent method return types"
1290 "function and inherent method return types"
1292 let mut err = struct_span_err!(
1296 "`impl Trait` not allowed outside of {}",
1299 if pos == ImplTraitPosition::Binding &&
1300 nightly_options::is_nightly_build() {
1302 "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1310 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1313 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1322 fn lower_existential_impl_trait(
1325 fn_def_id: Option<DefId>,
1326 exist_ty_node_id: NodeId,
1327 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1329 // Make sure we know that some funky desugaring has been going on here.
1330 // This is a first: there is code in other places like for loop
1331 // desugaring that explicitly states that we don't want to track that.
1332 // Not tracking it makes lints in rustc and clippy very fragile as
1333 // frequently opened issues show.
1334 let exist_ty_span = self.allow_internal_unstable(
1335 CompilerDesugaringKind::ExistentialReturnType,
1339 let exist_ty_def_index = self
1342 .opt_def_index(exist_ty_node_id)
1345 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1347 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1349 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1355 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1356 let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1357 generics: hir::Generics {
1358 params: lifetime_defs,
1359 where_clause: hir::WhereClause {
1360 id: lctx.next_id().node_id,
1361 predicates: Vec::new().into(),
1366 impl_trait_fn: fn_def_id,
1368 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1369 // Generate an `existential type Foo: Trait;` declaration
1370 trace!("creating existential type with id {:#?}", exist_ty_id);
1372 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1373 let exist_ty_item = hir::Item {
1374 id: exist_ty_id.node_id,
1375 hir_id: exist_ty_id.hir_id,
1376 name: keywords::Invalid.name(),
1377 attrs: Default::default(),
1378 node: exist_ty_item_kind,
1379 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1380 span: exist_ty_span,
1383 // Insert the item into the global list. This usually happens
1384 // automatically for all AST items. But this existential type item
1385 // does not actually exist in the AST.
1386 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1388 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1389 hir::TyKind::Def(hir::ItemId { id: exist_ty_id.node_id }, lifetimes)
1393 fn lifetimes_from_impl_trait_bounds(
1395 exist_ty_id: NodeId,
1396 parent_index: DefIndex,
1397 bounds: &hir::GenericBounds,
1398 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1399 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1400 // appear in the bounds, excluding lifetimes that are created within the bounds.
1401 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1402 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1403 context: &'r mut LoweringContext<'a>,
1405 exist_ty_id: NodeId,
1406 collect_elided_lifetimes: bool,
1407 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1408 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1409 output_lifetimes: Vec<hir::GenericArg>,
1410 output_lifetime_params: Vec<hir::GenericParam>,
1413 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1414 fn nested_visit_map<'this>(
1416 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1417 hir::intravisit::NestedVisitorMap::None
1420 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1421 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1422 if parameters.parenthesized {
1423 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1424 self.collect_elided_lifetimes = false;
1425 hir::intravisit::walk_generic_args(self, span, parameters);
1426 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1428 hir::intravisit::walk_generic_args(self, span, parameters);
1432 fn visit_ty(&mut self, t: &'v hir::Ty) {
1433 // Don't collect elided lifetimes used inside of `fn()` syntax
1434 if let hir::TyKind::BareFn(_) = t.node {
1435 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1436 self.collect_elided_lifetimes = false;
1438 // Record the "stack height" of `for<'a>` lifetime bindings
1439 // to be able to later fully undo their introduction.
1440 let old_len = self.currently_bound_lifetimes.len();
1441 hir::intravisit::walk_ty(self, t);
1442 self.currently_bound_lifetimes.truncate(old_len);
1444 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1446 hir::intravisit::walk_ty(self, t)
1450 fn visit_poly_trait_ref(
1452 trait_ref: &'v hir::PolyTraitRef,
1453 modifier: hir::TraitBoundModifier,
1455 // Record the "stack height" of `for<'a>` lifetime bindings
1456 // to be able to later fully undo their introduction.
1457 let old_len = self.currently_bound_lifetimes.len();
1458 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1459 self.currently_bound_lifetimes.truncate(old_len);
1462 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1463 // Record the introduction of 'a in `for<'a> ...`
1464 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1465 // Introduce lifetimes one at a time so that we can handle
1466 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1467 let lt_name = hir::LifetimeName::Param(param.name);
1468 self.currently_bound_lifetimes.push(lt_name);
1471 hir::intravisit::walk_generic_param(self, param);
1474 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1475 let name = match lifetime.name {
1476 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1477 if self.collect_elided_lifetimes {
1478 // Use `'_` for both implicit and underscore lifetimes in
1479 // `abstract type Foo<'_>: SomeTrait<'_>;`
1480 hir::LifetimeName::Underscore
1485 hir::LifetimeName::Param(_) => lifetime.name,
1486 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1489 if !self.currently_bound_lifetimes.contains(&name)
1490 && !self.already_defined_lifetimes.contains(&name) {
1491 self.already_defined_lifetimes.insert(name);
1493 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1494 id: self.context.next_id().node_id,
1495 span: lifetime.span,
1499 // We need to manually create the ids here, because the
1500 // definitions will go into the explicit `existential type`
1501 // declaration and thus need to have their owner set to that item
1502 let def_node_id = self.context.sess.next_node_id();
1503 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1504 self.context.resolver.definitions().create_def_with_parent(
1507 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1508 DefIndexAddressSpace::High,
1513 let (name, kind) = match name {
1514 hir::LifetimeName::Underscore => (
1515 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident()),
1516 hir::LifetimeParamKind::Elided,
1518 hir::LifetimeName::Param(param_name) => (
1520 hir::LifetimeParamKind::Explicit,
1522 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1525 self.output_lifetime_params.push(hir::GenericParam {
1528 span: lifetime.span,
1529 pure_wrt_drop: false,
1532 kind: hir::GenericParamKind::Lifetime { kind }
1538 let mut lifetime_collector = ImplTraitLifetimeCollector {
1540 parent: parent_index,
1542 collect_elided_lifetimes: true,
1543 currently_bound_lifetimes: Vec::new(),
1544 already_defined_lifetimes: FxHashSet::default(),
1545 output_lifetimes: Vec::new(),
1546 output_lifetime_params: Vec::new(),
1549 for bound in bounds {
1550 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1554 lifetime_collector.output_lifetimes.into(),
1555 lifetime_collector.output_lifetime_params.into(),
1559 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1564 .map(|x| self.lower_foreign_item(x))
1569 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1576 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1578 node: hir::VariantKind {
1579 name: v.node.ident.name,
1580 attrs: self.lower_attrs(&v.node.attrs),
1581 data: self.lower_variant_data(&v.node.data),
1582 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1591 qself: &Option<QSelf>,
1593 param_mode: ParamMode,
1594 mut itctx: ImplTraitContext<'_>,
1596 let qself_position = qself.as_ref().map(|q| q.position);
1597 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1599 let resolution = self.resolver
1601 .unwrap_or(PathResolution::new(Def::Err));
1603 let proj_start = p.segments.len() - resolution.unresolved_segments();
1604 let path = P(hir::Path {
1605 def: resolution.base_def(),
1606 segments: p.segments[..proj_start]
1609 .map(|(i, segment)| {
1610 let param_mode = match (qself_position, param_mode) {
1611 (Some(j), ParamMode::Optional) if i < j => {
1612 // This segment is part of the trait path in a
1613 // qualified path - one of `a`, `b` or `Trait`
1614 // in `<X as a::b::Trait>::T::U::method`.
1620 // Figure out if this is a type/trait segment,
1621 // which may need lifetime elision performed.
1622 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1623 krate: def_id.krate,
1624 index: this.def_key(def_id).parent.expect("missing parent"),
1626 let type_def_id = match resolution.base_def() {
1627 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1628 Some(parent_def_id(self, def_id))
1630 Def::Variant(def_id) if i + 1 == proj_start => {
1631 Some(parent_def_id(self, def_id))
1634 | Def::Union(def_id)
1636 | Def::TyAlias(def_id)
1637 | Def::Trait(def_id) if i + 1 == proj_start =>
1643 let parenthesized_generic_args = match resolution.base_def() {
1644 // `a::b::Trait(Args)`
1645 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1646 // `a::b::Trait(Args)::TraitItem`
1647 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1648 if i + 2 == proj_start =>
1650 ParenthesizedGenericArgs::Ok
1652 // Avoid duplicated errors
1653 Def::Err => ParenthesizedGenericArgs::Ok,
1659 | Def::Variant(..) if i + 1 == proj_start =>
1661 ParenthesizedGenericArgs::Err
1663 // A warning for now, for compatibility reasons
1664 _ => ParenthesizedGenericArgs::Warn,
1667 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1668 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1671 assert!(!def_id.is_local());
1673 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1674 let n = item_generics.own_counts().lifetimes;
1675 self.type_def_lifetime_params.insert(def_id, n);
1678 self.lower_path_segment(
1683 parenthesized_generic_args,
1691 // Simple case, either no projections, or only fully-qualified.
1692 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1693 if resolution.unresolved_segments() == 0 {
1694 return hir::QPath::Resolved(qself, path);
1697 // Create the innermost type that we're projecting from.
1698 let mut ty = if path.segments.is_empty() {
1699 // If the base path is empty that means there exists a
1700 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1701 qself.expect("missing QSelf for <T>::...")
1703 // Otherwise, the base path is an implicit `Self` type path,
1704 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1705 // `<I as Iterator>::Item::default`.
1706 let new_id = self.next_id();
1707 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1710 // Anything after the base path are associated "extensions",
1711 // out of which all but the last one are associated types,
1712 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1713 // * base path is `std::vec::Vec<T>`
1714 // * "extensions" are `IntoIter`, `Item` and `clone`
1715 // * type nodes are:
1716 // 1. `std::vec::Vec<T>` (created above)
1717 // 2. `<std::vec::Vec<T>>::IntoIter`
1718 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1719 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1720 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1721 let segment = P(self.lower_path_segment(
1726 ParenthesizedGenericArgs::Warn,
1729 let qpath = hir::QPath::TypeRelative(ty, segment);
1731 // It's finished, return the extension of the right node type.
1732 if i == p.segments.len() - 1 {
1736 // Wrap the associated extension in another type node.
1737 let new_id = self.next_id();
1738 ty = P(self.ty_path(new_id, p.span, qpath));
1741 // Should've returned in the for loop above.
1744 "lower_qpath: no final extension segment in {}..{}",
1750 fn lower_path_extra(
1754 ident: Option<Ident>,
1755 param_mode: ParamMode,
1759 segments: p.segments
1762 self.lower_path_segment(
1767 ParenthesizedGenericArgs::Err,
1768 ImplTraitContext::disallowed(),
1771 .chain(ident.map(|ident| hir::PathSegment::from_ident(ident)))
1777 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1778 let def = self.expect_full_def(id);
1779 self.lower_path_extra(def, p, None, param_mode)
1782 fn lower_path_segment(
1785 segment: &PathSegment,
1786 param_mode: ParamMode,
1787 expected_lifetimes: usize,
1788 parenthesized_generic_args: ParenthesizedGenericArgs,
1789 itctx: ImplTraitContext<'_>,
1790 ) -> hir::PathSegment {
1791 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1792 let msg = "parenthesized parameters may only be used with a trait";
1793 match **generic_args {
1794 GenericArgs::AngleBracketed(ref data) => {
1795 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1797 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1798 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1799 ParenthesizedGenericArgs::Warn => {
1800 self.sess.buffer_lint(
1801 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1806 (hir::GenericArgs::none(), true)
1808 ParenthesizedGenericArgs::Err => {
1809 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1810 .span_label(data.span, "only traits may use parentheses")
1812 (hir::GenericArgs::none(), true)
1817 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1820 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1821 GenericArg::Lifetime(_) => true,
1824 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1825 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1826 if !generic_args.parenthesized && !has_lifetimes {
1828 self.elided_path_lifetimes(path_span, expected_lifetimes)
1830 .map(|lt| GenericArg::Lifetime(lt))
1831 .chain(generic_args.args.into_iter())
1833 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1834 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1835 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1836 let no_bindings = generic_args.bindings.is_empty();
1837 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1838 // If there are no (non-implicit) generic args or associated-type
1839 // bindings, our suggestion includes the angle brackets
1840 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1842 // Otherwise—sorry, this is kind of gross—we need to infer the
1843 // place to splice in the `'_, ` from the generics that do exist
1844 let first_generic_span = first_generic_span
1845 .expect("already checked that type args or bindings exist");
1846 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1848 self.sess.buffer_lint_with_diagnostic(
1849 ELIDED_LIFETIMES_IN_PATHS,
1852 "hidden lifetime parameters in types are deprecated",
1853 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1854 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1860 hir::PathSegment::new(
1867 fn lower_angle_bracketed_parameter_data(
1869 data: &AngleBracketedArgs,
1870 param_mode: ParamMode,
1871 mut itctx: ImplTraitContext<'_>,
1872 ) -> (hir::GenericArgs, bool) {
1873 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1874 let has_types = args.iter().any(|arg| match arg {
1875 ast::GenericArg::Type(_) => true,
1879 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1880 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1881 parenthesized: false,
1883 !has_types && param_mode == ParamMode::Optional)
1886 fn lower_parenthesized_parameter_data(
1888 data: &ParenthesisedArgs,
1889 ) -> (hir::GenericArgs, bool) {
1890 // Switch to `PassThrough` mode for anonymous lifetimes: this
1891 // means that we permit things like `&Ref<T>`, where `Ref` has
1892 // a hidden lifetime parameter. This is needed for backwards
1893 // compatibility, even in contexts like an impl header where
1894 // we generally don't permit such things (see #51008).
1895 self.with_anonymous_lifetime_mode(
1896 AnonymousLifetimeMode::PassThrough,
1898 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1901 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
1903 let mk_tup = |this: &mut Self, tys, span| {
1904 let LoweredNodeId { node_id, hir_id } = this.next_id();
1905 hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1910 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1913 id: this.next_id().node_id,
1914 ident: Ident::from_str(FN_OUTPUT_NAME),
1917 .map(|ty| this.lower_ty(&ty, ImplTraitContext::disallowed()))
1918 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1919 span: output.as_ref().map_or(span, |ty| ty.span),
1922 parenthesized: true,
1930 fn lower_local(&mut self, l: &Local) -> (P<hir::Local>, SmallVec<[hir::ItemId; 1]>) {
1931 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1932 let mut ids = SmallVec::<[hir::ItemId; 1]>::new();
1933 if self.sess.features_untracked().impl_trait_in_bindings {
1934 if let Some(ref ty) = l.ty {
1935 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
1936 visitor.visit_ty(ty);
1939 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
1945 .map(|t| self.lower_ty(t,
1946 if self.sess.features_untracked().impl_trait_in_bindings {
1947 ImplTraitContext::Existential(Some(parent_def_id))
1949 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
1952 pat: self.lower_pat(&l.pat),
1953 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1955 attrs: l.attrs.clone(),
1956 source: hir::LocalSource::Normal,
1960 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1962 Mutability::Mutable => hir::MutMutable,
1963 Mutability::Immutable => hir::MutImmutable,
1967 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1968 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1972 pat: self.lower_pat(&arg.pat),
1976 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1979 .map(|arg| match arg.pat.node {
1980 PatKind::Ident(_, ident, _) => ident,
1981 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
1986 // Lowers a function declaration.
1988 // decl: the unlowered (ast) function declaration.
1989 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1990 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1991 // make_ret_async is also `Some`.
1992 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1993 // This guards against trait declarations and implementations where impl Trait is
1995 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1996 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
1997 // return type impl Trait item.
2001 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2002 impl_trait_return_allow: bool,
2003 make_ret_async: Option<NodeId>,
2004 ) -> P<hir::FnDecl> {
2005 let inputs = decl.inputs
2008 if let Some((_, ref mut ibty)) = in_band_ty_params {
2009 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2011 self.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2014 .collect::<HirVec<_>>();
2016 let output = if let Some(ret_id) = make_ret_async {
2017 self.lower_async_fn_ret_ty(
2020 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
2025 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2026 Some((def_id, _)) if impl_trait_return_allow => {
2027 hir::Return(self.lower_ty(ty,
2028 ImplTraitContext::Existential(Some(def_id))))
2031 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2034 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2041 variadic: decl.variadic,
2042 implicit_self: decl.inputs.get(0).map_or(
2043 hir::ImplicitSelfKind::None,
2045 let is_mutable_pat = match arg.pat.node {
2046 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2047 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2048 mt == Mutability::Mutable,
2053 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2054 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2055 // Given we are only considering `ImplicitSelf` types, we needn't consider
2056 // the case where we have a mutable pattern to a reference as that would
2057 // no longer be an `ImplicitSelf`.
2058 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2059 mt.mutbl == ast::Mutability::Mutable =>
2060 hir::ImplicitSelfKind::MutRef,
2061 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2062 hir::ImplicitSelfKind::ImmRef,
2063 _ => hir::ImplicitSelfKind::None,
2070 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
2072 // fn_span: the span of the async function declaration. Used for error reporting.
2073 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
2074 // output: unlowered output type (`T` in `-> T`)
2075 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
2076 fn lower_async_fn_ret_ty(
2079 output: &FunctionRetTy,
2081 return_impl_trait_id: NodeId,
2082 ) -> hir::FunctionRetTy {
2083 // Get lifetimes used in the input arguments to the function. Our output type must also
2084 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
2085 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
2086 // is a subset of the other. We really want some new lifetime that is a subset of all input
2087 // lifetimes, but that doesn't exist at the moment.
2089 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
2090 context: &'r mut LoweringContext<'a>,
2091 // Lifetimes bound by HRTB
2092 currently_bound_lifetimes: Vec<hir::LifetimeName>,
2093 // Whether to count elided lifetimes.
2094 // Disabled inside of `Fn` or `fn` syntax.
2095 collect_elided_lifetimes: bool,
2096 // The lifetime found.
2097 // Multiple different or elided lifetimes cannot appear in async fn for now.
2098 output_lifetime: Option<(hir::LifetimeName, Span)>,
2101 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
2102 fn nested_visit_map<'this>(
2104 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
2105 hir::intravisit::NestedVisitorMap::None
2108 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
2109 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2110 if parameters.parenthesized {
2111 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2112 self.collect_elided_lifetimes = false;
2113 hir::intravisit::walk_generic_args(self, span, parameters);
2114 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2116 hir::intravisit::walk_generic_args(self, span, parameters);
2120 fn visit_ty(&mut self, t: &'v hir::Ty) {
2121 // Don't collect elided lifetimes used inside of `fn()` syntax
2122 if let &hir::TyKind::BareFn(_) = &t.node {
2123 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2124 self.collect_elided_lifetimes = false;
2126 // Record the "stack height" of `for<'a>` lifetime bindings
2127 // to be able to later fully undo their introduction.
2128 let old_len = self.currently_bound_lifetimes.len();
2129 hir::intravisit::walk_ty(self, t);
2130 self.currently_bound_lifetimes.truncate(old_len);
2132 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2134 hir::intravisit::walk_ty(self, t);
2138 fn visit_poly_trait_ref(
2140 trait_ref: &'v hir::PolyTraitRef,
2141 modifier: hir::TraitBoundModifier,
2143 // Record the "stack height" of `for<'a>` lifetime bindings
2144 // to be able to later fully undo their introduction.
2145 let old_len = self.currently_bound_lifetimes.len();
2146 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2147 self.currently_bound_lifetimes.truncate(old_len);
2150 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2151 // Record the introduction of 'a in `for<'a> ...`
2152 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2153 // Introduce lifetimes one at a time so that we can handle
2154 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2155 let lt_name = hir::LifetimeName::Param(param.name);
2156 self.currently_bound_lifetimes.push(lt_name);
2159 hir::intravisit::walk_generic_param(self, param);
2162 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2163 let name = match lifetime.name {
2164 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2165 if self.collect_elided_lifetimes {
2166 // Use `'_` for both implicit and underscore lifetimes in
2167 // `abstract type Foo<'_>: SomeTrait<'_>;`
2168 hir::LifetimeName::Underscore
2173 hir::LifetimeName::Param(_) => lifetime.name,
2174 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
2177 if !self.currently_bound_lifetimes.contains(&name) {
2178 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2179 // We don't currently have a reliable way to desugar `async fn` with
2180 // multiple potentially unrelated input lifetimes into
2181 // `-> impl Trait + 'lt`, so we report an error in this case.
2182 if current_lt_name != name {
2185 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2187 "multiple different lifetimes used in arguments of `async fn`",
2189 .span_label(current_lt_span, "first lifetime here")
2190 .span_label(lifetime.span, "different lifetime here")
2191 .help("`async fn` can only accept borrowed values \
2192 with identical lifetimes")
2194 } else if current_lt_name.is_elided() && name.is_elided() {
2197 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2199 "multiple elided lifetimes used in arguments of `async fn`",
2201 .span_label(current_lt_span, "first lifetime here")
2202 .span_label(lifetime.span, "different lifetime here")
2203 .help("consider giving these arguments named lifetimes")
2207 self.output_lifetime = Some((name, lifetime.span));
2213 let bound_lifetime = {
2214 let mut lifetime_collector = AsyncFnLifetimeCollector {
2216 currently_bound_lifetimes: Vec::new(),
2217 collect_elided_lifetimes: true,
2218 output_lifetime: None,
2222 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2224 lifetime_collector.output_lifetime
2227 let span = match output {
2228 FunctionRetTy::Ty(ty) => ty.span,
2229 FunctionRetTy::Default(span) => *span,
2232 let impl_trait_ty = self.lower_existential_impl_trait(
2233 span, Some(fn_def_id), return_impl_trait_id, |this| {
2234 let output_ty = match output {
2235 FunctionRetTy::Ty(ty) => {
2236 this.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2238 FunctionRetTy::Default(span) => {
2239 let LoweredNodeId { node_id, hir_id } = this.next_id();
2243 node: hir::TyKind::Tup(hir_vec![]),
2250 let future_params = P(hir::GenericArgs {
2252 bindings: hir_vec![hir::TypeBinding {
2253 ident: Ident::from_str(FN_OUTPUT_NAME),
2255 id: this.next_id().node_id,
2258 parenthesized: false,
2262 this.std_path(span, &["future", "Future"], Some(future_params), false);
2264 let LoweredNodeId { node_id, hir_id } = this.next_id();
2265 let mut bounds = vec![
2266 hir::GenericBound::Trait(
2268 trait_ref: hir::TraitRef {
2273 bound_generic_params: hir_vec![],
2276 hir::TraitBoundModifier::None
2280 if let Some((name, span)) = bound_lifetime {
2281 bounds.push(hir::GenericBound::Outlives(
2282 hir::Lifetime { id: this.next_id().node_id, name, span }));
2285 hir::HirVec::from(bounds)
2288 let LoweredNodeId { node_id, hir_id } = self.next_id();
2289 let impl_trait_ty = P(hir::Ty {
2291 node: impl_trait_ty,
2296 hir::FunctionRetTy::Return(impl_trait_ty)
2299 fn lower_param_bound(
2302 itctx: ImplTraitContext<'_>,
2303 ) -> hir::GenericBound {
2305 GenericBound::Trait(ref ty, modifier) => {
2306 hir::GenericBound::Trait(
2307 self.lower_poly_trait_ref(ty, itctx),
2308 self.lower_trait_bound_modifier(modifier),
2311 GenericBound::Outlives(ref lifetime) => {
2312 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2317 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2318 let span = l.ident.span;
2320 ident if ident.name == keywords::StaticLifetime.name() =>
2321 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2322 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2323 match self.anonymous_lifetime_mode {
2324 AnonymousLifetimeMode::CreateParameter => {
2325 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2326 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2329 AnonymousLifetimeMode::PassThrough => {
2330 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2333 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2336 self.maybe_collect_in_band_lifetime(ident);
2337 let param_name = ParamName::Plain(ident);
2338 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2343 fn new_named_lifetime(
2347 name: hir::LifetimeName,
2348 ) -> hir::Lifetime {
2350 id: self.lower_node_id(id).node_id,
2356 fn lower_generic_params(
2358 params: &[GenericParam],
2359 add_bounds: &NodeMap<Vec<GenericBound>>,
2360 mut itctx: ImplTraitContext<'_>,
2361 ) -> hir::HirVec<hir::GenericParam> {
2362 params.iter().map(|param| {
2363 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2367 fn lower_generic_param(&mut self,
2368 param: &GenericParam,
2369 add_bounds: &NodeMap<Vec<GenericBound>>,
2370 mut itctx: ImplTraitContext<'_>)
2371 -> hir::GenericParam {
2372 let mut bounds = self.with_anonymous_lifetime_mode(
2373 AnonymousLifetimeMode::ReportError,
2374 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2378 GenericParamKind::Lifetime => {
2379 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2380 self.is_collecting_in_band_lifetimes = false;
2382 let lt = self.with_anonymous_lifetime_mode(
2383 AnonymousLifetimeMode::ReportError,
2384 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2386 let param_name = match lt.name {
2387 hir::LifetimeName::Param(param_name) => param_name,
2388 hir::LifetimeName::Implicit
2389 | hir::LifetimeName::Underscore
2390 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2391 hir::LifetimeName::Error => ParamName::Error,
2393 let param = hir::GenericParam {
2397 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2398 attrs: self.lower_attrs(¶m.attrs),
2400 kind: hir::GenericParamKind::Lifetime {
2401 kind: hir::LifetimeParamKind::Explicit,
2405 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2409 GenericParamKind::Type { ref default, .. } => {
2410 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2411 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2412 // Instead, use gensym("Self") to create a distinct name that looks the same.
2413 let ident = if param.ident.name == keywords::SelfType.name() {
2414 param.ident.gensym()
2419 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2420 if !add_bounds.is_empty() {
2421 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2422 bounds = bounds.into_iter()
2428 id: self.lower_node_id(param.id).node_id,
2429 name: hir::ParamName::Plain(ident),
2430 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2431 attrs: self.lower_attrs(¶m.attrs),
2434 kind: hir::GenericParamKind::Type {
2435 default: default.as_ref().map(|x| {
2436 self.lower_ty(x, ImplTraitContext::disallowed())
2438 synthetic: param.attrs.iter()
2439 .filter(|attr| attr.check_name("rustc_synthetic"))
2440 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2450 generics: &Generics,
2451 itctx: ImplTraitContext<'_>)
2454 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2455 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2456 // paths where report_error is called are also the only paths that advance to after
2457 // the match statement, so the error reporting could probably just be moved there.
2458 let mut add_bounds: NodeMap<Vec<_>> = NodeMap();
2459 for pred in &generics.where_clause.predicates {
2460 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2461 'next_bound: for bound in &bound_pred.bounds {
2462 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2463 let report_error = |this: &mut Self| {
2464 this.diagnostic().span_err(
2465 bound_pred.bounded_ty.span,
2466 "`?Trait` bounds are only permitted at the \
2467 point where a type parameter is declared",
2470 // Check if the where clause type is a plain type parameter.
2471 match bound_pred.bounded_ty.node {
2472 TyKind::Path(None, ref path)
2473 if path.segments.len() == 1
2474 && bound_pred.bound_generic_params.is_empty() =>
2476 if let Some(Def::TyParam(def_id)) = self.resolver
2477 .get_resolution(bound_pred.bounded_ty.id)
2478 .map(|d| d.base_def())
2480 if let Some(node_id) =
2481 self.resolver.definitions().as_local_node_id(def_id)
2483 for param in &generics.params {
2485 GenericParamKind::Type { .. } => {
2486 if node_id == param.id {
2487 add_bounds.entry(param.id)
2489 .push(bound.clone());
2490 continue 'next_bound;
2500 _ => report_error(self),
2508 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2509 where_clause: self.lower_where_clause(&generics.where_clause),
2510 span: generics.span,
2514 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2515 self.with_anonymous_lifetime_mode(
2516 AnonymousLifetimeMode::ReportError,
2519 id: this.lower_node_id(wc.id).node_id,
2520 predicates: wc.predicates
2522 .map(|predicate| this.lower_where_predicate(predicate))
2529 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2531 WherePredicate::BoundPredicate(WhereBoundPredicate {
2532 ref bound_generic_params,
2537 self.with_in_scope_lifetime_defs(
2538 &bound_generic_params,
2540 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2541 bound_generic_params: this.lower_generic_params(
2542 bound_generic_params,
2544 ImplTraitContext::disallowed(),
2546 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
2549 .filter_map(|bound| match *bound {
2550 // Ignore `?Trait` bounds.
2551 // Tthey were copied into type parameters already.
2552 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2553 _ => Some(this.lower_param_bound(
2555 ImplTraitContext::disallowed(),
2564 WherePredicate::RegionPredicate(WhereRegionPredicate {
2568 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2570 lifetime: self.lower_lifetime(lifetime),
2571 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2573 WherePredicate::EqPredicate(WhereEqPredicate {
2578 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2579 id: self.lower_node_id(id).node_id,
2580 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
2581 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
2587 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2589 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2593 .map(|f| self.lower_struct_field(f))
2595 self.lower_node_id(id).node_id,
2597 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2601 .map(|f| self.lower_struct_field(f))
2603 self.lower_node_id(id).node_id,
2605 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2609 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2610 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2611 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2612 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2614 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.ref_id);
2622 fn lower_poly_trait_ref(
2625 mut itctx: ImplTraitContext<'_>,
2626 ) -> hir::PolyTraitRef {
2627 let bound_generic_params =
2628 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx.reborrow());
2629 let trait_ref = self.with_parent_impl_lifetime_defs(
2630 &bound_generic_params,
2631 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2635 bound_generic_params,
2641 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2644 id: self.lower_node_id(f.id).node_id,
2645 ident: match f.ident {
2646 Some(ident) => ident,
2647 // FIXME(jseyfried) positional field hygiene
2648 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2650 vis: self.lower_visibility(&f.vis, None),
2651 ty: self.lower_ty(&f.ty, ImplTraitContext::disallowed()),
2652 attrs: self.lower_attrs(&f.attrs),
2656 fn lower_field(&mut self, f: &Field) -> hir::Field {
2658 id: self.next_id().node_id,
2660 expr: P(self.lower_expr(&f.expr)),
2662 is_shorthand: f.is_shorthand,
2666 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2668 ty: self.lower_ty(&mt.ty, itctx),
2669 mutbl: self.lower_mutability(mt.mutbl),
2673 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2674 -> hir::GenericBounds {
2675 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2678 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2679 let mut expr = None;
2681 let mut stmts = vec![];
2683 for (index, stmt) in b.stmts.iter().enumerate() {
2684 if index == b.stmts.len() - 1 {
2685 if let StmtKind::Expr(ref e) = stmt.node {
2686 expr = Some(P(self.lower_expr(e)));
2688 stmts.extend(self.lower_stmt(stmt));
2691 stmts.extend(self.lower_stmt(stmt));
2695 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2700 stmts: stmts.into(),
2702 rules: self.lower_block_check_mode(&b.rules),
2705 recovered: b.recovered,
2709 fn lower_async_body(
2715 self.lower_body(Some(decl), |this| {
2716 if let IsAsync::Async { closure_id, .. } = asyncness {
2717 let async_expr = this.make_async_expr(
2718 CaptureBy::Value, closure_id, None,
2720 let body = this.lower_block(body, false);
2721 this.expr_block(body, ThinVec::new())
2723 this.expr(body.span, async_expr, ThinVec::new())
2725 let body = this.lower_block(body, false);
2726 this.expr_block(body, ThinVec::new())
2735 attrs: &hir::HirVec<Attribute>,
2736 vis: &mut hir::Visibility,
2738 ) -> hir::ItemKind {
2740 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2741 ItemKind::Use(ref use_tree) => {
2742 // Start with an empty prefix
2745 span: use_tree.span,
2748 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2750 ItemKind::Static(ref t, m, ref e) => {
2751 let value = self.lower_body(None, |this| this.lower_expr(e));
2752 hir::ItemKind::Static(
2755 if self.sess.features_untracked().impl_trait_in_bindings {
2756 ImplTraitContext::Existential(None)
2758 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2761 self.lower_mutability(m),
2765 ItemKind::Const(ref t, ref e) => {
2766 let value = self.lower_body(None, |this| this.lower_expr(e));
2767 hir::ItemKind::Const(
2770 if self.sess.features_untracked().impl_trait_in_bindings {
2771 ImplTraitContext::Existential(None)
2773 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2779 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2780 let fn_def_id = self.resolver.definitions().local_def_id(id);
2781 self.with_new_scopes(|this| {
2782 // Note: we don't need to change the return type from `T` to
2783 // `impl Future<Output = T>` here because lower_body
2784 // only cares about the input argument patterns in the function
2785 // declaration (decl), not the return types.
2786 let body_id = this.lower_async_body(decl, header.asyncness, body);
2788 let (generics, fn_decl) = this.add_in_band_defs(
2791 AnonymousLifetimeMode::PassThrough,
2792 |this, idty| this.lower_fn_decl(
2794 Some((fn_def_id, idty)),
2796 header.asyncness.opt_return_id()
2802 this.lower_fn_header(header),
2808 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2809 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2810 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2811 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2812 self.lower_ty(t, ImplTraitContext::disallowed()),
2813 self.lower_generics(generics, ImplTraitContext::disallowed()),
2815 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2816 generics: self.lower_generics(generics, ImplTraitContext::disallowed()),
2817 bounds: self.lower_param_bounds(b, ImplTraitContext::disallowed()),
2818 impl_trait_fn: None,
2820 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2822 variants: enum_definition
2825 .map(|x| self.lower_variant(x))
2828 self.lower_generics(generics, ImplTraitContext::disallowed()),
2830 ItemKind::Struct(ref struct_def, ref generics) => {
2831 let struct_def = self.lower_variant_data(struct_def);
2832 hir::ItemKind::Struct(
2834 self.lower_generics(generics, ImplTraitContext::disallowed()),
2837 ItemKind::Union(ref vdata, ref generics) => {
2838 let vdata = self.lower_variant_data(vdata);
2839 hir::ItemKind::Union(
2841 self.lower_generics(generics, ImplTraitContext::disallowed()),
2853 let def_id = self.resolver.definitions().local_def_id(id);
2855 // Lower the "impl header" first. This ordering is important
2856 // for in-band lifetimes! Consider `'a` here:
2858 // impl Foo<'a> for u32 {
2859 // fn method(&'a self) { .. }
2862 // Because we start by lowering the `Foo<'a> for u32`
2863 // part, we will add `'a` to the list of generics on
2864 // the impl. When we then encounter it later in the
2865 // method, it will not be considered an in-band
2866 // lifetime to be added, but rather a reference to a
2868 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2871 AnonymousLifetimeMode::CreateParameter,
2873 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2874 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
2877 if let Some(ref trait_ref) = trait_ref {
2878 if let Def::Trait(def_id) = trait_ref.path.def {
2879 this.trait_impls.entry(def_id).or_default().push(id);
2883 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
2885 (trait_ref, lowered_ty)
2889 let new_impl_items = self.with_in_scope_lifetime_defs(
2890 &ast_generics.params,
2894 .map(|item| this.lower_impl_item_ref(item))
2899 hir::ItemKind::Impl(
2900 self.lower_unsafety(unsafety),
2901 self.lower_impl_polarity(polarity),
2902 self.lower_defaultness(defaultness, true /* [1] */),
2909 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2910 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
2913 .map(|item| self.lower_trait_item_ref(item))
2915 hir::ItemKind::Trait(
2916 self.lower_is_auto(is_auto),
2917 self.lower_unsafety(unsafety),
2918 self.lower_generics(generics, ImplTraitContext::disallowed()),
2923 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
2924 self.lower_generics(generics, ImplTraitContext::disallowed()),
2925 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2927 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2930 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2931 // not cause an assertion failure inside the `lower_defaultness` function
2939 vis: &mut hir::Visibility,
2941 attrs: &hir::HirVec<Attribute>,
2942 ) -> hir::ItemKind {
2943 let path = &tree.prefix;
2946 UseTreeKind::Simple(rename, id1, id2) => {
2947 *name = tree.ident().name;
2949 // First apply the prefix to the path
2950 let mut path = Path {
2954 .chain(path.segments.iter())
2960 // Correctly resolve `self` imports
2961 if path.segments.len() > 1
2962 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2964 let _ = path.segments.pop();
2965 if rename.is_none() {
2966 *name = path.segments.last().unwrap().ident.name;
2970 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2971 let mut defs = self.expect_full_def_from_use(id);
2972 // we want to return *something* from this function, so hang onto the first item
2974 let ret_def = defs.next().unwrap_or(Def::Err);
2976 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2977 let vis = vis.clone();
2978 let name = name.clone();
2979 let span = path.span;
2980 self.resolver.definitions().create_def_with_parent(
2984 DefIndexAddressSpace::High,
2987 self.allocate_hir_id_counter(new_node_id, &path);
2989 self.with_hir_id_owner(new_node_id, |this| {
2990 let new_id = this.lower_node_id(new_node_id);
2991 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2992 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
2993 let vis_kind = match vis.node {
2994 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2995 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2996 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2997 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
2998 let id = this.next_id();
2999 hir::VisibilityKind::Restricted {
3001 // We are allocating a new NodeId here
3007 let vis = respan(vis.span, vis_kind);
3013 hir_id: new_id.hir_id,
3015 attrs: attrs.clone(),
3024 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
3025 hir::ItemKind::Use(path, hir::UseKind::Single)
3027 UseTreeKind::Glob => {
3028 let path = P(self.lower_path(
3034 .chain(path.segments.iter())
3039 ParamMode::Explicit,
3041 hir::ItemKind::Use(path, hir::UseKind::Glob)
3043 UseTreeKind::Nested(ref trees) => {
3048 .chain(path.segments.iter())
3051 span: prefix.span.to(path.span),
3054 // Add all the nested PathListItems in the HIR
3055 for &(ref use_tree, id) in trees {
3056 self.allocate_hir_id_counter(id, &use_tree);
3060 } = self.lower_node_id(id);
3062 let mut vis = vis.clone();
3063 let mut name = name.clone();
3065 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
3067 self.with_hir_id_owner(new_id, |this| {
3068 let vis_kind = match vis.node {
3069 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3070 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3071 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3072 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3073 let id = this.next_id();
3074 hir::VisibilityKind::Restricted {
3076 // We are allocating a new NodeId here
3082 let vis = respan(vis.span, vis_kind);
3090 attrs: attrs.clone(),
3093 span: use_tree.span,
3099 // Privatize the degenerate import base, used only to check
3100 // the stability of `use a::{};`, to avoid it showing up as
3101 // a re-export by accident when `pub`, e.g. in documentation.
3102 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
3103 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3104 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3109 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3110 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3111 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
3113 let (generics, node) = match i.node {
3114 TraitItemKind::Const(ref ty, ref default) => (
3115 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3116 hir::TraitItemKind::Const(
3117 self.lower_ty(ty, ImplTraitContext::disallowed()),
3120 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
3123 TraitItemKind::Method(ref sig, None) => {
3124 let names = self.lower_fn_args_to_names(&sig.decl);
3125 let (generics, sig) = self.lower_method_sig(
3132 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3134 TraitItemKind::Method(ref sig, Some(ref body)) => {
3135 let body_id = self.lower_body(Some(&sig.decl), |this| {
3136 let body = this.lower_block(body, false);
3137 this.expr_block(body, ThinVec::new())
3139 let (generics, sig) = self.lower_method_sig(
3146 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3148 TraitItemKind::Type(ref bounds, ref default) => (
3149 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3150 hir::TraitItemKind::Type(
3151 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3154 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3157 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3164 attrs: self.lower_attrs(&i.attrs),
3171 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3172 let (kind, has_default) = match i.node {
3173 TraitItemKind::Const(_, ref default) => {
3174 (hir::AssociatedItemKind::Const, default.is_some())
3176 TraitItemKind::Type(_, ref default) => {
3177 (hir::AssociatedItemKind::Type, default.is_some())
3179 TraitItemKind::Method(ref sig, ref default) => (
3180 hir::AssociatedItemKind::Method {
3181 has_self: sig.decl.has_self(),
3185 TraitItemKind::Macro(..) => unimplemented!(),
3188 id: hir::TraitItemId { node_id: i.id },
3191 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3196 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3197 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3198 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3200 let (generics, node) = match i.node {
3201 ImplItemKind::Const(ref ty, ref expr) => {
3202 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3204 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3205 hir::ImplItemKind::Const(
3206 self.lower_ty(ty, ImplTraitContext::disallowed()),
3211 ImplItemKind::Method(ref sig, ref body) => {
3212 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3213 let impl_trait_return_allow = !self.is_in_trait_impl;
3214 let (generics, sig) = self.lower_method_sig(
3218 impl_trait_return_allow,
3219 sig.header.asyncness.opt_return_id(),
3221 (generics, hir::ImplItemKind::Method(sig, body_id))
3223 ImplItemKind::Type(ref ty) => (
3224 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3225 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3227 ImplItemKind::Existential(ref bounds) => (
3228 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3229 hir::ImplItemKind::Existential(
3230 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3233 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3240 attrs: self.lower_attrs(&i.attrs),
3242 vis: self.lower_visibility(&i.vis, None),
3243 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3248 // [1] since `default impl` is not yet implemented, this is always true in impls
3251 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3253 id: hir::ImplItemId { node_id: i.id },
3256 vis: self.lower_visibility(&i.vis, Some(i.id)),
3257 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3258 kind: match i.node {
3259 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3260 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3261 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3262 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3263 has_self: sig.decl.has_self(),
3265 ImplItemKind::Macro(..) => unimplemented!(),
3269 // [1] since `default impl` is not yet implemented, this is always true in impls
3272 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3275 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3279 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3281 ItemKind::Use(ref use_tree) => {
3282 let mut vec = smallvec![hir::ItemId { id: i.id }];
3283 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3286 ItemKind::MacroDef(..) => SmallVec::new(),
3288 ItemKind::Impl(.., None, _, _) => smallvec![hir::ItemId { id: i.id }],
3289 ItemKind::Static(ref ty, ..) => {
3290 let mut ids = smallvec![hir::ItemId { id: i.id }];
3291 if self.sess.features_untracked().impl_trait_in_bindings {
3292 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3293 visitor.visit_ty(ty);
3297 ItemKind::Const(ref ty, ..) => {
3298 let mut ids = smallvec![hir::ItemId { id: i.id }];
3299 if self.sess.features_untracked().impl_trait_in_bindings {
3300 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3301 visitor.visit_ty(ty);
3305 _ => smallvec![hir::ItemId { id: i.id }],
3309 fn lower_item_id_use_tree(&mut self,
3312 vec: &mut SmallVec<[hir::ItemId; 1]>)
3315 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3316 vec.push(hir::ItemId { id });
3317 self.lower_item_id_use_tree(nested, id, vec);
3319 UseTreeKind::Glob => {}
3320 UseTreeKind::Simple(_, id1, id2) => {
3321 for (_, &id) in self.expect_full_def_from_use(base_id)
3323 .zip([id1, id2].iter())
3325 vec.push(hir::ItemId { id });
3331 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3332 let mut name = i.ident.name;
3333 let mut vis = self.lower_visibility(&i.vis, None);
3334 let attrs = self.lower_attrs(&i.attrs);
3335 if let ItemKind::MacroDef(ref def) = i.node {
3336 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3337 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3338 let body = self.lower_token_stream(def.stream());
3339 self.exported_macros.push(hir::MacroDef {
3352 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3354 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3367 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3368 let node_id = self.lower_node_id(i.id).node_id;
3369 let def_id = self.resolver.definitions().local_def_id(node_id);
3373 attrs: self.lower_attrs(&i.attrs),
3374 node: match i.node {
3375 ForeignItemKind::Fn(ref fdec, ref generics) => {
3376 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3379 AnonymousLifetimeMode::PassThrough,
3382 // Disallow impl Trait in foreign items
3383 this.lower_fn_decl(fdec, None, false, None),
3384 this.lower_fn_args_to_names(fdec),
3389 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3391 ForeignItemKind::Static(ref t, m) => {
3392 hir::ForeignItemKind::Static(
3393 self.lower_ty(t, ImplTraitContext::disallowed()), m)
3395 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3396 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3398 vis: self.lower_visibility(&i.vis, None),
3403 fn lower_method_sig(
3405 generics: &Generics,
3408 impl_trait_return_allow: bool,
3409 is_async: Option<NodeId>,
3410 ) -> (hir::Generics, hir::MethodSig) {
3411 let header = self.lower_fn_header(sig.header);
3412 let (generics, decl) = self.add_in_band_defs(
3415 AnonymousLifetimeMode::PassThrough,
3416 |this, idty| this.lower_fn_decl(
3418 Some((fn_def_id, idty)),
3419 impl_trait_return_allow,
3423 (generics, hir::MethodSig { header, decl })
3426 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3428 IsAuto::Yes => hir::IsAuto::Yes,
3429 IsAuto::No => hir::IsAuto::No,
3433 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3435 unsafety: self.lower_unsafety(h.unsafety),
3436 asyncness: self.lower_asyncness(h.asyncness),
3437 constness: self.lower_constness(h.constness),
3442 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3444 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3445 Unsafety::Normal => hir::Unsafety::Normal,
3449 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3451 Constness::Const => hir::Constness::Const,
3452 Constness::NotConst => hir::Constness::NotConst,
3456 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3458 IsAsync::Async { .. } => hir::IsAsync::Async,
3459 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3463 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3465 UnOp::Deref => hir::UnDeref,
3466 UnOp::Not => hir::UnNot,
3467 UnOp::Neg => hir::UnNeg,
3471 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3473 node: match b.node {
3474 BinOpKind::Add => hir::BinOpKind::Add,
3475 BinOpKind::Sub => hir::BinOpKind::Sub,
3476 BinOpKind::Mul => hir::BinOpKind::Mul,
3477 BinOpKind::Div => hir::BinOpKind::Div,
3478 BinOpKind::Rem => hir::BinOpKind::Rem,
3479 BinOpKind::And => hir::BinOpKind::And,
3480 BinOpKind::Or => hir::BinOpKind::Or,
3481 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3482 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3483 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3484 BinOpKind::Shl => hir::BinOpKind::Shl,
3485 BinOpKind::Shr => hir::BinOpKind::Shr,
3486 BinOpKind::Eq => hir::BinOpKind::Eq,
3487 BinOpKind::Lt => hir::BinOpKind::Lt,
3488 BinOpKind::Le => hir::BinOpKind::Le,
3489 BinOpKind::Ne => hir::BinOpKind::Ne,
3490 BinOpKind::Ge => hir::BinOpKind::Ge,
3491 BinOpKind::Gt => hir::BinOpKind::Gt,
3497 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3498 let node = match p.node {
3499 PatKind::Wild => hir::PatKind::Wild,
3500 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3501 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3502 // `None` can occur in body-less function signatures
3503 def @ None | def @ Some(Def::Local(_)) => {
3504 let canonical_id = match def {
3505 Some(Def::Local(id)) => id,
3508 hir::PatKind::Binding(
3509 self.lower_binding_mode(binding_mode),
3512 sub.as_ref().map(|x| self.lower_pat(x)),
3515 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3520 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3525 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3526 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3527 let qpath = self.lower_qpath(
3531 ParamMode::Optional,
3532 ImplTraitContext::disallowed(),
3534 self.check_self_struct_ctor_feature(&qpath);
3535 hir::PatKind::TupleStruct(
3537 pats.iter().map(|x| self.lower_pat(x)).collect(),
3541 PatKind::Path(ref qself, ref path) => {
3542 let qpath = self.lower_qpath(
3546 ParamMode::Optional,
3547 ImplTraitContext::disallowed(),
3549 self.check_self_struct_ctor_feature(&qpath);
3550 hir::PatKind::Path(qpath)
3552 PatKind::Struct(ref path, ref fields, etc) => {
3553 let qpath = self.lower_qpath(
3557 ParamMode::Optional,
3558 ImplTraitContext::disallowed(),
3565 node: hir::FieldPat {
3566 id: self.next_id().node_id,
3567 ident: f.node.ident,
3568 pat: self.lower_pat(&f.node.pat),
3569 is_shorthand: f.node.is_shorthand,
3573 hir::PatKind::Struct(qpath, fs, etc)
3575 PatKind::Tuple(ref elts, ddpos) => {
3576 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3578 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3579 PatKind::Ref(ref inner, mutbl) => {
3580 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3582 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3583 P(self.lower_expr(e1)),
3584 P(self.lower_expr(e2)),
3585 self.lower_range_end(end),
3587 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3588 before.iter().map(|x| self.lower_pat(x)).collect(),
3589 slice.as_ref().map(|x| self.lower_pat(x)),
3590 after.iter().map(|x| self.lower_pat(x)).collect(),
3592 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3593 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3596 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3605 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3607 RangeEnd::Included(_) => hir::RangeEnd::Included,
3608 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3612 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3613 self.with_new_scopes(|this| {
3614 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3618 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3623 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3624 let kind = match e.node {
3625 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3626 ExprKind::ObsoleteInPlace(..) => {
3627 self.sess.abort_if_errors();
3628 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3630 ExprKind::Array(ref exprs) => {
3631 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3633 ExprKind::Repeat(ref expr, ref count) => {
3634 let expr = P(self.lower_expr(expr));
3635 let count = self.lower_anon_const(count);
3636 hir::ExprKind::Repeat(expr, count)
3638 ExprKind::Tup(ref elts) => {
3639 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3641 ExprKind::Call(ref f, ref args) => {
3642 let f = P(self.lower_expr(f));
3643 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3645 ExprKind::MethodCall(ref seg, ref args) => {
3646 let hir_seg = self.lower_path_segment(
3649 ParamMode::Optional,
3651 ParenthesizedGenericArgs::Err,
3652 ImplTraitContext::disallowed(),
3654 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3655 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3657 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3658 let binop = self.lower_binop(binop);
3659 let lhs = P(self.lower_expr(lhs));
3660 let rhs = P(self.lower_expr(rhs));
3661 hir::ExprKind::Binary(binop, lhs, rhs)
3663 ExprKind::Unary(op, ref ohs) => {
3664 let op = self.lower_unop(op);
3665 let ohs = P(self.lower_expr(ohs));
3666 hir::ExprKind::Unary(op, ohs)
3668 ExprKind::Lit(ref l) => hir::ExprKind::Lit(P((**l).clone())),
3669 ExprKind::Cast(ref expr, ref ty) => {
3670 let expr = P(self.lower_expr(expr));
3671 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3673 ExprKind::Type(ref expr, ref ty) => {
3674 let expr = P(self.lower_expr(expr));
3675 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3677 ExprKind::AddrOf(m, ref ohs) => {
3678 let m = self.lower_mutability(m);
3679 let ohs = P(self.lower_expr(ohs));
3680 hir::ExprKind::AddrOf(m, ohs)
3682 // More complicated than you might expect because the else branch
3683 // might be `if let`.
3684 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3685 let else_opt = else_opt.as_ref().map(|els| {
3687 ExprKind::IfLet(..) => {
3688 // wrap the if-let expr in a block
3689 let span = els.span;
3690 let els = P(self.lower_expr(els));
3691 let LoweredNodeId { node_id, hir_id } = self.next_id();
3692 let blk = P(hir::Block {
3697 rules: hir::DefaultBlock,
3699 targeted_by_break: false,
3700 recovered: blk.recovered,
3702 P(self.expr_block(blk, ThinVec::new()))
3704 _ => P(self.lower_expr(els)),
3708 let then_blk = self.lower_block(blk, false);
3709 let then_expr = self.expr_block(then_blk, ThinVec::new());
3711 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3713 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3714 hir::ExprKind::While(
3715 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3716 this.lower_block(body, false),
3717 this.lower_label(opt_label),
3720 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3721 hir::ExprKind::Loop(
3722 this.lower_block(body, false),
3723 this.lower_label(opt_label),
3724 hir::LoopSource::Loop,
3727 ExprKind::TryBlock(ref body) => {
3728 self.with_catch_scope(body.id, |this| {
3730 this.allow_internal_unstable(CompilerDesugaringKind::TryBlock, body.span);
3731 let mut block = this.lower_block(body, true).into_inner();
3732 let tail = block.expr.take().map_or_else(
3734 let LoweredNodeId { node_id, hir_id } = this.next_id();
3735 let span = this.sess.source_map().end_point(unstable_span);
3739 node: hir::ExprKind::Tup(hir_vec![]),
3740 attrs: ThinVec::new(),
3744 |x: P<hir::Expr>| x.into_inner(),
3746 block.expr = Some(this.wrap_in_try_constructor(
3747 "from_ok", tail, unstable_span));
3748 hir::ExprKind::Block(P(block), None)
3751 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3752 P(self.lower_expr(expr)),
3753 arms.iter().map(|x| self.lower_arm(x)).collect(),
3754 hir::MatchSource::Normal,
3756 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3757 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3758 this.with_new_scopes(|this| {
3759 let block = this.lower_block(block, false);
3760 this.expr_block(block, ThinVec::new())
3765 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3767 if let IsAsync::Async { closure_id, .. } = asyncness {
3768 let outer_decl = FnDecl {
3769 inputs: decl.inputs.clone(),
3770 output: FunctionRetTy::Default(fn_decl_span),
3773 // We need to lower the declaration outside the new scope, because we
3774 // have to conserve the state of being inside a loop condition for the
3775 // closure argument types.
3776 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3778 self.with_new_scopes(|this| {
3779 // FIXME(cramertj) allow `async` non-`move` closures with
3780 if capture_clause == CaptureBy::Ref &&
3781 !decl.inputs.is_empty()
3787 "`async` non-`move` closures with arguments \
3788 are not currently supported",
3790 .help("consider using `let` statements to manually capture \
3791 variables by reference before entering an \
3792 `async move` closure")
3796 // Transform `async |x: u8| -> X { ... }` into
3797 // `|x: u8| future_from_generator(|| -> X { ... })`
3798 let body_id = this.lower_body(Some(&outer_decl), |this| {
3799 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3802 let async_body = this.make_async_expr(
3803 capture_clause, closure_id, async_ret_ty,
3805 this.with_new_scopes(|this| this.lower_expr(body))
3807 this.expr(fn_decl_span, async_body, ThinVec::new())
3809 hir::ExprKind::Closure(
3810 this.lower_capture_clause(capture_clause),
3818 // Lower outside new scope to preserve `is_in_loop_condition`.
3819 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3821 self.with_new_scopes(|this| {
3822 let mut is_generator = false;
3823 let body_id = this.lower_body(Some(decl), |this| {
3824 let e = this.lower_expr(body);
3825 is_generator = this.is_generator;
3828 let generator_option = if is_generator {
3829 if !decl.inputs.is_empty() {
3834 "generators cannot have explicit arguments"
3836 this.sess.abort_if_errors();
3838 Some(match movability {
3839 Movability::Movable => hir::GeneratorMovability::Movable,
3840 Movability::Static => hir::GeneratorMovability::Static,
3843 if movability == Movability::Static {
3848 "closures cannot be static"
3853 hir::ExprKind::Closure(
3854 this.lower_capture_clause(capture_clause),
3863 ExprKind::Block(ref blk, opt_label) => {
3864 hir::ExprKind::Block(self.lower_block(blk,
3865 opt_label.is_some()),
3866 self.lower_label(opt_label))
3868 ExprKind::Assign(ref el, ref er) => {
3869 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3871 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
3872 self.lower_binop(op),
3873 P(self.lower_expr(el)),
3874 P(self.lower_expr(er)),
3876 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
3877 ExprKind::Index(ref el, ref er) => {
3878 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
3880 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3881 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3882 let id = self.next_id();
3883 let e1 = self.lower_expr(e1);
3884 let e2 = self.lower_expr(e2);
3885 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
3886 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
3887 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3888 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3889 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
3890 hir::ExprKind::Call(new, hir_vec![e1, e2])
3892 ExprKind::Range(ref e1, ref e2, lims) => {
3893 use syntax::ast::RangeLimits::*;
3895 let path = match (e1, e2, lims) {
3896 (&None, &None, HalfOpen) => "RangeFull",
3897 (&Some(..), &None, HalfOpen) => "RangeFrom",
3898 (&None, &Some(..), HalfOpen) => "RangeTo",
3899 (&Some(..), &Some(..), HalfOpen) => "Range",
3900 (&None, &Some(..), Closed) => "RangeToInclusive",
3901 (&Some(..), &Some(..), Closed) => unreachable!(),
3902 (_, &None, Closed) => self.diagnostic()
3903 .span_fatal(e.span, "inclusive range with no end")
3907 let fields = e1.iter()
3908 .map(|e| ("start", e))
3909 .chain(e2.iter().map(|e| ("end", e)))
3911 let expr = P(self.lower_expr(&e));
3912 let ident = Ident::new(Symbol::intern(s), e.span);
3913 self.field(ident, expr, e.span)
3915 .collect::<P<[hir::Field]>>();
3917 let is_unit = fields.is_empty();
3918 let struct_path = ["ops", path];
3919 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
3920 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3922 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3928 hir::ExprKind::Path(struct_path)
3930 hir::ExprKind::Struct(struct_path, fields, None)
3933 attrs: e.attrs.clone(),
3936 ExprKind::Path(ref qself, ref path) => {
3937 let qpath = self.lower_qpath(
3941 ParamMode::Optional,
3942 ImplTraitContext::disallowed(),
3944 self.check_self_struct_ctor_feature(&qpath);
3945 hir::ExprKind::Path(qpath)
3947 ExprKind::Break(opt_label, ref opt_expr) => {
3948 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3951 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3954 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3956 hir::ExprKind::Break(
3958 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3961 ExprKind::Continue(opt_label) => {
3962 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
3965 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3968 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3971 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
3972 ExprKind::InlineAsm(ref asm) => {
3973 let hir_asm = hir::InlineAsm {
3974 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3975 outputs: asm.outputs
3977 .map(|out| hir::InlineAsmOutput {
3978 constraint: out.constraint.clone(),
3980 is_indirect: out.is_indirect,
3981 span: out.expr.span,
3984 asm: asm.asm.clone(),
3985 asm_str_style: asm.asm_str_style,
3986 clobbers: asm.clobbers.clone().into(),
3987 volatile: asm.volatile,
3988 alignstack: asm.alignstack,
3989 dialect: asm.dialect,
3992 let outputs = asm.outputs
3994 .map(|out| self.lower_expr(&out.expr))
3996 let inputs = asm.inputs
3998 .map(|&(_, ref input)| self.lower_expr(input))
4000 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
4002 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4007 ParamMode::Optional,
4008 ImplTraitContext::disallowed(),
4010 fields.iter().map(|x| self.lower_field(x)).collect(),
4011 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4013 ExprKind::Paren(ref ex) => {
4014 let mut ex = self.lower_expr(ex);
4015 // include parens in span, but only if it is a super-span.
4016 if e.span.contains(ex.span) {
4019 // merge attributes into the inner expression.
4020 let mut attrs = e.attrs.clone();
4021 attrs.extend::<Vec<_>>(ex.attrs.into());
4026 ExprKind::Yield(ref opt_expr) => {
4027 self.is_generator = true;
4030 .map(|x| self.lower_expr(x))
4032 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
4034 hir::ExprKind::Yield(P(expr))
4037 // Desugar ExprIfLet
4038 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
4039 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4042 // match <sub_expr> {
4044 // _ => [<else_opt> | ()]
4047 let mut arms = vec![];
4049 // `<pat> => <body>`
4051 let body = self.lower_block(body, false);
4052 let body_expr = P(self.expr_block(body, ThinVec::new()));
4053 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4054 arms.push(self.arm(pats, body_expr));
4057 // _ => [<else_opt>|()]
4059 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4060 let wildcard_pattern = self.pat_wild(e.span);
4061 let body = if let Some(else_expr) = wildcard_arm {
4062 P(self.lower_expr(else_expr))
4064 self.expr_tuple(e.span, hir_vec![])
4066 arms.push(self.arm(hir_vec![wildcard_pattern], body));
4069 let contains_else_clause = else_opt.is_some();
4071 let sub_expr = P(self.lower_expr(sub_expr));
4073 hir::ExprKind::Match(
4076 hir::MatchSource::IfLetDesugar {
4077 contains_else_clause,
4082 // Desugar ExprWhileLet
4083 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4084 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4087 // [opt_ident]: loop {
4088 // match <sub_expr> {
4094 // Note that the block AND the condition are evaluated in the loop scope.
4095 // This is done to allow `break` from inside the condition of the loop.
4096 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4098 this.lower_block(body, false),
4099 this.expr_break(e.span, ThinVec::new()),
4100 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4104 // `<pat> => <body>`
4106 let body_expr = P(self.expr_block(body, ThinVec::new()));
4107 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4108 self.arm(pats, body_expr)
4113 let pat_under = self.pat_wild(e.span);
4114 self.arm(hir_vec![pat_under], break_expr)
4117 // `match <sub_expr> { ... }`
4118 let arms = hir_vec![pat_arm, break_arm];
4119 let match_expr = self.expr(
4121 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4125 // `[opt_ident]: loop { ... }`
4126 let loop_block = P(self.block_expr(P(match_expr)));
4127 let loop_expr = hir::ExprKind::Loop(
4129 self.lower_label(opt_label),
4130 hir::LoopSource::WhileLet,
4132 // add attributes to the outer returned expr node
4136 // Desugar ExprForLoop
4137 // From: `[opt_ident]: for <pat> in <head> <body>`
4138 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4142 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4144 // [opt_ident]: loop {
4146 // match ::std::iter::Iterator::next(&mut iter) {
4147 // ::std::option::Option::Some(val) => __next = val,
4148 // ::std::option::Option::None => break
4150 // let <pat> = __next;
4151 // StmtKind::Expr(<body>);
4159 let head = self.lower_expr(head);
4160 let head_sp = head.span;
4161 let desugared_span = self.allow_internal_unstable(
4162 CompilerDesugaringKind::ForLoop,
4166 let iter = self.str_to_ident("iter");
4168 let next_ident = self.str_to_ident("__next");
4169 let next_pat = self.pat_ident_binding_mode(
4172 hir::BindingAnnotation::Mutable,
4175 // `::std::option::Option::Some(val) => next = val`
4177 let val_ident = self.str_to_ident("val");
4178 let val_pat = self.pat_ident(pat.span, val_ident);
4179 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4180 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4181 let assign = P(self.expr(
4183 hir::ExprKind::Assign(next_expr, val_expr),
4186 let some_pat = self.pat_some(pat.span, val_pat);
4187 self.arm(hir_vec![some_pat], assign)
4190 // `::std::option::Option::None => break`
4193 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4194 let pat = self.pat_none(e.span);
4195 self.arm(hir_vec![pat], break_expr)
4199 let iter_pat = self.pat_ident_binding_mode(
4202 hir::BindingAnnotation::Mutable
4205 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4207 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4208 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4209 let next_path = &["iter", "Iterator", "next"];
4210 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4211 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4212 let arms = hir_vec![pat_arm, break_arm];
4216 hir::ExprKind::Match(
4219 hir::MatchSource::ForLoopDesugar
4224 let match_stmt = respan(
4226 hir::StmtKind::Expr(match_expr, self.next_id().node_id)
4229 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4232 let next_let = self.stmt_let_pat(
4236 hir::LocalSource::ForLoopDesugar,
4239 // `let <pat> = __next`
4240 let pat = self.lower_pat(pat);
4241 let pat_let = self.stmt_let_pat(
4245 hir::LocalSource::ForLoopDesugar,
4248 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4249 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4250 let body_stmt = respan(
4252 hir::StmtKind::Expr(body_expr, self.next_id().node_id)
4255 let loop_block = P(self.block_all(
4257 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4261 // `[opt_ident]: loop { ... }`
4262 let loop_expr = hir::ExprKind::Loop(
4264 self.lower_label(opt_label),
4265 hir::LoopSource::ForLoop,
4267 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4268 let loop_expr = P(hir::Expr {
4273 attrs: ThinVec::new(),
4276 // `mut iter => { ... }`
4277 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4279 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4280 let into_iter_expr = {
4281 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4282 let into_iter = P(self.expr_std_path(
4283 head_sp, into_iter_path, None, ThinVec::new()));
4284 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4287 let match_expr = P(self.expr_match(
4291 hir::MatchSource::ForLoopDesugar,
4294 // `{ let _result = ...; _result }`
4295 // underscore prevents an unused_variables lint if the head diverges
4296 let result_ident = self.str_to_ident("_result");
4297 let (let_stmt, let_stmt_binding) =
4298 self.stmt_let(e.span, false, result_ident, match_expr);
4300 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4301 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4302 // add the attributes to the outer returned expr node
4303 return self.expr_block(block, e.attrs.clone());
4306 // Desugar ExprKind::Try
4308 ExprKind::Try(ref sub_expr) => {
4311 // match Try::into_result(<expr>) {
4312 // Ok(val) => #[allow(unreachable_code)] val,
4313 // Err(err) => #[allow(unreachable_code)]
4314 // // If there is an enclosing `catch {...}`
4315 // break 'catch_target Try::from_error(From::from(err)),
4317 // return Try::from_error(From::from(err)),
4321 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4323 // Try::into_result(<expr>)
4326 let sub_expr = self.lower_expr(sub_expr);
4328 let path = &["ops", "Try", "into_result"];
4329 let path = P(self.expr_std_path(
4330 unstable_span, path, None, ThinVec::new()));
4331 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4334 // #[allow(unreachable_code)]
4336 // allow(unreachable_code)
4338 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4339 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4340 let uc_nested = attr::mk_nested_word_item(uc_ident);
4341 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4343 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4345 let attrs = vec![attr];
4347 // Ok(val) => #[allow(unreachable_code)] val,
4349 let val_ident = self.str_to_ident("val");
4350 let val_pat = self.pat_ident(e.span, val_ident);
4351 let val_expr = P(self.expr_ident_with_attrs(
4355 ThinVec::from(attrs.clone()),
4357 let ok_pat = self.pat_ok(e.span, val_pat);
4359 self.arm(hir_vec![ok_pat], val_expr)
4362 // Err(err) => #[allow(unreachable_code)]
4363 // return Try::from_error(From::from(err)),
4365 let err_ident = self.str_to_ident("err");
4366 let err_local = self.pat_ident(e.span, err_ident);
4368 let path = &["convert", "From", "from"];
4369 let from = P(self.expr_std_path(
4370 e.span, path, None, ThinVec::new()));
4371 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4373 self.expr_call(e.span, from, hir_vec![err_expr])
4376 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4377 let thin_attrs = ThinVec::from(attrs);
4378 let catch_scope = self.catch_scopes.last().map(|x| *x);
4379 let ret_expr = if let Some(catch_node) = catch_scope {
4382 hir::ExprKind::Break(
4385 target_id: Ok(catch_node),
4387 Some(from_err_expr),
4392 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4395 let err_pat = self.pat_err(e.span, err_local);
4396 self.arm(hir_vec![err_pat], ret_expr)
4399 hir::ExprKind::Match(
4401 hir_vec![err_arm, ok_arm],
4402 hir::MatchSource::TryDesugar,
4406 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4409 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4416 attrs: e.attrs.clone(),
4420 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
4421 smallvec![match s.node {
4422 StmtKind::Local(ref l) => {
4423 let (l, item_ids) = self.lower_local(l);
4424 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
4426 .map(|item_id| Spanned {
4427 node: hir::StmtKind::Decl(
4429 node: hir::DeclKind::Item(item_id),
4432 self.next_id().node_id,
4438 node: hir::StmtKind::Decl(
4440 node: hir::DeclKind::Local(l),
4443 self.lower_node_id(s.id).node_id,
4449 StmtKind::Item(ref it) => {
4450 // Can only use the ID once.
4451 let mut id = Some(s.id);
4452 return self.lower_item_id(it)
4454 .map(|item_id| Spanned {
4455 node: hir::StmtKind::Decl(
4457 node: hir::DeclKind::Item(item_id),
4461 .map(|id| self.lower_node_id(id).node_id)
4462 .unwrap_or_else(|| self.next_id().node_id),
4468 StmtKind::Expr(ref e) => Spanned {
4469 node: hir::StmtKind::Expr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4472 StmtKind::Semi(ref e) => Spanned {
4473 node: hir::StmtKind::Semi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4476 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4480 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4482 CaptureBy::Value => hir::CaptureByValue,
4483 CaptureBy::Ref => hir::CaptureByRef,
4487 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4488 /// the address space of that item instead of the item currently being
4489 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4490 /// lower a `Visibility` value although we haven't lowered the owning
4491 /// `ImplItem` in question yet.
4492 fn lower_visibility(
4495 explicit_owner: Option<NodeId>,
4496 ) -> hir::Visibility {
4497 let node = match v.node {
4498 VisibilityKind::Public => hir::VisibilityKind::Public,
4499 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4500 VisibilityKind::Restricted { ref path, id } => {
4501 let lowered_id = if let Some(owner) = explicit_owner {
4502 self.lower_node_id_with_owner(id, owner)
4504 self.lower_node_id(id)
4506 hir::VisibilityKind::Restricted {
4507 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4508 id: lowered_id.node_id,
4509 hir_id: lowered_id.hir_id,
4512 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4514 respan(v.span, node)
4517 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4519 Defaultness::Default => hir::Defaultness::Default {
4520 has_value: has_value,
4522 Defaultness::Final => {
4524 hir::Defaultness::Final
4529 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4531 BlockCheckMode::Default => hir::DefaultBlock,
4532 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4536 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4538 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4539 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4540 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4541 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4545 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4547 CompilerGenerated => hir::CompilerGenerated,
4548 UserProvided => hir::UserProvided,
4552 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4554 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4555 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4559 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4561 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4562 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4566 // Helper methods for building HIR.
4568 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4577 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4579 id: self.next_id().node_id,
4583 is_shorthand: false,
4587 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4588 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4589 P(self.expr(span, expr_break, attrs))
4596 args: hir::HirVec<hir::Expr>,
4598 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4601 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4602 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4605 fn expr_ident_with_attrs(
4610 attrs: ThinVec<Attribute>,
4612 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4616 def: Def::Local(binding),
4617 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4621 self.expr(span, expr_path, attrs)
4624 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4625 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4631 components: &[&str],
4632 params: Option<P<hir::GenericArgs>>,
4633 attrs: ThinVec<Attribute>,
4635 let path = self.std_path(span, components, params, true);
4638 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4647 arms: hir::HirVec<hir::Arm>,
4648 source: hir::MatchSource,
4650 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4653 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4654 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4657 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4658 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4661 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4662 let LoweredNodeId { node_id, hir_id } = self.next_id();
4675 ex: Option<P<hir::Expr>>,
4677 source: hir::LocalSource,
4679 let LoweredNodeId { node_id, hir_id } = self.next_id();
4681 let local = P(hir::Local {
4688 attrs: ThinVec::new(),
4691 let decl = respan(sp, hir::DeclKind::Local(local));
4692 respan(sp, hir::StmtKind::Decl(P(decl), self.next_id().node_id))
4701 ) -> (hir::Stmt, NodeId) {
4702 let pat = if mutbl {
4703 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4705 self.pat_ident(sp, ident)
4707 let pat_id = pat.id;
4709 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4714 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4715 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4721 stmts: hir::HirVec<hir::Stmt>,
4722 expr: Option<P<hir::Expr>>,
4724 let LoweredNodeId { node_id, hir_id } = self.next_id();
4731 rules: hir::DefaultBlock,
4733 targeted_by_break: false,
4738 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4739 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4742 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4743 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4746 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4747 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4750 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4751 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4757 components: &[&str],
4758 subpats: hir::HirVec<P<hir::Pat>>,
4760 let path = self.std_path(span, components, None, true);
4761 let qpath = hir::QPath::Resolved(None, P(path));
4762 let pt = if subpats.is_empty() {
4763 hir::PatKind::Path(qpath)
4765 hir::PatKind::TupleStruct(qpath, subpats, None)
4770 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4771 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4774 fn pat_ident_binding_mode(
4778 bm: hir::BindingAnnotation,
4780 let LoweredNodeId { node_id, hir_id } = self.next_id();
4785 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4790 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4791 self.pat(span, hir::PatKind::Wild)
4794 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4795 let LoweredNodeId { node_id, hir_id } = self.next_id();
4804 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4805 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4806 /// The path is also resolved according to `is_value`.
4810 components: &[&str],
4811 params: Option<P<hir::GenericArgs>>,
4815 .resolve_str_path(span, self.crate_root, components, params, is_value)
4818 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4820 let node = match qpath {
4821 hir::QPath::Resolved(None, path) => {
4822 // Turn trait object paths into `TyKind::TraitObject` instead.
4823 if let Def::Trait(_) = path.def {
4824 let principal = hir::PolyTraitRef {
4825 bound_generic_params: hir::HirVec::new(),
4826 trait_ref: hir::TraitRef {
4827 path: path.and_then(|path| path),
4829 hir_ref_id: id.hir_id,
4834 // The original ID is taken by the `PolyTraitRef`,
4835 // so the `Ty` itself needs a different one.
4836 id = self.next_id();
4837 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4839 hir::TyKind::Path(hir::QPath::Resolved(None, path))
4842 _ => hir::TyKind::Path(qpath),
4852 /// Invoked to create the lifetime argument for a type `&T`
4853 /// with no explicit lifetime.
4854 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4855 match self.anonymous_lifetime_mode {
4856 // Intercept when we are in an impl header and introduce an in-band lifetime.
4857 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4859 AnonymousLifetimeMode::CreateParameter => {
4860 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4862 id: self.next_id().node_id,
4864 name: hir::LifetimeName::Param(fresh_name),
4868 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
4870 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4874 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
4875 /// return a "error lifetime".
4876 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
4877 let (id, msg, label) = match id {
4878 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
4881 self.next_id().node_id,
4882 "`&` without an explicit lifetime name cannot be used here",
4883 "explicit lifetime name needed here",
4887 let mut err = struct_span_err!(
4894 err.span_label(span, label);
4897 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
4900 /// Invoked to create the lifetime argument(s) for a path like
4901 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4902 /// sorts of cases are deprecated. This may therefore report a warning or an
4903 /// error, depending on the mode.
4904 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4905 match self.anonymous_lifetime_mode {
4906 // NB. We intentionally ignore the create-parameter mode here
4907 // and instead "pass through" to resolve-lifetimes, which will then
4908 // report an error. This is because we don't want to support
4909 // impl elision for deprecated forms like
4911 // impl Foo for std::cell::Ref<u32> // note lack of '_
4912 AnonymousLifetimeMode::CreateParameter => {}
4914 AnonymousLifetimeMode::ReportError => {
4916 .map(|_| self.new_error_lifetime(None, span))
4920 // This is the normal case.
4921 AnonymousLifetimeMode::PassThrough => {}
4925 .map(|_| self.new_implicit_lifetime(span))
4929 /// Invoked to create the lifetime argument(s) for an elided trait object
4930 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4931 /// when the bound is written, even if it is written with `'_` like in
4932 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4933 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4934 match self.anonymous_lifetime_mode {
4935 // NB. We intentionally ignore the create-parameter mode here.
4936 // and instead "pass through" to resolve-lifetimes, which will apply
4937 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4938 // do not act like other elided lifetimes. In other words, given this:
4940 // impl Foo for Box<dyn Debug>
4942 // we do not introduce a fresh `'_` to serve as the bound, but instead
4943 // ultimately translate to the equivalent of:
4945 // impl Foo for Box<dyn Debug + 'static>
4947 // `resolve_lifetime` has the code to make that happen.
4948 AnonymousLifetimeMode::CreateParameter => {}
4950 AnonymousLifetimeMode::ReportError => {
4951 // ReportError applies to explicit use of `'_`.
4954 // This is the normal case.
4955 AnonymousLifetimeMode::PassThrough => {}
4958 self.new_implicit_lifetime(span)
4961 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4963 id: self.next_id().node_id,
4965 name: hir::LifetimeName::Implicit,
4969 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4970 self.sess.buffer_lint_with_diagnostic(
4971 builtin::BARE_TRAIT_OBJECTS,
4974 "trait objects without an explicit `dyn` are deprecated",
4975 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4979 fn wrap_in_try_constructor(
4981 method: &'static str,
4983 unstable_span: Span,
4985 let path = &["ops", "Try", method];
4986 let from_err = P(self.expr_std_path(unstable_span, path, None,
4988 P(self.expr_call(e.span, from_err, hir_vec![e]))
4991 fn check_self_struct_ctor_feature(&self, qp: &hir::QPath) {
4992 if let hir::QPath::Resolved(_, ref p) = qp {
4993 if p.segments.len() == 1 &&
4994 p.segments[0].ident.name == keywords::SelfType.name() &&
4995 !self.sess.features_untracked().self_struct_ctor {
4996 emit_feature_err(&self.sess.parse_sess, "self_struct_ctor",
4997 p.span, GateIssue::Language,
4998 "`Self` struct constructors are unstable");
5004 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5005 // Sorting by span ensures that we get things in order within a
5006 // file, and also puts the files in a sensible order.
5007 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5008 body_ids.sort_by_key(|b| bodies[b].value.span);