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::small_vec::OneVector;
56 use rustc_data_structures::thin_vec::ThinVec;
58 use util::common::FN_OUTPUT_NAME;
59 use util::nodemap::{DefIdMap, NodeMap};
61 use std::collections::BTreeMap;
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 current_impl_trait_owner: Vec<DefId>,
143 item_local_id_counters: NodeMap<u32>,
144 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
148 /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
149 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
151 /// Obtain the resolution for a node id
152 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
154 /// Obtain the possible resolutions for the given `use` statement.
155 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
157 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
158 /// This should only return `None` during testing.
159 fn definitions(&mut self) -> &mut Definitions;
161 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
162 /// it based on `is_value`.
166 crate_root: Option<&str>,
168 params: Option<P<hir::GenericArgs>>,
174 enum ImplTraitContext<'a> {
175 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
176 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
177 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
179 /// Newly generated parameters should be inserted into the given `Vec`.
180 Universal(&'a mut Vec<hir::GenericParam>),
182 /// Treat `impl Trait` as shorthand for a new existential parameter.
183 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
184 /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
186 /// We optionally store a `DefId` for the parent item here so we can look up necessary
187 /// information later. It is `None` when no information about the context should be stored,
188 /// e.g. for consts and statics.
189 Existential(Option<DefId>),
191 /// `impl Trait` is not accepted in this position.
195 impl<'a> ImplTraitContext<'a> {
196 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
197 use self::ImplTraitContext::*;
199 Universal(params) => Universal(params),
200 Existential(did) => Existential(*did),
201 Disallowed => Disallowed,
208 cstore: &dyn CrateStore,
209 dep_graph: &DepGraph,
211 resolver: &mut dyn Resolver,
213 // We're constructing the HIR here; we don't care what we will
214 // read, since we haven't even constructed the *input* to
216 dep_graph.assert_ignored();
219 crate_root: std_inject::injected_crate_name(),
223 items: BTreeMap::new(),
224 trait_items: BTreeMap::new(),
225 impl_items: BTreeMap::new(),
226 bodies: BTreeMap::new(),
227 trait_impls: BTreeMap::new(),
228 trait_auto_impl: BTreeMap::new(),
229 exported_macros: Vec::new(),
230 catch_scopes: Vec::new(),
231 loop_scopes: Vec::new(),
232 is_in_loop_condition: false,
233 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
234 type_def_lifetime_params: DefIdMap(),
235 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
236 current_impl_trait_owner: vec![],
237 item_local_id_counters: NodeMap(),
238 node_id_to_hir_id: IndexVec::new(),
240 is_in_trait_impl: false,
241 lifetimes_to_define: Vec::new(),
242 is_collecting_in_band_lifetimes: false,
243 in_scope_lifetimes: Vec::new(),
247 #[derive(Copy, Clone, PartialEq)]
249 /// Any path in a type context.
251 /// The `module::Type` in `module::Type::method` in an expression.
256 struct LoweredNodeId {
261 enum ParenthesizedGenericArgs {
267 /// What to do when we encounter an **anonymous** lifetime
268 /// reference. Anonymous lifetime references come in two flavors. You
269 /// have implicit, or fully elided, references to lifetimes, like the
270 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
271 /// or `Ref<'_, T>`. These often behave the same, but not always:
273 /// - certain usages of implicit references are deprecated, like
274 /// `Ref<T>`, and we sometimes just give hard errors in those cases
276 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
277 /// the same as `Box<dyn Foo + '_>`.
279 /// We describe the effects of the various modes in terms of three cases:
281 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
282 /// of a `&` (e.g., the missing lifetime in something like `&T`)
283 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
284 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
285 /// elided bounds follow special rules. Note that this only covers
286 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
287 /// '_>` is a case of "modern" elision.
288 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
289 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
290 /// non-deprecated equivalent.
292 /// Currently, the handling of lifetime elision is somewhat spread out
293 /// between HIR lowering and -- as described below -- the
294 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
295 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
296 /// everything into HIR lowering.
297 #[derive(Copy, Clone)]
298 enum AnonymousLifetimeMode {
299 /// For **Modern** cases, create a new anonymous region parameter
300 /// and reference that.
302 /// For **Dyn Bound** cases, pass responsibility to
303 /// `resolve_lifetime` code.
305 /// For **Deprecated** cases, report an error.
308 /// Pass responsibility to `resolve_lifetime` code for all cases.
312 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut OneVector<hir::ItemId> }
314 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
315 fn visit_ty(&mut self, ty: &'a Ty) {
321 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
324 visit::walk_ty(self, ty);
327 fn visit_path_segment(
330 path_segment: &'v PathSegment,
332 if let Some(ref p) = path_segment.args {
333 if let GenericArgs::Parenthesized(_) = **p {
337 visit::walk_path_segment(self, path_span, path_segment)
341 impl<'a> LoweringContext<'a> {
342 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
343 /// Full-crate AST visitor that inserts into a fresh
344 /// `LoweringContext` any information that may be
345 /// needed from arbitrary locations in the crate.
346 /// E.g. The number of lifetime generic parameters
347 /// declared for every type and trait definition.
348 struct MiscCollector<'lcx, 'interner: 'lcx> {
349 lctx: &'lcx mut LoweringContext<'interner>,
352 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
353 fn visit_item(&mut self, item: &'lcx Item) {
354 self.lctx.allocate_hir_id_counter(item.id, item);
357 ItemKind::Struct(_, ref generics)
358 | ItemKind::Union(_, ref generics)
359 | ItemKind::Enum(_, ref generics)
360 | ItemKind::Ty(_, ref generics)
361 | ItemKind::Existential(_, ref generics)
362 | ItemKind::Trait(_, _, ref generics, ..) => {
363 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
367 .filter(|param| match param.kind {
368 ast::GenericParamKind::Lifetime { .. } => true,
372 self.lctx.type_def_lifetime_params.insert(def_id, count);
376 visit::walk_item(self, item);
379 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
380 self.lctx.allocate_hir_id_counter(item.id, item);
381 visit::walk_trait_item(self, item);
384 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
385 self.lctx.allocate_hir_id_counter(item.id, item);
386 visit::walk_impl_item(self, item);
390 struct ItemLowerer<'lcx, 'interner: 'lcx> {
391 lctx: &'lcx mut LoweringContext<'interner>,
394 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
395 fn with_impl_trait_owner<F, T>(&mut self, def_id: DefId, f: F) -> T
397 F: FnOnce(&mut Self) -> T,
399 self.lctx.current_impl_trait_owner.push(def_id);
401 self.lctx.current_impl_trait_owner.pop();
406 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
408 F: FnOnce(&mut Self),
410 let old = self.lctx.is_in_trait_impl;
411 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
417 self.lctx.is_in_trait_impl = old;
421 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
422 fn visit_item(&mut self, item: &'lcx Item) {
423 let mut item_lowered = true;
424 self.lctx.with_hir_id_owner(item.id, |lctx| {
425 if let Some(hir_item) = lctx.lower_item(item) {
426 lctx.items.insert(item.id, hir_item);
428 item_lowered = false;
433 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
434 hir::ItemKind::Impl(_, _, _, ref generics, ..)
435 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
436 generics.params.clone()
441 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
442 let this = &mut ItemLowerer { lctx: this };
443 if let ItemKind::Fn(..) = item.node {
444 let fn_def_id = this.lctx.resolver.definitions().local_def_id(item.id);
445 this.with_impl_trait_owner(fn_def_id, |this| {
446 visit::walk_item(this, item)
448 } else if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
449 this.with_trait_impl_ref(opt_trait_ref, |this| {
450 visit::walk_item(this, item)
453 visit::walk_item(this, item);
459 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
460 self.lctx.with_hir_id_owner(item.id, |lctx| {
461 let id = hir::TraitItemId { node_id: item.id };
462 let hir_item = lctx.lower_trait_item(item);
463 lctx.trait_items.insert(id, hir_item);
466 visit::walk_trait_item(self, item);
469 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
470 self.lctx.with_hir_id_owner(item.id, |lctx| {
471 let id = hir::ImplItemId { node_id: item.id };
472 let hir_item = lctx.lower_impl_item(item);
473 lctx.impl_items.insert(id, hir_item);
475 visit::walk_impl_item(self, item);
479 self.lower_node_id(CRATE_NODE_ID);
480 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
482 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
483 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
485 let module = self.lower_mod(&c.module);
486 let attrs = self.lower_attrs(&c.attrs);
487 let body_ids = body_ids(&self.bodies);
491 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
497 exported_macros: hir::HirVec::from(self.exported_macros),
499 trait_items: self.trait_items,
500 impl_items: self.impl_items,
503 trait_impls: self.trait_impls,
504 trait_auto_impl: self.trait_auto_impl,
508 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
509 if self.item_local_id_counters.insert(owner, 0).is_some() {
511 "Tried to allocate item_local_id_counter for {:?} twice",
515 // Always allocate the first HirId for the owner itself
516 self.lower_node_id_with_owner(owner, owner)
519 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
521 F: FnOnce(&mut Self) -> hir::HirId,
523 if ast_node_id == DUMMY_NODE_ID {
524 return LoweredNodeId {
525 node_id: DUMMY_NODE_ID,
526 hir_id: hir::DUMMY_HIR_ID,
530 let min_size = ast_node_id.as_usize() + 1;
532 if min_size > self.node_id_to_hir_id.len() {
533 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
536 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
538 if existing_hir_id == hir::DUMMY_HIR_ID {
539 // Generate a new HirId
540 let hir_id = alloc_hir_id(self);
541 self.node_id_to_hir_id[ast_node_id] = hir_id;
543 node_id: ast_node_id,
548 node_id: ast_node_id,
549 hir_id: existing_hir_id,
554 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
556 F: FnOnce(&mut Self) -> T,
558 let counter = self.item_local_id_counters
559 .insert(owner, HIR_ID_COUNTER_LOCKED)
560 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
561 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
562 self.current_hir_id_owner.push((def_index, counter));
564 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
566 debug_assert!(def_index == new_def_index);
567 debug_assert!(new_counter >= counter);
569 let prev = self.item_local_id_counters
570 .insert(owner, new_counter)
572 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
576 fn with_impl_trait_owner<F, T>(&mut self, def_id: DefId, f: F) -> T
578 F: FnOnce(&mut LoweringContext) -> T,
580 self.current_impl_trait_owner.push(def_id);
582 self.current_impl_trait_owner.pop();
587 /// This method allocates a new HirId for the given NodeId and stores it in
588 /// the LoweringContext's NodeId => HirId map.
589 /// Take care not to call this method if the resulting HirId is then not
590 /// actually used in the HIR, as that would trigger an assertion in the
591 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
592 /// properly. Calling the method twice with the same NodeId is fine though.
593 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
594 self.lower_node_id_generic(ast_node_id, |this| {
595 let &mut (def_index, ref mut local_id_counter) =
596 this.current_hir_id_owner.last_mut().unwrap();
597 let local_id = *local_id_counter;
598 *local_id_counter += 1;
601 local_id: hir::ItemLocalId(local_id),
606 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
607 self.lower_node_id_generic(ast_node_id, |this| {
608 let local_id_counter = this
609 .item_local_id_counters
611 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
612 let local_id = *local_id_counter;
614 // We want to be sure not to modify the counter in the map while it
615 // is also on the stack. Otherwise we'll get lost updates when writing
616 // back from the stack to the map.
617 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
619 *local_id_counter += 1;
623 .opt_def_index(owner)
624 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
625 that do not belong to the current owner");
629 local_id: hir::ItemLocalId(local_id),
634 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
635 let body = hir::Body {
636 arguments: decl.map_or(hir_vec![], |decl| {
637 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
639 is_generator: self.is_generator,
643 self.bodies.insert(id, body);
647 fn next_id(&mut self) -> LoweredNodeId {
648 self.lower_node_id(self.sess.next_node_id())
651 fn expect_full_def(&mut self, id: NodeId) -> Def {
652 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
653 if pr.unresolved_segments() != 0 {
654 bug!("path not fully resolved: {:?}", pr);
660 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Def> {
661 self.resolver.get_import(id).present_items().map(|pr| {
662 if pr.unresolved_segments() != 0 {
663 bug!("path not fully resolved: {:?}", pr);
669 fn diagnostic(&self) -> &errors::Handler {
670 self.sess.diagnostic()
673 fn str_to_ident(&self, s: &'static str) -> Ident {
674 Ident::with_empty_ctxt(Symbol::gensym(s))
677 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
678 let mark = Mark::fresh(Mark::root());
679 mark.set_expn_info(source_map::ExpnInfo {
681 def_site: Some(span),
682 format: source_map::CompilerDesugaring(reason),
683 allow_internal_unstable: true,
684 allow_internal_unsafe: false,
685 local_inner_macros: false,
686 edition: source_map::hygiene::default_edition(),
688 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
691 fn with_anonymous_lifetime_mode<R>(
693 anonymous_lifetime_mode: AnonymousLifetimeMode,
694 op: impl FnOnce(&mut Self) -> R,
696 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
697 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
698 let result = op(self);
699 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
703 /// Creates a new hir::GenericParam for every new lifetime and
704 /// type parameter encountered while evaluating `f`. Definitions
705 /// are created with the parent provided. If no `parent_id` is
706 /// provided, no definitions will be returned.
708 /// Presuming that in-band lifetimes are enabled, then
709 /// `self.anonymous_lifetime_mode` will be updated to match the
710 /// argument while `f` is running (and restored afterwards).
711 fn collect_in_band_defs<T, F>(
714 anonymous_lifetime_mode: AnonymousLifetimeMode,
716 ) -> (Vec<hir::GenericParam>, T)
718 F: FnOnce(&mut LoweringContext) -> (Vec<hir::GenericParam>, T),
720 assert!(!self.is_collecting_in_band_lifetimes);
721 assert!(self.lifetimes_to_define.is_empty());
722 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
724 if self.sess.features_untracked().impl_header_lifetime_elision {
725 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
726 self.is_collecting_in_band_lifetimes = true;
727 } else if self.sess.features_untracked().in_band_lifetimes {
728 self.is_collecting_in_band_lifetimes = true;
731 let (in_band_ty_params, res) = f(self);
733 self.is_collecting_in_band_lifetimes = false;
734 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
736 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
738 let params = lifetimes_to_define
740 .map(|(span, hir_name)| {
741 let def_node_id = self.next_id().node_id;
743 // Get the name we'll use to make the def-path. Note
744 // that collisions are ok here and this shouldn't
745 // really show up for end-user.
746 let str_name = match hir_name {
747 ParamName::Plain(ident) => ident.as_interned_str(),
748 ParamName::Fresh(_) => keywords::UnderscoreLifetime.name().as_interned_str(),
751 // Add a definition for the in-band lifetime def
752 self.resolver.definitions().create_def_with_parent(
755 DefPathData::LifetimeParam(str_name),
756 DefIndexAddressSpace::High,
767 pure_wrt_drop: false,
768 kind: hir::GenericParamKind::Lifetime { in_band: true }
771 .chain(in_band_ty_params.into_iter())
777 /// When there is a reference to some lifetime `'a`, and in-band
778 /// lifetimes are enabled, then we want to push that lifetime into
779 /// the vector of names to define later. In that case, it will get
780 /// added to the appropriate generics.
781 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
782 if !self.is_collecting_in_band_lifetimes {
786 if !self.sess.features_untracked().in_band_lifetimes {
790 if self.in_scope_lifetimes.contains(&ident.modern()) {
794 let hir_name = ParamName::Plain(ident);
796 if self.lifetimes_to_define.iter()
797 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
801 self.lifetimes_to_define.push((ident.span, hir_name));
804 /// When we have either an elided or `'_` lifetime in an impl
805 /// header, we convert it to
806 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
807 assert!(self.is_collecting_in_band_lifetimes);
808 let index = self.lifetimes_to_define.len();
809 let hir_name = ParamName::Fresh(index);
810 self.lifetimes_to_define.push((span, hir_name));
814 // Evaluates `f` with the lifetimes in `params` in-scope.
815 // This is used to track which lifetimes have already been defined, and
816 // which are new in-band lifetimes that need to have a definition created
818 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
820 F: FnOnce(&mut LoweringContext) -> T,
822 let old_len = self.in_scope_lifetimes.len();
823 let lt_def_names = params.iter().filter_map(|param| match param.kind {
824 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
827 self.in_scope_lifetimes.extend(lt_def_names);
831 self.in_scope_lifetimes.truncate(old_len);
835 // Same as the method above, but accepts `hir::GenericParam`s
836 // instead of `ast::GenericParam`s.
837 // This should only be used with generics that have already had their
838 // in-band lifetimes added. In practice, this means that this function is
839 // only used when lowering a child item of a trait or impl.
840 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
841 params: &HirVec<hir::GenericParam>,
844 F: FnOnce(&mut LoweringContext) -> T,
846 let old_len = self.in_scope_lifetimes.len();
847 let lt_def_names = params.iter().filter_map(|param| match param.kind {
848 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
851 self.in_scope_lifetimes.extend(lt_def_names);
855 self.in_scope_lifetimes.truncate(old_len);
859 /// Appends in-band lifetime defs and argument-position `impl
860 /// Trait` defs to the existing set of generics.
862 /// Presuming that in-band lifetimes are enabled, then
863 /// `self.anonymous_lifetime_mode` will be updated to match the
864 /// argument while `f` is running (and restored afterwards).
865 fn add_in_band_defs<F, T>(
869 anonymous_lifetime_mode: AnonymousLifetimeMode,
871 ) -> (hir::Generics, T)
873 F: FnOnce(&mut LoweringContext, &mut Vec<hir::GenericParam>) -> T,
875 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
878 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
879 let mut params = Vec::new();
880 let generics = this.lower_generics(
882 ImplTraitContext::Universal(&mut params),
884 let res = f(this, &mut params);
885 (params, (generics, res))
890 lowered_generics.params = lowered_generics
897 (lowered_generics, res)
900 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
902 F: FnOnce(&mut LoweringContext) -> T,
904 let len = self.catch_scopes.len();
905 self.catch_scopes.push(catch_id);
907 let result = f(self);
910 self.catch_scopes.len(),
911 "catch scopes should be added and removed in stack order"
914 self.catch_scopes.pop().unwrap();
921 capture_clause: CaptureBy,
922 closure_node_id: NodeId,
924 body: impl FnOnce(&mut LoweringContext) -> hir::Expr,
926 let prev_is_generator = mem::replace(&mut self.is_generator, true);
927 let body_expr = body(self);
928 let span = body_expr.span;
929 let output = match ret_ty {
930 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
931 None => FunctionRetTy::Default(span),
938 let body_id = self.record_body(body_expr, Some(&decl));
939 self.is_generator = prev_is_generator;
941 let capture_clause = self.lower_capture_clause(capture_clause);
942 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
943 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
944 let generator = hir::Expr {
946 hir_id: closure_hir_id,
947 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
948 Some(hir::GeneratorMovability::Static)),
950 attrs: ThinVec::new(),
953 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
954 let gen_future = self.expr_std_path(
955 unstable_span, &["future", "from_generator"], None, ThinVec::new());
956 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
959 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
961 F: FnOnce(&mut LoweringContext) -> hir::Expr,
963 let prev = mem::replace(&mut self.is_generator, false);
964 let result = f(self);
965 let r = self.record_body(result, decl);
966 self.is_generator = prev;
970 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
972 F: FnOnce(&mut LoweringContext) -> T,
974 // We're no longer in the base loop's condition; we're in another loop.
975 let was_in_loop_condition = self.is_in_loop_condition;
976 self.is_in_loop_condition = false;
978 let len = self.loop_scopes.len();
979 self.loop_scopes.push(loop_id);
981 let result = f(self);
984 self.loop_scopes.len(),
985 "Loop scopes should be added and removed in stack order"
988 self.loop_scopes.pop().unwrap();
990 self.is_in_loop_condition = was_in_loop_condition;
995 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
997 F: FnOnce(&mut LoweringContext) -> T,
999 let was_in_loop_condition = self.is_in_loop_condition;
1000 self.is_in_loop_condition = true;
1002 let result = f(self);
1004 self.is_in_loop_condition = was_in_loop_condition;
1009 fn with_new_scopes<T, F>(&mut self, f: F) -> T
1011 F: FnOnce(&mut LoweringContext) -> T,
1013 let was_in_loop_condition = self.is_in_loop_condition;
1014 self.is_in_loop_condition = false;
1016 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
1017 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
1019 self.catch_scopes = catch_scopes;
1020 self.loop_scopes = loop_scopes;
1022 self.is_in_loop_condition = was_in_loop_condition;
1027 fn def_key(&mut self, id: DefId) -> DefKey {
1029 self.resolver.definitions().def_key(id.index)
1031 self.cstore.def_key(id)
1035 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1036 label.map(|label| hir::Label {
1041 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1042 let target_id = match destination {
1044 if let Def::Label(loop_id) = self.expect_full_def(id) {
1045 Ok(self.lower_node_id(loop_id).node_id)
1047 Err(hir::LoopIdError::UnresolvedLabel)
1054 .map(|id| Ok(self.lower_node_id(id).node_id))
1055 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1060 label: self.lower_label(destination.map(|(_, label)| label)),
1065 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1068 .map(|a| self.lower_attr(a))
1069 .collect::<Vec<_>>()
1073 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1077 path: attr.path.clone(),
1078 tokens: self.lower_token_stream(attr.tokens.clone()),
1079 is_sugared_doc: attr.is_sugared_doc,
1084 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1087 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1091 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1093 TokenTree::Token(span, token) => self.lower_token(token, span),
1094 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1097 delim: delimited.delim,
1098 tts: self.lower_token_stream(delimited.tts.into()).into(),
1104 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1106 Token::Interpolated(_) => {}
1107 other => return TokenTree::Token(span, other).into(),
1110 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1111 self.lower_token_stream(tts)
1114 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1116 attrs: self.lower_attrs(&arm.attrs),
1117 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1118 guard: match arm.guard {
1119 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1122 body: P(self.lower_expr(&arm.body)),
1126 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1128 id: self.lower_node_id(b.id).node_id,
1130 ty: self.lower_ty(&b.ty, itctx),
1135 fn lower_generic_arg(&mut self,
1136 arg: &ast::GenericArg,
1137 itctx: ImplTraitContext)
1138 -> hir::GenericArg {
1140 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1141 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1145 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1146 P(self.lower_ty_direct(t, itctx))
1149 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext) -> hir::Ty {
1150 let kind = match t.node {
1151 TyKind::Infer => hir::TyKind::Infer,
1152 TyKind::Err => hir::TyKind::Err,
1153 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1154 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1155 TyKind::Rptr(ref region, ref mt) => {
1156 let span = t.span.shrink_to_lo();
1157 let lifetime = match *region {
1158 Some(ref lt) => self.lower_lifetime(lt),
1159 None => self.elided_ref_lifetime(span),
1161 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1163 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1166 this.with_anonymous_lifetime_mode(
1167 AnonymousLifetimeMode::PassThrough,
1169 hir::TyKind::BareFn(P(hir::BareFnTy {
1170 generic_params: this.lower_generic_params(
1173 ImplTraitContext::Disallowed,
1175 unsafety: this.lower_unsafety(f.unsafety),
1177 decl: this.lower_fn_decl(&f.decl, None, false, None),
1178 arg_names: this.lower_fn_args_to_names(&f.decl),
1184 TyKind::Never => hir::TyKind::Never,
1185 TyKind::Tup(ref tys) => {
1186 hir::TyKind::Tup(tys.iter().map(|ty| {
1187 self.lower_ty_direct(ty, itctx.reborrow())
1190 TyKind::Paren(ref ty) => {
1191 return self.lower_ty_direct(ty, itctx);
1193 TyKind::Path(ref qself, ref path) => {
1194 let id = self.lower_node_id(t.id);
1195 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1196 let ty = self.ty_path(id, t.span, qpath);
1197 if let hir::TyKind::TraitObject(..) = ty.node {
1198 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1202 TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1205 def: self.expect_full_def(t.id),
1206 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1210 TyKind::Array(ref ty, ref length) => {
1211 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1213 TyKind::Typeof(ref expr) => {
1214 hir::TyKind::Typeof(self.lower_anon_const(expr))
1216 TyKind::TraitObject(ref bounds, kind) => {
1217 let mut lifetime_bound = None;
1220 .filter_map(|bound| match *bound {
1221 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1222 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1224 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1225 GenericBound::Outlives(ref lifetime) => {
1226 if lifetime_bound.is_none() {
1227 lifetime_bound = Some(self.lower_lifetime(lifetime));
1233 let lifetime_bound =
1234 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1235 if kind != TraitObjectSyntax::Dyn {
1236 self.maybe_lint_bare_trait(t.span, t.id, false);
1238 hir::TyKind::TraitObject(bounds, lifetime_bound)
1240 TyKind::ImplTrait(def_node_id, ref bounds) => {
1243 ImplTraitContext::Existential(fn_def_id) => {
1244 self.lower_existential_impl_trait(
1245 span, fn_def_id, def_node_id,
1246 |this| this.lower_param_bounds(bounds, itctx),
1249 ImplTraitContext::Universal(in_band_ty_params) => {
1250 self.lower_node_id(def_node_id);
1251 // Add a definition for the in-band Param
1252 let def_index = self
1255 .opt_def_index(def_node_id)
1258 let hir_bounds = self.lower_param_bounds(
1260 ImplTraitContext::Universal(in_band_ty_params),
1262 // Set the name to `impl Bound1 + Bound2`
1263 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1264 in_band_ty_params.push(hir::GenericParam {
1266 name: ParamName::Plain(ident),
1267 pure_wrt_drop: false,
1271 kind: hir::GenericParamKind::Type {
1273 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1277 hir::TyKind::Path(hir::QPath::Resolved(
1281 def: Def::TyParam(DefId::local(def_index)),
1282 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1286 ImplTraitContext::Disallowed => {
1287 let allowed_in = if self.sess.features_untracked()
1288 .impl_trait_in_bindings {
1289 "bindings or function and inherent method return types"
1291 "function and inherent method return types"
1297 "`impl Trait` not allowed outside of {}",
1304 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1307 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1316 fn lower_existential_impl_trait(
1319 fn_def_id: Option<DefId>,
1320 exist_ty_node_id: NodeId,
1321 lower_bounds: impl FnOnce(&mut LoweringContext) -> hir::GenericBounds,
1323 // Make sure we know that some funky desugaring has been going on here.
1324 // This is a first: there is code in other places like for loop
1325 // desugaring that explicitly states that we don't want to track that.
1326 // Not tracking it makes lints in rustc and clippy very fragile as
1327 // frequently opened issues show.
1328 let exist_ty_span = self.allow_internal_unstable(
1329 CompilerDesugaringKind::ExistentialReturnType,
1333 let exist_ty_def_index = self
1336 .opt_def_index(exist_ty_node_id)
1339 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1341 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1343 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1349 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1350 let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1351 generics: hir::Generics {
1352 params: lifetime_defs,
1353 where_clause: hir::WhereClause {
1354 id: lctx.next_id().node_id,
1355 predicates: Vec::new().into(),
1360 impl_trait_fn: fn_def_id,
1362 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1363 // Generate an `existential type Foo: Trait;` declaration
1364 trace!("creating existential type with id {:#?}", exist_ty_id);
1366 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1367 let exist_ty_item = hir::Item {
1368 id: exist_ty_id.node_id,
1369 hir_id: exist_ty_id.hir_id,
1370 name: keywords::Invalid.name(),
1371 attrs: Default::default(),
1372 node: exist_ty_item_kind,
1373 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1374 span: exist_ty_span,
1377 // Insert the item into the global list. This usually happens
1378 // automatically for all AST items. But this existential type item
1379 // does not actually exist in the AST.
1380 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1382 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1383 let path = P(hir::Path {
1384 span: exist_ty_span,
1385 def: Def::Existential(DefId::local(exist_ty_def_index)),
1386 segments: hir_vec![hir::PathSegment {
1388 ident: Ident::new(keywords::Invalid.name(), exist_ty_span),
1389 args: Some(P(hir::GenericArgs {
1390 parenthesized: false,
1391 bindings: HirVec::new(),
1396 hir::TyKind::Path(hir::QPath::Resolved(None, path))
1400 fn lifetimes_from_impl_trait_bounds(
1402 exist_ty_id: NodeId,
1403 parent_index: DefIndex,
1404 bounds: &hir::GenericBounds,
1405 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1406 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1407 // appear in the bounds, excluding lifetimes that are created within the bounds.
1408 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1409 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1410 context: &'r mut LoweringContext<'a>,
1412 exist_ty_id: NodeId,
1413 collect_elided_lifetimes: bool,
1414 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1415 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1416 output_lifetimes: Vec<hir::GenericArg>,
1417 output_lifetime_params: Vec<hir::GenericParam>,
1420 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1421 fn nested_visit_map<'this>(
1423 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1424 hir::intravisit::NestedVisitorMap::None
1427 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1428 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1429 if parameters.parenthesized {
1430 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1431 self.collect_elided_lifetimes = false;
1432 hir::intravisit::walk_generic_args(self, span, parameters);
1433 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1435 hir::intravisit::walk_generic_args(self, span, parameters);
1439 fn visit_ty(&mut self, t: &'v hir::Ty) {
1440 // Don't collect elided lifetimes used inside of `fn()` syntax
1441 if let hir::TyKind::BareFn(_) = t.node {
1442 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1443 self.collect_elided_lifetimes = false;
1445 // Record the "stack height" of `for<'a>` lifetime bindings
1446 // to be able to later fully undo their introduction.
1447 let old_len = self.currently_bound_lifetimes.len();
1448 hir::intravisit::walk_ty(self, t);
1449 self.currently_bound_lifetimes.truncate(old_len);
1451 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1453 hir::intravisit::walk_ty(self, t)
1457 fn visit_poly_trait_ref(
1459 trait_ref: &'v hir::PolyTraitRef,
1460 modifier: hir::TraitBoundModifier,
1462 // Record the "stack height" of `for<'a>` lifetime bindings
1463 // to be able to later fully undo their introduction.
1464 let old_len = self.currently_bound_lifetimes.len();
1465 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1466 self.currently_bound_lifetimes.truncate(old_len);
1469 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1470 // Record the introduction of 'a in `for<'a> ...`
1471 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1472 // Introduce lifetimes one at a time so that we can handle
1473 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1474 let lt_name = hir::LifetimeName::Param(param.name);
1475 self.currently_bound_lifetimes.push(lt_name);
1478 hir::intravisit::walk_generic_param(self, param);
1481 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1482 let name = match lifetime.name {
1483 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1484 if self.collect_elided_lifetimes {
1485 // Use `'_` for both implicit and underscore lifetimes in
1486 // `abstract type Foo<'_>: SomeTrait<'_>;`
1487 hir::LifetimeName::Underscore
1492 hir::LifetimeName::Param(_) => lifetime.name,
1493 hir::LifetimeName::Static => return,
1496 if !self.currently_bound_lifetimes.contains(&name)
1497 && !self.already_defined_lifetimes.contains(&name) {
1498 self.already_defined_lifetimes.insert(name);
1500 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1501 id: self.context.next_id().node_id,
1502 span: lifetime.span,
1506 // We need to manually create the ids here, because the
1507 // definitions will go into the explicit `existential type`
1508 // declaration and thus need to have their owner set to that item
1509 let def_node_id = self.context.sess.next_node_id();
1510 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1511 self.context.resolver.definitions().create_def_with_parent(
1514 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1515 DefIndexAddressSpace::High,
1520 let name = match name {
1521 hir::LifetimeName::Underscore => {
1522 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident())
1524 hir::LifetimeName::Param(param_name) => param_name,
1525 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1528 self.output_lifetime_params.push(hir::GenericParam {
1531 span: lifetime.span,
1532 pure_wrt_drop: false,
1535 kind: hir::GenericParamKind::Lifetime {
1543 let mut lifetime_collector = ImplTraitLifetimeCollector {
1545 parent: parent_index,
1547 collect_elided_lifetimes: true,
1548 currently_bound_lifetimes: Vec::new(),
1549 already_defined_lifetimes: FxHashSet::default(),
1550 output_lifetimes: Vec::new(),
1551 output_lifetime_params: Vec::new(),
1554 for bound in bounds {
1555 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1559 lifetime_collector.output_lifetimes.into(),
1560 lifetime_collector.output_lifetime_params.into(),
1564 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1569 .map(|x| self.lower_foreign_item(x))
1574 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1581 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1583 node: hir::VariantKind {
1584 name: v.node.ident.name,
1585 attrs: self.lower_attrs(&v.node.attrs),
1586 data: self.lower_variant_data(&v.node.data),
1587 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1596 qself: &Option<QSelf>,
1598 param_mode: ParamMode,
1599 mut itctx: ImplTraitContext,
1601 let qself_position = qself.as_ref().map(|q| q.position);
1602 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1604 let resolution = self.resolver
1606 .unwrap_or(PathResolution::new(Def::Err));
1608 let proj_start = p.segments.len() - resolution.unresolved_segments();
1609 let path = P(hir::Path {
1610 def: resolution.base_def(),
1611 segments: p.segments[..proj_start]
1614 .map(|(i, segment)| {
1615 let param_mode = match (qself_position, param_mode) {
1616 (Some(j), ParamMode::Optional) if i < j => {
1617 // This segment is part of the trait path in a
1618 // qualified path - one of `a`, `b` or `Trait`
1619 // in `<X as a::b::Trait>::T::U::method`.
1625 // Figure out if this is a type/trait segment,
1626 // which may need lifetime elision performed.
1627 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1628 krate: def_id.krate,
1629 index: this.def_key(def_id).parent.expect("missing parent"),
1631 let type_def_id = match resolution.base_def() {
1632 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1633 Some(parent_def_id(self, def_id))
1635 Def::Variant(def_id) if i + 1 == proj_start => {
1636 Some(parent_def_id(self, def_id))
1639 | Def::Union(def_id)
1641 | Def::TyAlias(def_id)
1642 | Def::Trait(def_id) if i + 1 == proj_start =>
1648 let parenthesized_generic_args = match resolution.base_def() {
1649 // `a::b::Trait(Args)`
1650 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1651 // `a::b::Trait(Args)::TraitItem`
1652 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1653 if i + 2 == proj_start =>
1655 ParenthesizedGenericArgs::Ok
1657 // Avoid duplicated errors
1658 Def::Err => ParenthesizedGenericArgs::Ok,
1664 | Def::Variant(..) if i + 1 == proj_start =>
1666 ParenthesizedGenericArgs::Err
1668 // A warning for now, for compatibility reasons
1669 _ => ParenthesizedGenericArgs::Warn,
1672 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1673 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1676 assert!(!def_id.is_local());
1678 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1679 let n = item_generics.own_counts().lifetimes;
1680 self.type_def_lifetime_params.insert(def_id, n);
1683 self.lower_path_segment(
1688 parenthesized_generic_args,
1696 // Simple case, either no projections, or only fully-qualified.
1697 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1698 if resolution.unresolved_segments() == 0 {
1699 return hir::QPath::Resolved(qself, path);
1702 // Create the innermost type that we're projecting from.
1703 let mut ty = if path.segments.is_empty() {
1704 // If the base path is empty that means there exists a
1705 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1706 qself.expect("missing QSelf for <T>::...")
1708 // Otherwise, the base path is an implicit `Self` type path,
1709 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1710 // `<I as Iterator>::Item::default`.
1711 let new_id = self.next_id();
1712 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1715 // Anything after the base path are associated "extensions",
1716 // out of which all but the last one are associated types,
1717 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1718 // * base path is `std::vec::Vec<T>`
1719 // * "extensions" are `IntoIter`, `Item` and `clone`
1720 // * type nodes are:
1721 // 1. `std::vec::Vec<T>` (created above)
1722 // 2. `<std::vec::Vec<T>>::IntoIter`
1723 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1724 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1725 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1726 let segment = P(self.lower_path_segment(
1731 ParenthesizedGenericArgs::Warn,
1734 let qpath = hir::QPath::TypeRelative(ty, segment);
1736 // It's finished, return the extension of the right node type.
1737 if i == p.segments.len() - 1 {
1741 // Wrap the associated extension in another type node.
1742 let new_id = self.next_id();
1743 ty = P(self.ty_path(new_id, p.span, qpath));
1746 // Should've returned in the for loop above.
1749 "lower_qpath: no final extension segment in {}..{}",
1755 fn lower_path_extra(
1759 ident: Option<Ident>,
1760 param_mode: ParamMode,
1764 segments: p.segments
1767 self.lower_path_segment(
1772 ParenthesizedGenericArgs::Err,
1773 ImplTraitContext::Disallowed,
1776 .chain(ident.map(|ident| hir::PathSegment::from_ident(ident)))
1782 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1783 let def = self.expect_full_def(id);
1784 self.lower_path_extra(def, p, None, param_mode)
1787 fn lower_path_segment(
1790 segment: &PathSegment,
1791 param_mode: ParamMode,
1792 expected_lifetimes: usize,
1793 parenthesized_generic_args: ParenthesizedGenericArgs,
1794 itctx: ImplTraitContext,
1795 ) -> hir::PathSegment {
1796 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1797 let msg = "parenthesized parameters may only be used with a trait";
1798 match **generic_args {
1799 GenericArgs::AngleBracketed(ref data) => {
1800 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1802 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1803 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1804 ParenthesizedGenericArgs::Warn => {
1805 self.sess.buffer_lint(
1806 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1811 (hir::GenericArgs::none(), true)
1813 ParenthesizedGenericArgs::Err => {
1814 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1815 .span_label(data.span, "only traits may use parentheses")
1817 (hir::GenericArgs::none(), true)
1822 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1825 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1826 GenericArg::Lifetime(_) => true,
1829 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1830 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1831 if !generic_args.parenthesized && !has_lifetimes {
1833 self.elided_path_lifetimes(path_span, expected_lifetimes)
1835 .map(|lt| GenericArg::Lifetime(lt))
1836 .chain(generic_args.args.into_iter())
1838 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1839 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1840 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1841 let no_bindings = generic_args.bindings.is_empty();
1842 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1843 // If there are no (non-implicit) generic args or associated-type
1844 // bindings, our suggestion includes the angle brackets
1845 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1847 // Otherwise—sorry, this is kind of gross—we need to infer the
1848 // place to splice in the `'_, ` from the generics that do exist
1849 let first_generic_span = first_generic_span
1850 .expect("already checked that type args or bindings exist");
1851 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1853 self.sess.buffer_lint_with_diagnostic(
1854 ELIDED_LIFETIMES_IN_PATHS,
1857 "hidden lifetime parameters in types are deprecated",
1858 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1859 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1865 hir::PathSegment::new(
1872 fn lower_angle_bracketed_parameter_data(
1874 data: &AngleBracketedArgs,
1875 param_mode: ParamMode,
1876 mut itctx: ImplTraitContext,
1877 ) -> (hir::GenericArgs, bool) {
1878 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1879 let has_types = args.iter().any(|arg| match arg {
1880 ast::GenericArg::Type(_) => true,
1884 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1885 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1886 parenthesized: false,
1888 !has_types && param_mode == ParamMode::Optional)
1891 fn lower_parenthesized_parameter_data(
1893 data: &ParenthesisedArgs,
1894 ) -> (hir::GenericArgs, bool) {
1895 // Switch to `PassThrough` mode for anonymous lifetimes: this
1896 // means that we permit things like `&Ref<T>`, where `Ref` has
1897 // a hidden lifetime parameter. This is needed for backwards
1898 // compatibility, even in contexts like an impl header where
1899 // we generally don't permit such things (see #51008).
1900 self.with_anonymous_lifetime_mode(
1901 AnonymousLifetimeMode::PassThrough,
1903 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1904 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1905 let inputs = inputs.iter().map(|ty| this.lower_ty_direct(ty, DISALLOWED)).collect();
1906 let mk_tup = |this: &mut Self, tys, span| {
1907 let LoweredNodeId { node_id, hir_id } = this.next_id();
1908 hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1913 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1916 id: this.next_id().node_id,
1917 ident: Ident::from_str(FN_OUTPUT_NAME),
1920 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1921 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1922 span: output.as_ref().map_or(span, |ty| ty.span),
1925 parenthesized: true,
1933 fn lower_local(&mut self, l: &Local) -> (P<hir::Local>, OneVector<hir::ItemId>) {
1934 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1935 let mut ids = OneVector::<hir::ItemId>::new();
1936 if self.sess.features_untracked().impl_trait_in_bindings {
1937 if let Some(ref ty) = l.ty {
1938 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
1939 visitor.visit_ty(ty);
1942 let impl_trait_owner_id = self.current_impl_trait_owner.last().map(|id| *id);
1948 .map(|t| self.lower_ty(t,
1949 if self.sess.features_untracked().impl_trait_in_bindings {
1950 ImplTraitContext::Existential(impl_trait_owner_id)
1952 ImplTraitContext::Disallowed
1955 pat: self.lower_pat(&l.pat),
1956 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1958 attrs: l.attrs.clone(),
1959 source: hir::LocalSource::Normal,
1963 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1965 Mutability::Mutable => hir::MutMutable,
1966 Mutability::Immutable => hir::MutImmutable,
1970 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1971 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1975 pat: self.lower_pat(&arg.pat),
1979 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1982 .map(|arg| match arg.pat.node {
1983 PatKind::Ident(_, ident, _) => ident,
1984 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
1989 // Lowers a function declaration.
1991 // decl: the unlowered (ast) function declaration.
1992 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1993 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1994 // make_ret_async is also `Some`.
1995 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1996 // This guards against trait declarations and implementations where impl Trait is
1998 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1999 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
2000 // return type impl Trait item.
2004 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2005 impl_trait_return_allow: bool,
2006 make_ret_async: Option<NodeId>,
2007 ) -> P<hir::FnDecl> {
2008 let inputs = decl.inputs
2011 if let Some((_, ref mut ibty)) = in_band_ty_params {
2012 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2014 self.lower_ty_direct(&arg.ty, ImplTraitContext::Disallowed)
2017 .collect::<HirVec<_>>();
2019 let output = if let Some(ret_id) = make_ret_async {
2020 self.lower_async_fn_ret_ty(
2023 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
2028 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2029 Some((def_id, _)) if impl_trait_return_allow => {
2030 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(Some(def_id))))
2032 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
2034 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2041 variadic: decl.variadic,
2042 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
2043 TyKind::ImplicitSelf => true,
2044 TyKind::Rptr(_, ref mt) => mt.ty.node.is_implicit_self(),
2050 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
2052 // fn_span: the span of the async function declaration. Used for error reporting.
2053 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
2054 // output: unlowered output type (`T` in `-> T`)
2055 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
2056 fn lower_async_fn_ret_ty(
2059 output: &FunctionRetTy,
2061 return_impl_trait_id: NodeId,
2062 ) -> hir::FunctionRetTy {
2063 // Get lifetimes used in the input arguments to the function. Our output type must also
2064 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
2065 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
2066 // is a subset of the other. We really want some new lifetime that is a subset of all input
2067 // lifetimes, but that doesn't exist at the moment.
2069 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
2070 context: &'r mut LoweringContext<'a>,
2071 // Lifetimes bound by HRTB
2072 currently_bound_lifetimes: Vec<hir::LifetimeName>,
2073 // Whether to count elided lifetimes.
2074 // Disabled inside of `Fn` or `fn` syntax.
2075 collect_elided_lifetimes: bool,
2076 // The lifetime found.
2077 // Multiple different or elided lifetimes cannot appear in async fn for now.
2078 output_lifetime: Option<(hir::LifetimeName, Span)>,
2081 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
2082 fn nested_visit_map<'this>(
2084 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
2085 hir::intravisit::NestedVisitorMap::None
2088 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
2089 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2090 if parameters.parenthesized {
2091 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2092 self.collect_elided_lifetimes = false;
2093 hir::intravisit::walk_generic_args(self, span, parameters);
2094 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2096 hir::intravisit::walk_generic_args(self, span, parameters);
2100 fn visit_ty(&mut self, t: &'v hir::Ty) {
2101 // Don't collect elided lifetimes used inside of `fn()` syntax
2102 if let &hir::TyKind::BareFn(_) = &t.node {
2103 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2104 self.collect_elided_lifetimes = false;
2106 // Record the "stack height" of `for<'a>` lifetime bindings
2107 // to be able to later fully undo their introduction.
2108 let old_len = self.currently_bound_lifetimes.len();
2109 hir::intravisit::walk_ty(self, t);
2110 self.currently_bound_lifetimes.truncate(old_len);
2112 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2114 hir::intravisit::walk_ty(self, t);
2118 fn visit_poly_trait_ref(
2120 trait_ref: &'v hir::PolyTraitRef,
2121 modifier: hir::TraitBoundModifier,
2123 // Record the "stack height" of `for<'a>` lifetime bindings
2124 // to be able to later fully undo their introduction.
2125 let old_len = self.currently_bound_lifetimes.len();
2126 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2127 self.currently_bound_lifetimes.truncate(old_len);
2130 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2131 // Record the introduction of 'a in `for<'a> ...`
2132 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2133 // Introduce lifetimes one at a time so that we can handle
2134 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2135 let lt_name = hir::LifetimeName::Param(param.name);
2136 self.currently_bound_lifetimes.push(lt_name);
2139 hir::intravisit::walk_generic_param(self, param);
2142 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2143 let name = match lifetime.name {
2144 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2145 if self.collect_elided_lifetimes {
2146 // Use `'_` for both implicit and underscore lifetimes in
2147 // `abstract type Foo<'_>: SomeTrait<'_>;`
2148 hir::LifetimeName::Underscore
2153 hir::LifetimeName::Param(_) => lifetime.name,
2154 hir::LifetimeName::Static => return,
2157 if !self.currently_bound_lifetimes.contains(&name) {
2158 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2159 // We don't currently have a reliable way to desugar `async fn` with
2160 // multiple potentially unrelated input lifetimes into
2161 // `-> impl Trait + 'lt`, so we report an error in this case.
2162 if current_lt_name != name {
2165 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2167 "multiple different lifetimes used in arguments of `async fn`",
2169 .span_label(current_lt_span, "first lifetime here")
2170 .span_label(lifetime.span, "different lifetime here")
2171 .help("`async fn` can only accept borrowed values \
2172 with identical lifetimes")
2174 } else if current_lt_name.is_elided() && name.is_elided() {
2177 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2179 "multiple elided lifetimes used in arguments of `async fn`",
2181 .span_label(current_lt_span, "first lifetime here")
2182 .span_label(lifetime.span, "different lifetime here")
2183 .help("consider giving these arguments named lifetimes")
2187 self.output_lifetime = Some((name, lifetime.span));
2193 let bound_lifetime = {
2194 let mut lifetime_collector = AsyncFnLifetimeCollector {
2196 currently_bound_lifetimes: Vec::new(),
2197 collect_elided_lifetimes: true,
2198 output_lifetime: None,
2202 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2204 lifetime_collector.output_lifetime
2207 let span = match output {
2208 FunctionRetTy::Ty(ty) => ty.span,
2209 FunctionRetTy::Default(span) => *span,
2212 let impl_trait_ty = self.lower_existential_impl_trait(
2213 span, Some(fn_def_id), return_impl_trait_id, |this| {
2214 let output_ty = match output {
2215 FunctionRetTy::Ty(ty) => {
2216 let impl_trait_owner_id = *this.current_impl_trait_owner.last().unwrap();
2217 this.lower_ty(ty, ImplTraitContext::Existential(Some(impl_trait_owner_id)))
2219 FunctionRetTy::Default(span) => {
2220 let LoweredNodeId { node_id, hir_id } = this.next_id();
2224 node: hir::TyKind::Tup(hir_vec![]),
2231 let future_params = P(hir::GenericArgs {
2233 bindings: hir_vec![hir::TypeBinding {
2234 ident: Ident::from_str(FN_OUTPUT_NAME),
2236 id: this.next_id().node_id,
2239 parenthesized: false,
2243 this.std_path(span, &["future", "Future"], Some(future_params), false);
2245 let LoweredNodeId { node_id, hir_id } = this.next_id();
2246 let mut bounds = vec![
2247 hir::GenericBound::Trait(
2249 trait_ref: hir::TraitRef {
2254 bound_generic_params: hir_vec![],
2257 hir::TraitBoundModifier::None
2261 if let Some((name, span)) = bound_lifetime {
2262 bounds.push(hir::GenericBound::Outlives(
2263 hir::Lifetime { id: this.next_id().node_id, name, span }));
2266 hir::HirVec::from(bounds)
2269 let LoweredNodeId { node_id, hir_id } = self.next_id();
2270 let impl_trait_ty = P(hir::Ty {
2272 node: impl_trait_ty,
2277 hir::FunctionRetTy::Return(impl_trait_ty)
2280 fn lower_param_bound(
2283 itctx: ImplTraitContext,
2284 ) -> hir::GenericBound {
2286 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2287 self.lower_poly_trait_ref(ty, itctx),
2288 self.lower_trait_bound_modifier(modifier),
2290 GenericBound::Outlives(ref lifetime) => {
2291 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2296 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2297 let span = l.ident.span;
2299 ident if ident.name == keywords::StaticLifetime.name() =>
2300 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2301 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2302 match self.anonymous_lifetime_mode {
2303 AnonymousLifetimeMode::CreateParameter => {
2304 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2305 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2308 AnonymousLifetimeMode::PassThrough => {
2309 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2313 self.maybe_collect_in_band_lifetime(ident);
2314 let param_name = ParamName::Plain(ident);
2315 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2320 fn new_named_lifetime(
2324 name: hir::LifetimeName,
2325 ) -> hir::Lifetime {
2327 id: self.lower_node_id(id).node_id,
2333 fn lower_generic_params(
2335 params: &[GenericParam],
2336 add_bounds: &NodeMap<Vec<GenericBound>>,
2337 mut itctx: ImplTraitContext,
2338 ) -> hir::HirVec<hir::GenericParam> {
2339 params.iter().map(|param| {
2340 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2344 fn lower_generic_param(&mut self,
2345 param: &GenericParam,
2346 add_bounds: &NodeMap<Vec<GenericBound>>,
2347 mut itctx: ImplTraitContext)
2348 -> hir::GenericParam {
2349 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx.reborrow());
2351 GenericParamKind::Lifetime => {
2352 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2353 self.is_collecting_in_band_lifetimes = false;
2355 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
2356 let param_name = match lt.name {
2357 hir::LifetimeName::Param(param_name) => param_name,
2358 _ => hir::ParamName::Plain(lt.name.ident()),
2360 let param = hir::GenericParam {
2364 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2365 attrs: self.lower_attrs(¶m.attrs),
2367 kind: hir::GenericParamKind::Lifetime { in_band: false }
2370 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2374 GenericParamKind::Type { ref default, .. } => {
2375 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2376 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2377 // Instead, use gensym("Self") to create a distinct name that looks the same.
2378 let ident = if param.ident.name == keywords::SelfType.name() {
2379 param.ident.gensym()
2384 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2385 if !add_bounds.is_empty() {
2386 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2387 bounds = bounds.into_iter()
2393 id: self.lower_node_id(param.id).node_id,
2394 name: hir::ParamName::Plain(ident),
2395 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2396 attrs: self.lower_attrs(¶m.attrs),
2399 kind: hir::GenericParamKind::Type {
2400 default: default.as_ref().map(|x| {
2401 self.lower_ty(x, ImplTraitContext::Disallowed)
2403 synthetic: param.attrs.iter()
2404 .filter(|attr| attr.check_name("rustc_synthetic"))
2405 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2415 generics: &Generics,
2416 itctx: ImplTraitContext)
2419 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2420 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2421 // paths where report_error is called are also the only paths that advance to after
2422 // the match statement, so the error reporting could probably just be moved there.
2423 let mut add_bounds: NodeMap<Vec<_>> = NodeMap();
2424 for pred in &generics.where_clause.predicates {
2425 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2426 'next_bound: for bound in &bound_pred.bounds {
2427 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2428 let report_error = |this: &mut Self| {
2429 this.diagnostic().span_err(
2430 bound_pred.bounded_ty.span,
2431 "`?Trait` bounds are only permitted at the \
2432 point where a type parameter is declared",
2435 // Check if the where clause type is a plain type parameter.
2436 match bound_pred.bounded_ty.node {
2437 TyKind::Path(None, ref path)
2438 if path.segments.len() == 1
2439 && bound_pred.bound_generic_params.is_empty() =>
2441 if let Some(Def::TyParam(def_id)) = self.resolver
2442 .get_resolution(bound_pred.bounded_ty.id)
2443 .map(|d| d.base_def())
2445 if let Some(node_id) =
2446 self.resolver.definitions().as_local_node_id(def_id)
2448 for param in &generics.params {
2450 GenericParamKind::Type { .. } => {
2451 if node_id == param.id {
2452 add_bounds.entry(param.id)
2454 .push(bound.clone());
2455 continue 'next_bound;
2465 _ => report_error(self),
2473 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2474 where_clause: self.lower_where_clause(&generics.where_clause),
2475 span: generics.span,
2479 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2481 id: self.lower_node_id(wc.id).node_id,
2482 predicates: wc.predicates
2484 .map(|predicate| self.lower_where_predicate(predicate))
2489 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2491 WherePredicate::BoundPredicate(WhereBoundPredicate {
2492 ref bound_generic_params,
2497 self.with_in_scope_lifetime_defs(
2498 &bound_generic_params,
2500 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2501 bound_generic_params: this.lower_generic_params(
2502 bound_generic_params,
2504 ImplTraitContext::Disallowed,
2506 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2509 .filter_map(|bound| match *bound {
2510 // Ignore `?Trait` bounds.
2511 // Tthey were copied into type parameters already.
2512 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2513 _ => Some(this.lower_param_bound(
2515 ImplTraitContext::Disallowed,
2524 WherePredicate::RegionPredicate(WhereRegionPredicate {
2528 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2530 lifetime: self.lower_lifetime(lifetime),
2531 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2533 WherePredicate::EqPredicate(WhereEqPredicate {
2538 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2539 id: self.lower_node_id(id).node_id,
2540 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2541 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2547 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2549 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2553 .map(|f| self.lower_struct_field(f))
2555 self.lower_node_id(id).node_id,
2557 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2561 .map(|f| self.lower_struct_field(f))
2563 self.lower_node_id(id).node_id,
2565 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2569 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2570 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2571 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2572 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2574 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.ref_id);
2582 fn lower_poly_trait_ref(
2585 mut itctx: ImplTraitContext,
2586 ) -> hir::PolyTraitRef {
2587 let bound_generic_params =
2588 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx.reborrow());
2589 let trait_ref = self.with_parent_impl_lifetime_defs(
2590 &bound_generic_params,
2591 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2595 bound_generic_params,
2601 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2604 id: self.lower_node_id(f.id).node_id,
2605 ident: match f.ident {
2606 Some(ident) => ident,
2607 // FIXME(jseyfried) positional field hygiene
2608 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2610 vis: self.lower_visibility(&f.vis, None),
2611 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2612 attrs: self.lower_attrs(&f.attrs),
2616 fn lower_field(&mut self, f: &Field) -> hir::Field {
2618 id: self.next_id().node_id,
2620 expr: P(self.lower_expr(&f.expr)),
2622 is_shorthand: f.is_shorthand,
2626 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2628 ty: self.lower_ty(&mt.ty, itctx),
2629 mutbl: self.lower_mutability(mt.mutbl),
2633 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext)
2634 -> hir::GenericBounds {
2635 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2638 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2639 let mut expr = None;
2641 let mut stmts = vec![];
2643 for (index, stmt) in b.stmts.iter().enumerate() {
2644 if index == b.stmts.len() - 1 {
2645 if let StmtKind::Expr(ref e) = stmt.node {
2646 expr = Some(P(self.lower_expr(e)));
2648 stmts.extend(self.lower_stmt(stmt));
2651 stmts.extend(self.lower_stmt(stmt));
2655 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2660 stmts: stmts.into(),
2662 rules: self.lower_block_check_mode(&b.rules),
2665 recovered: b.recovered,
2669 fn lower_async_body(
2675 self.lower_body(Some(decl), |this| {
2676 if let IsAsync::Async { closure_id, .. } = asyncness {
2677 let async_expr = this.make_async_expr(
2678 CaptureBy::Value, closure_id, None,
2680 let body = this.lower_block(body, false);
2681 this.expr_block(body, ThinVec::new())
2683 this.expr(body.span, async_expr, ThinVec::new())
2685 let body = this.lower_block(body, false);
2686 this.expr_block(body, ThinVec::new())
2695 attrs: &hir::HirVec<Attribute>,
2696 vis: &mut hir::Visibility,
2698 ) -> hir::ItemKind {
2700 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2701 ItemKind::Use(ref use_tree) => {
2702 // Start with an empty prefix
2705 span: use_tree.span,
2708 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2710 ItemKind::Static(ref t, m, ref e) => {
2711 let value = self.lower_body(None, |this| this.lower_expr(e));
2712 hir::ItemKind::Static(
2715 if self.sess.features_untracked().impl_trait_in_bindings {
2716 ImplTraitContext::Existential(None)
2718 ImplTraitContext::Disallowed
2721 self.lower_mutability(m),
2725 ItemKind::Const(ref t, ref e) => {
2726 let value = self.lower_body(None, |this| this.lower_expr(e));
2727 hir::ItemKind::Const(
2730 if self.sess.features_untracked().impl_trait_in_bindings {
2731 ImplTraitContext::Existential(None)
2733 ImplTraitContext::Disallowed
2739 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2740 let fn_def_id = self.resolver.definitions().local_def_id(id);
2741 self.with_impl_trait_owner(fn_def_id, |this| {
2742 this.with_new_scopes(|this| {
2743 // Note: we don't need to change the return type from `T` to
2744 // `impl Future<Output = T>` here because lower_body
2745 // only cares about the input argument patterns in the function
2746 // declaration (decl), not the return types.
2747 let body_id = this.lower_async_body(decl, header.asyncness, body);
2749 let (generics, fn_decl) = this.add_in_band_defs(
2752 AnonymousLifetimeMode::PassThrough,
2753 |this, idty| this.lower_fn_decl(
2755 Some((fn_def_id, idty)),
2757 header.asyncness.opt_return_id()
2763 this.lower_fn_header(header),
2770 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2771 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2772 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2773 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2774 self.lower_ty(t, ImplTraitContext::Disallowed),
2775 self.lower_generics(generics, ImplTraitContext::Disallowed),
2777 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2778 generics: self.lower_generics(generics, ImplTraitContext::Disallowed),
2779 bounds: self.lower_param_bounds(b, ImplTraitContext::Disallowed),
2780 impl_trait_fn: None,
2782 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2784 variants: enum_definition
2787 .map(|x| self.lower_variant(x))
2790 self.lower_generics(generics, ImplTraitContext::Disallowed),
2792 ItemKind::Struct(ref struct_def, ref generics) => {
2793 let struct_def = self.lower_variant_data(struct_def);
2794 hir::ItemKind::Struct(
2796 self.lower_generics(generics, ImplTraitContext::Disallowed),
2799 ItemKind::Union(ref vdata, ref generics) => {
2800 let vdata = self.lower_variant_data(vdata);
2801 hir::ItemKind::Union(
2803 self.lower_generics(generics, ImplTraitContext::Disallowed),
2815 let def_id = self.resolver.definitions().local_def_id(id);
2817 // Lower the "impl header" first. This ordering is important
2818 // for in-band lifetimes! Consider `'a` here:
2820 // impl Foo<'a> for u32 {
2821 // fn method(&'a self) { .. }
2824 // Because we start by lowering the `Foo<'a> for u32`
2825 // part, we will add `'a` to the list of generics on
2826 // the impl. When we then encounter it later in the
2827 // method, it will not be considered an in-band
2828 // lifetime to be added, but rather a reference to a
2830 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2833 AnonymousLifetimeMode::CreateParameter,
2835 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2836 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2839 if let Some(ref trait_ref) = trait_ref {
2840 if let Def::Trait(def_id) = trait_ref.path.def {
2841 this.trait_impls.entry(def_id).or_default().push(id);
2845 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2847 (trait_ref, lowered_ty)
2851 let new_impl_items = self.with_in_scope_lifetime_defs(
2852 &ast_generics.params,
2856 .map(|item| this.lower_impl_item_ref(item))
2861 hir::ItemKind::Impl(
2862 self.lower_unsafety(unsafety),
2863 self.lower_impl_polarity(polarity),
2864 self.lower_defaultness(defaultness, true /* [1] */),
2871 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2872 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2875 .map(|item| self.lower_trait_item_ref(item))
2877 hir::ItemKind::Trait(
2878 self.lower_is_auto(is_auto),
2879 self.lower_unsafety(unsafety),
2880 self.lower_generics(generics, ImplTraitContext::Disallowed),
2885 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
2886 self.lower_generics(generics, ImplTraitContext::Disallowed),
2887 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2889 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2892 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2893 // not cause an assertion failure inside the `lower_defaultness` function
2901 vis: &mut hir::Visibility,
2903 attrs: &hir::HirVec<Attribute>,
2904 ) -> hir::ItemKind {
2905 let path = &tree.prefix;
2908 UseTreeKind::Simple(rename, id1, id2) => {
2909 *name = tree.ident().name;
2911 // First apply the prefix to the path
2912 let mut path = Path {
2916 .chain(path.segments.iter())
2922 // Correctly resolve `self` imports
2923 if path.segments.len() > 1
2924 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2926 let _ = path.segments.pop();
2927 if rename.is_none() {
2928 *name = path.segments.last().unwrap().ident.name;
2932 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2933 let mut defs = self.expect_full_def_from_use(id);
2934 // we want to return *something* from this function, so hang onto the first item
2936 let ret_def = defs.next().unwrap_or(Def::Err);
2938 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2939 let vis = vis.clone();
2940 let name = name.clone();
2941 let span = path.span;
2942 self.resolver.definitions().create_def_with_parent(
2946 DefIndexAddressSpace::High,
2949 self.allocate_hir_id_counter(new_node_id, &path);
2951 self.with_hir_id_owner(new_node_id, |this| {
2952 let new_id = this.lower_node_id(new_node_id);
2953 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2954 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
2955 let vis_kind = match vis.node {
2956 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2957 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2958 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2959 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
2960 let id = this.next_id();
2961 hir::VisibilityKind::Restricted {
2963 // We are allocating a new NodeId here
2969 let vis = respan(vis.span, vis_kind);
2975 hir_id: new_id.hir_id,
2977 attrs: attrs.clone(),
2986 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2987 hir::ItemKind::Use(path, hir::UseKind::Single)
2989 UseTreeKind::Glob => {
2990 let path = P(self.lower_path(
2996 .chain(path.segments.iter())
3001 ParamMode::Explicit,
3003 hir::ItemKind::Use(path, hir::UseKind::Glob)
3005 UseTreeKind::Nested(ref trees) => {
3010 .chain(path.segments.iter())
3013 span: prefix.span.to(path.span),
3016 // Add all the nested PathListItems in the HIR
3017 for &(ref use_tree, id) in trees {
3018 self.allocate_hir_id_counter(id, &use_tree);
3022 } = self.lower_node_id(id);
3024 let mut vis = vis.clone();
3025 let mut name = name.clone();
3027 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
3029 self.with_hir_id_owner(new_id, |this| {
3030 let vis_kind = match vis.node {
3031 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3032 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3033 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3034 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3035 let id = this.next_id();
3036 hir::VisibilityKind::Restricted {
3038 // We are allocating a new NodeId here
3044 let vis = respan(vis.span, vis_kind);
3052 attrs: attrs.clone(),
3055 span: use_tree.span,
3061 // Privatize the degenerate import base, used only to check
3062 // the stability of `use a::{};`, to avoid it showing up as
3063 // a re-export by accident when `pub`, e.g. in documentation.
3064 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
3065 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3066 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3071 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3072 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3073 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
3075 let (generics, node) = match i.node {
3076 TraitItemKind::Const(ref ty, ref default) => (
3077 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3078 hir::TraitItemKind::Const(
3079 self.lower_ty(ty, ImplTraitContext::Disallowed),
3082 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
3085 TraitItemKind::Method(ref sig, None) => {
3086 self.with_impl_trait_owner(trait_item_def_id, |this| {
3087 let names = this.lower_fn_args_to_names(&sig.decl);
3088 let (generics, sig) = this.lower_method_sig(
3095 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3098 TraitItemKind::Method(ref sig, Some(ref body)) => {
3099 self.with_impl_trait_owner(trait_item_def_id, |this| {
3100 let body_id = this.lower_body(Some(&sig.decl), |this| {
3101 let body = this.lower_block(body, false);
3102 this.expr_block(body, ThinVec::new())
3104 let (generics, sig) = this.lower_method_sig(
3111 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3114 TraitItemKind::Type(ref bounds, ref default) => (
3115 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3116 hir::TraitItemKind::Type(
3117 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3120 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
3123 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3130 attrs: self.lower_attrs(&i.attrs),
3137 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3138 let (kind, has_default) = match i.node {
3139 TraitItemKind::Const(_, ref default) => {
3140 (hir::AssociatedItemKind::Const, default.is_some())
3142 TraitItemKind::Type(_, ref default) => {
3143 (hir::AssociatedItemKind::Type, default.is_some())
3145 TraitItemKind::Method(ref sig, ref default) => (
3146 hir::AssociatedItemKind::Method {
3147 has_self: sig.decl.has_self(),
3151 TraitItemKind::Macro(..) => unimplemented!(),
3154 id: hir::TraitItemId { node_id: i.id },
3157 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3162 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3163 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3164 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3166 let (generics, node) = match i.node {
3167 ImplItemKind::Const(ref ty, ref expr) => {
3168 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3170 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3171 hir::ImplItemKind::Const(
3172 self.lower_ty(ty, ImplTraitContext::Disallowed),
3177 ImplItemKind::Method(ref sig, ref body) => {
3178 self.with_impl_trait_owner(impl_item_def_id, |this| {
3179 let body_id = this.lower_async_body(&sig.decl, sig.header.asyncness, body);
3180 let impl_trait_return_allow = !this.is_in_trait_impl;
3181 let (generics, sig) = this.lower_method_sig(
3185 impl_trait_return_allow,
3186 sig.header.asyncness.opt_return_id(),
3188 (generics, hir::ImplItemKind::Method(sig, body_id))
3191 ImplItemKind::Type(ref ty) => (
3192 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3193 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
3195 ImplItemKind::Existential(ref bounds) => (
3196 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3197 hir::ImplItemKind::Existential(
3198 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3201 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3208 attrs: self.lower_attrs(&i.attrs),
3210 vis: self.lower_visibility(&i.vis, None),
3211 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3216 // [1] since `default impl` is not yet implemented, this is always true in impls
3219 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3221 id: hir::ImplItemId { node_id: i.id },
3224 vis: self.lower_visibility(&i.vis, Some(i.id)),
3225 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3226 kind: match i.node {
3227 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3228 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3229 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3230 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3231 has_self: sig.decl.has_self(),
3233 ImplItemKind::Macro(..) => unimplemented!(),
3237 // [1] since `default impl` is not yet implemented, this is always true in impls
3240 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3243 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3247 /// Lowers `impl Trait` items for a function and appends them to the list
3248 fn lower_fn_impl_trait_ids(
3252 ids: &mut OneVector<hir::ItemId>,
3254 if let Some(id) = header.asyncness.opt_return_id() {
3255 ids.push(hir::ItemId { id });
3257 let mut visitor = ImplTraitTypeIdVisitor { ids };
3259 FunctionRetTy::Default(_) => {},
3260 FunctionRetTy::Ty(ref ty) => visitor.visit_ty(ty),
3264 fn lower_item_id(&mut self, i: &Item) -> OneVector<hir::ItemId> {
3266 ItemKind::Use(ref use_tree) => {
3267 let mut vec = smallvec![hir::ItemId { id: i.id }];
3268 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3271 ItemKind::MacroDef(..) => OneVector::new(),
3272 ItemKind::Fn(ref decl, ref header, ..) => {
3273 let mut ids = smallvec![hir::ItemId { id: i.id }];
3274 self.lower_fn_impl_trait_ids(decl, header, &mut ids);
3277 ItemKind::Impl(.., None, _, ref items) => {
3278 let mut ids = smallvec![hir::ItemId { id: i.id }];
3280 if let ImplItemKind::Method(ref sig, _) = item.node {
3281 self.lower_fn_impl_trait_ids(&sig.decl, &sig.header, &mut ids);
3286 ItemKind::Static(ref ty, ..) => {
3287 let mut ids = smallvec![hir::ItemId { id: i.id }];
3288 if self.sess.features_untracked().impl_trait_in_bindings {
3289 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3290 visitor.visit_ty(ty);
3294 ItemKind::Const(ref ty, ..) => {
3295 let mut ids = smallvec![hir::ItemId { id: i.id }];
3296 if self.sess.features_untracked().impl_trait_in_bindings {
3297 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3298 visitor.visit_ty(ty);
3302 _ => smallvec![hir::ItemId { id: i.id }],
3306 fn lower_item_id_use_tree(&mut self,
3309 vec: &mut OneVector<hir::ItemId>)
3312 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3313 vec.push(hir::ItemId { id });
3314 self.lower_item_id_use_tree(nested, id, vec);
3316 UseTreeKind::Glob => {}
3317 UseTreeKind::Simple(_, id1, id2) => {
3318 for (_, &id) in self.expect_full_def_from_use(base_id)
3320 .zip([id1, id2].iter())
3322 vec.push(hir::ItemId { id });
3328 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3329 let mut name = i.ident.name;
3330 let mut vis = self.lower_visibility(&i.vis, None);
3331 let attrs = self.lower_attrs(&i.attrs);
3332 if let ItemKind::MacroDef(ref def) = i.node {
3333 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3334 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3335 let body = self.lower_token_stream(def.stream());
3336 self.exported_macros.push(hir::MacroDef {
3349 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3351 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3364 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3365 let node_id = self.lower_node_id(i.id).node_id;
3366 let def_id = self.resolver.definitions().local_def_id(node_id);
3370 attrs: self.lower_attrs(&i.attrs),
3371 node: match i.node {
3372 ForeignItemKind::Fn(ref fdec, ref generics) => {
3373 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3376 AnonymousLifetimeMode::PassThrough,
3379 // Disallow impl Trait in foreign items
3380 this.lower_fn_decl(fdec, None, false, None),
3381 this.lower_fn_args_to_names(fdec),
3386 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3388 ForeignItemKind::Static(ref t, m) => {
3389 hir::ForeignItemKind::Static(self.lower_ty(t, ImplTraitContext::Disallowed), m)
3391 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3392 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3394 vis: self.lower_visibility(&i.vis, None),
3399 fn lower_method_sig(
3401 generics: &Generics,
3404 impl_trait_return_allow: bool,
3405 is_async: Option<NodeId>,
3406 ) -> (hir::Generics, hir::MethodSig) {
3407 let header = self.lower_fn_header(sig.header);
3408 let (generics, decl) = self.add_in_band_defs(
3411 AnonymousLifetimeMode::PassThrough,
3412 |this, idty| this.lower_fn_decl(
3414 Some((fn_def_id, idty)),
3415 impl_trait_return_allow,
3419 (generics, hir::MethodSig { header, decl })
3422 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3424 IsAuto::Yes => hir::IsAuto::Yes,
3425 IsAuto::No => hir::IsAuto::No,
3429 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3431 unsafety: self.lower_unsafety(h.unsafety),
3432 asyncness: self.lower_asyncness(h.asyncness),
3433 constness: self.lower_constness(h.constness),
3438 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3440 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3441 Unsafety::Normal => hir::Unsafety::Normal,
3445 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3447 Constness::Const => hir::Constness::Const,
3448 Constness::NotConst => hir::Constness::NotConst,
3452 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3454 IsAsync::Async { .. } => hir::IsAsync::Async,
3455 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3459 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3461 UnOp::Deref => hir::UnDeref,
3462 UnOp::Not => hir::UnNot,
3463 UnOp::Neg => hir::UnNeg,
3467 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3469 node: match b.node {
3470 BinOpKind::Add => hir::BinOpKind::Add,
3471 BinOpKind::Sub => hir::BinOpKind::Sub,
3472 BinOpKind::Mul => hir::BinOpKind::Mul,
3473 BinOpKind::Div => hir::BinOpKind::Div,
3474 BinOpKind::Rem => hir::BinOpKind::Rem,
3475 BinOpKind::And => hir::BinOpKind::And,
3476 BinOpKind::Or => hir::BinOpKind::Or,
3477 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3478 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3479 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3480 BinOpKind::Shl => hir::BinOpKind::Shl,
3481 BinOpKind::Shr => hir::BinOpKind::Shr,
3482 BinOpKind::Eq => hir::BinOpKind::Eq,
3483 BinOpKind::Lt => hir::BinOpKind::Lt,
3484 BinOpKind::Le => hir::BinOpKind::Le,
3485 BinOpKind::Ne => hir::BinOpKind::Ne,
3486 BinOpKind::Ge => hir::BinOpKind::Ge,
3487 BinOpKind::Gt => hir::BinOpKind::Gt,
3493 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3494 let node = match p.node {
3495 PatKind::Wild => hir::PatKind::Wild,
3496 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3497 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3498 // `None` can occur in body-less function signatures
3499 def @ None | def @ Some(Def::Local(_)) => {
3500 let canonical_id = match def {
3501 Some(Def::Local(id)) => id,
3504 hir::PatKind::Binding(
3505 self.lower_binding_mode(binding_mode),
3508 sub.as_ref().map(|x| self.lower_pat(x)),
3511 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3516 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3521 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3522 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3523 let qpath = self.lower_qpath(
3527 ParamMode::Optional,
3528 ImplTraitContext::Disallowed,
3530 self.check_self_struct_ctor_feature(&qpath);
3531 hir::PatKind::TupleStruct(
3533 pats.iter().map(|x| self.lower_pat(x)).collect(),
3537 PatKind::Path(ref qself, ref path) => {
3538 let qpath = self.lower_qpath(
3542 ParamMode::Optional,
3543 ImplTraitContext::Disallowed,
3545 self.check_self_struct_ctor_feature(&qpath);
3546 hir::PatKind::Path(qpath)
3548 PatKind::Struct(ref path, ref fields, etc) => {
3549 let qpath = self.lower_qpath(
3553 ParamMode::Optional,
3554 ImplTraitContext::Disallowed,
3561 node: hir::FieldPat {
3562 id: self.next_id().node_id,
3563 ident: f.node.ident,
3564 pat: self.lower_pat(&f.node.pat),
3565 is_shorthand: f.node.is_shorthand,
3569 hir::PatKind::Struct(qpath, fs, etc)
3571 PatKind::Tuple(ref elts, ddpos) => {
3572 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3574 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3575 PatKind::Ref(ref inner, mutbl) => {
3576 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3578 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3579 P(self.lower_expr(e1)),
3580 P(self.lower_expr(e2)),
3581 self.lower_range_end(end),
3583 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3584 before.iter().map(|x| self.lower_pat(x)).collect(),
3585 slice.as_ref().map(|x| self.lower_pat(x)),
3586 after.iter().map(|x| self.lower_pat(x)).collect(),
3588 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3589 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3592 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3601 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3603 RangeEnd::Included(_) => hir::RangeEnd::Included,
3604 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3608 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3609 self.with_new_scopes(|this| {
3610 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3614 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3619 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3620 let kind = match e.node {
3621 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3622 ExprKind::ObsoleteInPlace(..) => {
3623 self.sess.abort_if_errors();
3624 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3626 ExprKind::Array(ref exprs) => {
3627 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3629 ExprKind::Repeat(ref expr, ref count) => {
3630 let expr = P(self.lower_expr(expr));
3631 let count = self.lower_anon_const(count);
3632 hir::ExprKind::Repeat(expr, count)
3634 ExprKind::Tup(ref elts) => {
3635 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3637 ExprKind::Call(ref f, ref args) => {
3638 let f = P(self.lower_expr(f));
3639 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3641 ExprKind::MethodCall(ref seg, ref args) => {
3642 let hir_seg = self.lower_path_segment(
3645 ParamMode::Optional,
3647 ParenthesizedGenericArgs::Err,
3648 ImplTraitContext::Disallowed,
3650 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3651 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3653 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3654 let binop = self.lower_binop(binop);
3655 let lhs = P(self.lower_expr(lhs));
3656 let rhs = P(self.lower_expr(rhs));
3657 hir::ExprKind::Binary(binop, lhs, rhs)
3659 ExprKind::Unary(op, ref ohs) => {
3660 let op = self.lower_unop(op);
3661 let ohs = P(self.lower_expr(ohs));
3662 hir::ExprKind::Unary(op, ohs)
3664 ExprKind::Lit(ref l) => hir::ExprKind::Lit(P((**l).clone())),
3665 ExprKind::Cast(ref expr, ref ty) => {
3666 let expr = P(self.lower_expr(expr));
3667 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3669 ExprKind::Type(ref expr, ref ty) => {
3670 let expr = P(self.lower_expr(expr));
3671 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3673 ExprKind::AddrOf(m, ref ohs) => {
3674 let m = self.lower_mutability(m);
3675 let ohs = P(self.lower_expr(ohs));
3676 hir::ExprKind::AddrOf(m, ohs)
3678 // More complicated than you might expect because the else branch
3679 // might be `if let`.
3680 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3681 let else_opt = else_opt.as_ref().map(|els| {
3683 ExprKind::IfLet(..) => {
3684 // wrap the if-let expr in a block
3685 let span = els.span;
3686 let els = P(self.lower_expr(els));
3687 let LoweredNodeId { node_id, hir_id } = self.next_id();
3688 let blk = P(hir::Block {
3693 rules: hir::DefaultBlock,
3695 targeted_by_break: false,
3696 recovered: blk.recovered,
3698 P(self.expr_block(blk, ThinVec::new()))
3700 _ => P(self.lower_expr(els)),
3704 let then_blk = self.lower_block(blk, false);
3705 let then_expr = self.expr_block(then_blk, ThinVec::new());
3707 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3709 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3710 hir::ExprKind::While(
3711 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3712 this.lower_block(body, false),
3713 this.lower_label(opt_label),
3716 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3717 hir::ExprKind::Loop(
3718 this.lower_block(body, false),
3719 this.lower_label(opt_label),
3720 hir::LoopSource::Loop,
3723 ExprKind::TryBlock(ref body) => {
3724 self.with_catch_scope(body.id, |this| {
3726 this.allow_internal_unstable(CompilerDesugaringKind::TryBlock, body.span);
3727 let mut block = this.lower_block(body, true).into_inner();
3728 let tail = block.expr.take().map_or_else(
3730 let LoweredNodeId { node_id, hir_id } = this.next_id();
3731 let span = this.sess.source_map().end_point(unstable_span);
3735 node: hir::ExprKind::Tup(hir_vec![]),
3736 attrs: ThinVec::new(),
3740 |x: P<hir::Expr>| x.into_inner(),
3742 block.expr = Some(this.wrap_in_try_constructor(
3743 "from_ok", tail, unstable_span));
3744 hir::ExprKind::Block(P(block), None)
3747 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3748 P(self.lower_expr(expr)),
3749 arms.iter().map(|x| self.lower_arm(x)).collect(),
3750 hir::MatchSource::Normal,
3752 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3753 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3754 this.with_new_scopes(|this| {
3755 let block = this.lower_block(block, false);
3756 this.expr_block(block, ThinVec::new())
3761 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3763 if let IsAsync::Async { closure_id, .. } = asyncness {
3764 let outer_decl = FnDecl {
3765 inputs: decl.inputs.clone(),
3766 output: FunctionRetTy::Default(fn_decl_span),
3769 // We need to lower the declaration outside the new scope, because we
3770 // have to conserve the state of being inside a loop condition for the
3771 // closure argument types.
3772 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3774 self.with_new_scopes(|this| {
3775 // FIXME(cramertj) allow `async` non-`move` closures with
3776 if capture_clause == CaptureBy::Ref &&
3777 !decl.inputs.is_empty()
3783 "`async` non-`move` closures with arguments \
3784 are not currently supported",
3786 .help("consider using `let` statements to manually capture \
3787 variables by reference before entering an \
3788 `async move` closure")
3792 // Transform `async |x: u8| -> X { ... }` into
3793 // `|x: u8| future_from_generator(|| -> X { ... })`
3794 let body_id = this.lower_body(Some(&outer_decl), |this| {
3795 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3798 let async_body = this.make_async_expr(
3799 capture_clause, closure_id, async_ret_ty,
3801 this.with_new_scopes(|this| this.lower_expr(body))
3803 this.expr(fn_decl_span, async_body, ThinVec::new())
3805 hir::ExprKind::Closure(
3806 this.lower_capture_clause(capture_clause),
3814 // Lower outside new scope to preserve `is_in_loop_condition`.
3815 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3817 self.with_new_scopes(|this| {
3818 let mut is_generator = false;
3819 let body_id = this.lower_body(Some(decl), |this| {
3820 let e = this.lower_expr(body);
3821 is_generator = this.is_generator;
3824 let generator_option = if is_generator {
3825 if !decl.inputs.is_empty() {
3830 "generators cannot have explicit arguments"
3832 this.sess.abort_if_errors();
3834 Some(match movability {
3835 Movability::Movable => hir::GeneratorMovability::Movable,
3836 Movability::Static => hir::GeneratorMovability::Static,
3839 if movability == Movability::Static {
3844 "closures cannot be static"
3849 hir::ExprKind::Closure(
3850 this.lower_capture_clause(capture_clause),
3859 ExprKind::Block(ref blk, opt_label) => {
3860 hir::ExprKind::Block(self.lower_block(blk,
3861 opt_label.is_some()),
3862 self.lower_label(opt_label))
3864 ExprKind::Assign(ref el, ref er) => {
3865 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3867 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
3868 self.lower_binop(op),
3869 P(self.lower_expr(el)),
3870 P(self.lower_expr(er)),
3872 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
3873 ExprKind::Index(ref el, ref er) => {
3874 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
3876 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3877 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3878 let id = self.next_id();
3879 let e1 = self.lower_expr(e1);
3880 let e2 = self.lower_expr(e2);
3881 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
3882 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
3883 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3884 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3885 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
3886 hir::ExprKind::Call(new, hir_vec![e1, e2])
3888 ExprKind::Range(ref e1, ref e2, lims) => {
3889 use syntax::ast::RangeLimits::*;
3891 let path = match (e1, e2, lims) {
3892 (&None, &None, HalfOpen) => "RangeFull",
3893 (&Some(..), &None, HalfOpen) => "RangeFrom",
3894 (&None, &Some(..), HalfOpen) => "RangeTo",
3895 (&Some(..), &Some(..), HalfOpen) => "Range",
3896 (&None, &Some(..), Closed) => "RangeToInclusive",
3897 (&Some(..), &Some(..), Closed) => unreachable!(),
3898 (_, &None, Closed) => self.diagnostic()
3899 .span_fatal(e.span, "inclusive range with no end")
3903 let fields = e1.iter()
3904 .map(|e| ("start", e))
3905 .chain(e2.iter().map(|e| ("end", e)))
3907 let expr = P(self.lower_expr(&e));
3908 let ident = Ident::new(Symbol::intern(s), e.span);
3909 self.field(ident, expr, e.span)
3911 .collect::<P<[hir::Field]>>();
3913 let is_unit = fields.is_empty();
3914 let struct_path = iter::once("ops")
3915 .chain(iter::once(path))
3916 .collect::<Vec<_>>();
3917 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
3918 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3920 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3926 hir::ExprKind::Path(struct_path)
3928 hir::ExprKind::Struct(struct_path, fields, None)
3931 attrs: e.attrs.clone(),
3934 ExprKind::Path(ref qself, ref path) => {
3935 let qpath = self.lower_qpath(
3939 ParamMode::Optional,
3940 ImplTraitContext::Disallowed,
3942 self.check_self_struct_ctor_feature(&qpath);
3943 hir::ExprKind::Path(qpath)
3945 ExprKind::Break(opt_label, ref opt_expr) => {
3946 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3949 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3952 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3954 hir::ExprKind::Break(
3956 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3959 ExprKind::Continue(opt_label) => {
3960 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
3963 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3966 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3969 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
3970 ExprKind::InlineAsm(ref asm) => {
3971 let hir_asm = hir::InlineAsm {
3972 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3973 outputs: asm.outputs
3975 .map(|out| hir::InlineAsmOutput {
3976 constraint: out.constraint.clone(),
3978 is_indirect: out.is_indirect,
3981 asm: asm.asm.clone(),
3982 asm_str_style: asm.asm_str_style,
3983 clobbers: asm.clobbers.clone().into(),
3984 volatile: asm.volatile,
3985 alignstack: asm.alignstack,
3986 dialect: asm.dialect,
3989 let outputs = asm.outputs
3991 .map(|out| self.lower_expr(&out.expr))
3993 let inputs = asm.inputs
3995 .map(|&(_, ref input)| self.lower_expr(input))
3997 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
3999 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4004 ParamMode::Optional,
4005 ImplTraitContext::Disallowed,
4007 fields.iter().map(|x| self.lower_field(x)).collect(),
4008 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4010 ExprKind::Paren(ref ex) => {
4011 let mut ex = self.lower_expr(ex);
4012 // include parens in span, but only if it is a super-span.
4013 if e.span.contains(ex.span) {
4016 // merge attributes into the inner expression.
4017 let mut attrs = e.attrs.clone();
4018 attrs.extend::<Vec<_>>(ex.attrs.into());
4023 ExprKind::Yield(ref opt_expr) => {
4024 self.is_generator = true;
4027 .map(|x| self.lower_expr(x))
4029 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
4031 hir::ExprKind::Yield(P(expr))
4034 // Desugar ExprIfLet
4035 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
4036 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4039 // match <sub_expr> {
4041 // _ => [<else_opt> | ()]
4044 let mut arms = vec![];
4046 // `<pat> => <body>`
4048 let body = self.lower_block(body, false);
4049 let body_expr = P(self.expr_block(body, ThinVec::new()));
4050 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4051 arms.push(self.arm(pats, body_expr));
4054 // _ => [<else_opt>|()]
4056 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4057 let wildcard_pattern = self.pat_wild(e.span);
4058 let body = if let Some(else_expr) = wildcard_arm {
4059 P(self.lower_expr(else_expr))
4061 self.expr_tuple(e.span, hir_vec![])
4063 arms.push(self.arm(hir_vec![wildcard_pattern], body));
4066 let contains_else_clause = else_opt.is_some();
4068 let sub_expr = P(self.lower_expr(sub_expr));
4070 hir::ExprKind::Match(
4073 hir::MatchSource::IfLetDesugar {
4074 contains_else_clause,
4079 // Desugar ExprWhileLet
4080 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4081 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4084 // [opt_ident]: loop {
4085 // match <sub_expr> {
4091 // Note that the block AND the condition are evaluated in the loop scope.
4092 // This is done to allow `break` from inside the condition of the loop.
4093 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4095 this.lower_block(body, false),
4096 this.expr_break(e.span, ThinVec::new()),
4097 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4101 // `<pat> => <body>`
4103 let body_expr = P(self.expr_block(body, ThinVec::new()));
4104 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4105 self.arm(pats, body_expr)
4110 let pat_under = self.pat_wild(e.span);
4111 self.arm(hir_vec![pat_under], break_expr)
4114 // `match <sub_expr> { ... }`
4115 let arms = hir_vec![pat_arm, break_arm];
4116 let match_expr = self.expr(
4118 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4122 // `[opt_ident]: loop { ... }`
4123 let loop_block = P(self.block_expr(P(match_expr)));
4124 let loop_expr = hir::ExprKind::Loop(
4126 self.lower_label(opt_label),
4127 hir::LoopSource::WhileLet,
4129 // add attributes to the outer returned expr node
4133 // Desugar ExprForLoop
4134 // From: `[opt_ident]: for <pat> in <head> <body>`
4135 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4139 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4141 // [opt_ident]: loop {
4143 // match ::std::iter::Iterator::next(&mut iter) {
4144 // ::std::option::Option::Some(val) => __next = val,
4145 // ::std::option::Option::None => break
4147 // let <pat> = __next;
4148 // StmtKind::Expr(<body>);
4156 let head = self.lower_expr(head);
4157 let head_sp = head.span;
4159 let iter = self.str_to_ident("iter");
4161 let next_ident = self.str_to_ident("__next");
4162 let next_sp = self.allow_internal_unstable(
4163 CompilerDesugaringKind::ForLoop,
4166 let next_pat = self.pat_ident_binding_mode(
4169 hir::BindingAnnotation::Mutable,
4172 // `::std::option::Option::Some(val) => next = val`
4174 let val_ident = self.str_to_ident("val");
4175 let val_pat = self.pat_ident(pat.span, val_ident);
4176 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4177 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4178 let assign = P(self.expr(
4180 hir::ExprKind::Assign(next_expr, val_expr),
4183 let some_pat = self.pat_some(pat.span, val_pat);
4184 self.arm(hir_vec![some_pat], assign)
4187 // `::std::option::Option::None => break`
4190 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4191 let pat = self.pat_none(e.span);
4192 self.arm(hir_vec![pat], break_expr)
4197 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
4199 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4201 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4202 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4203 let next_path = &["iter", "Iterator", "next"];
4204 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4205 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4206 let arms = hir_vec![pat_arm, break_arm];
4210 hir::ExprKind::Match(
4213 hir::MatchSource::ForLoopDesugar
4218 let match_stmt = respan(
4220 hir::StmtKind::Expr(match_expr, self.next_id().node_id)
4223 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4227 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
4229 // `let <pat> = __next`
4230 let pat = self.lower_pat(pat);
4231 let pat_let = self.stmt_let_pat(
4235 hir::LocalSource::ForLoopDesugar,
4238 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4239 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4240 let body_stmt = respan(
4242 hir::StmtKind::Expr(body_expr, self.next_id().node_id)
4245 let loop_block = P(self.block_all(
4247 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4251 // `[opt_ident]: loop { ... }`
4252 let loop_expr = hir::ExprKind::Loop(
4254 self.lower_label(opt_label),
4255 hir::LoopSource::ForLoop,
4257 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4258 let loop_expr = P(hir::Expr {
4263 attrs: ThinVec::new(),
4266 // `mut iter => { ... }`
4267 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4269 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4270 let into_iter_expr = {
4271 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4272 let into_iter = P(self.expr_std_path(
4273 head_sp, into_iter_path, None, ThinVec::new()));
4274 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4277 let match_expr = P(self.expr_match(
4281 hir::MatchSource::ForLoopDesugar,
4284 // `{ let _result = ...; _result }`
4285 // underscore prevents an unused_variables lint if the head diverges
4286 let result_ident = self.str_to_ident("_result");
4287 let (let_stmt, let_stmt_binding) =
4288 self.stmt_let(e.span, false, result_ident, match_expr);
4290 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4291 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4292 // add the attributes to the outer returned expr node
4293 return self.expr_block(block, e.attrs.clone());
4296 // Desugar ExprKind::Try
4298 ExprKind::Try(ref sub_expr) => {
4301 // match Try::into_result(<expr>) {
4302 // Ok(val) => #[allow(unreachable_code)] val,
4303 // Err(err) => #[allow(unreachable_code)]
4304 // // If there is an enclosing `catch {...}`
4305 // break 'catch_target Try::from_error(From::from(err)),
4307 // return Try::from_error(From::from(err)),
4311 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4313 // Try::into_result(<expr>)
4316 let sub_expr = self.lower_expr(sub_expr);
4318 let path = &["ops", "Try", "into_result"];
4319 let path = P(self.expr_std_path(
4320 unstable_span, path, None, ThinVec::new()));
4321 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4324 // #[allow(unreachable_code)]
4326 // allow(unreachable_code)
4328 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4329 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4330 let uc_nested = attr::mk_nested_word_item(uc_ident);
4331 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4333 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4335 let attrs = vec![attr];
4337 // Ok(val) => #[allow(unreachable_code)] val,
4339 let val_ident = self.str_to_ident("val");
4340 let val_pat = self.pat_ident(e.span, val_ident);
4341 let val_expr = P(self.expr_ident_with_attrs(
4345 ThinVec::from(attrs.clone()),
4347 let ok_pat = self.pat_ok(e.span, val_pat);
4349 self.arm(hir_vec![ok_pat], val_expr)
4352 // Err(err) => #[allow(unreachable_code)]
4353 // return Try::from_error(From::from(err)),
4355 let err_ident = self.str_to_ident("err");
4356 let err_local = self.pat_ident(e.span, err_ident);
4358 let path = &["convert", "From", "from"];
4359 let from = P(self.expr_std_path(
4360 e.span, path, None, ThinVec::new()));
4361 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4363 self.expr_call(e.span, from, hir_vec![err_expr])
4366 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4367 let thin_attrs = ThinVec::from(attrs);
4368 let catch_scope = self.catch_scopes.last().map(|x| *x);
4369 let ret_expr = if let Some(catch_node) = catch_scope {
4372 hir::ExprKind::Break(
4375 target_id: Ok(catch_node),
4377 Some(from_err_expr),
4382 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4385 let err_pat = self.pat_err(e.span, err_local);
4386 self.arm(hir_vec![err_pat], ret_expr)
4389 hir::ExprKind::Match(
4391 hir_vec![err_arm, ok_arm],
4392 hir::MatchSource::TryDesugar,
4396 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4399 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4406 attrs: e.attrs.clone(),
4410 fn lower_stmt(&mut self, s: &Stmt) -> OneVector<hir::Stmt> {
4411 smallvec![match s.node {
4412 StmtKind::Local(ref l) => {
4413 let (l, item_ids) = self.lower_local(l);
4414 let mut ids: OneVector<hir::Stmt> = item_ids
4416 .map(|item_id| Spanned {
4417 node: hir::StmtKind::Decl(
4419 node: hir::DeclKind::Item(item_id),
4422 self.next_id().node_id,
4428 node: hir::StmtKind::Decl(
4430 node: hir::DeclKind::Local(l),
4433 self.lower_node_id(s.id).node_id,
4439 StmtKind::Item(ref it) => {
4440 // Can only use the ID once.
4441 let mut id = Some(s.id);
4442 return self.lower_item_id(it)
4444 .map(|item_id| Spanned {
4445 node: hir::StmtKind::Decl(
4447 node: hir::DeclKind::Item(item_id),
4451 .map(|id| self.lower_node_id(id).node_id)
4452 .unwrap_or_else(|| self.next_id().node_id),
4458 StmtKind::Expr(ref e) => Spanned {
4459 node: hir::StmtKind::Expr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4462 StmtKind::Semi(ref e) => Spanned {
4463 node: hir::StmtKind::Semi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4466 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4470 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4472 CaptureBy::Value => hir::CaptureByValue,
4473 CaptureBy::Ref => hir::CaptureByRef,
4477 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4478 /// the address space of that item instead of the item currently being
4479 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4480 /// lower a `Visibility` value although we haven't lowered the owning
4481 /// `ImplItem` in question yet.
4482 fn lower_visibility(
4485 explicit_owner: Option<NodeId>,
4486 ) -> hir::Visibility {
4487 let node = match v.node {
4488 VisibilityKind::Public => hir::VisibilityKind::Public,
4489 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4490 VisibilityKind::Restricted { ref path, id } => {
4491 let lowered_id = if let Some(owner) = explicit_owner {
4492 self.lower_node_id_with_owner(id, owner)
4494 self.lower_node_id(id)
4496 hir::VisibilityKind::Restricted {
4497 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4498 id: lowered_id.node_id,
4499 hir_id: lowered_id.hir_id,
4502 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4504 respan(v.span, node)
4507 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4509 Defaultness::Default => hir::Defaultness::Default {
4510 has_value: has_value,
4512 Defaultness::Final => {
4514 hir::Defaultness::Final
4519 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4521 BlockCheckMode::Default => hir::DefaultBlock,
4522 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4526 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4528 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4529 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4530 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4531 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4535 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4537 CompilerGenerated => hir::CompilerGenerated,
4538 UserProvided => hir::UserProvided,
4542 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4544 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4545 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4549 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4551 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4552 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4556 // Helper methods for building HIR.
4558 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4567 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4569 id: self.next_id().node_id,
4573 is_shorthand: false,
4577 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4578 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4579 P(self.expr(span, expr_break, attrs))
4586 args: hir::HirVec<hir::Expr>,
4588 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4591 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4592 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4595 fn expr_ident_with_attrs(
4600 attrs: ThinVec<Attribute>,
4602 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4606 def: Def::Local(binding),
4607 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4611 self.expr(span, expr_path, attrs)
4614 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4615 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4621 components: &[&str],
4622 params: Option<P<hir::GenericArgs>>,
4623 attrs: ThinVec<Attribute>,
4625 let path = self.std_path(span, components, params, true);
4628 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4637 arms: hir::HirVec<hir::Arm>,
4638 source: hir::MatchSource,
4640 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4643 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4644 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4647 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4648 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4651 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4652 let LoweredNodeId { node_id, hir_id } = self.next_id();
4665 ex: Option<P<hir::Expr>>,
4667 source: hir::LocalSource,
4669 let LoweredNodeId { node_id, hir_id } = self.next_id();
4671 let local = P(hir::Local {
4678 attrs: ThinVec::new(),
4681 let decl = respan(sp, hir::DeclKind::Local(local));
4682 respan(sp, hir::StmtKind::Decl(P(decl), self.next_id().node_id))
4691 ) -> (hir::Stmt, NodeId) {
4692 let pat = if mutbl {
4693 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4695 self.pat_ident(sp, ident)
4697 let pat_id = pat.id;
4699 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4704 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4705 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4711 stmts: hir::HirVec<hir::Stmt>,
4712 expr: Option<P<hir::Expr>>,
4714 let LoweredNodeId { node_id, hir_id } = self.next_id();
4721 rules: hir::DefaultBlock,
4723 targeted_by_break: false,
4728 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4729 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4732 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4733 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4736 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4737 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4740 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4741 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4747 components: &[&str],
4748 subpats: hir::HirVec<P<hir::Pat>>,
4750 let path = self.std_path(span, components, None, true);
4751 let qpath = hir::QPath::Resolved(None, P(path));
4752 let pt = if subpats.is_empty() {
4753 hir::PatKind::Path(qpath)
4755 hir::PatKind::TupleStruct(qpath, subpats, None)
4760 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4761 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4764 fn pat_ident_binding_mode(
4768 bm: hir::BindingAnnotation,
4770 let LoweredNodeId { node_id, hir_id } = self.next_id();
4775 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4780 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4781 self.pat(span, hir::PatKind::Wild)
4784 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4785 let LoweredNodeId { node_id, hir_id } = self.next_id();
4794 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4795 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4796 /// The path is also resolved according to `is_value`.
4800 components: &[&str],
4801 params: Option<P<hir::GenericArgs>>,
4805 .resolve_str_path(span, self.crate_root, components, params, is_value)
4808 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4810 let node = match qpath {
4811 hir::QPath::Resolved(None, path) => {
4812 // Turn trait object paths into `TyKind::TraitObject` instead.
4813 if let Def::Trait(_) = path.def {
4814 let principal = hir::PolyTraitRef {
4815 bound_generic_params: hir::HirVec::new(),
4816 trait_ref: hir::TraitRef {
4817 path: path.and_then(|path| path),
4819 hir_ref_id: id.hir_id,
4824 // The original ID is taken by the `PolyTraitRef`,
4825 // so the `Ty` itself needs a different one.
4826 id = self.next_id();
4827 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4829 hir::TyKind::Path(hir::QPath::Resolved(None, path))
4832 _ => hir::TyKind::Path(qpath),
4842 /// Invoked to create the lifetime argument for a type `&T`
4843 /// with no explicit lifetime.
4844 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4845 match self.anonymous_lifetime_mode {
4846 // Intercept when we are in an impl header and introduce an in-band lifetime.
4847 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4849 AnonymousLifetimeMode::CreateParameter => {
4850 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4852 id: self.next_id().node_id,
4854 name: hir::LifetimeName::Param(fresh_name),
4858 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4862 /// Invoked to create the lifetime argument(s) for a path like
4863 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4864 /// sorts of cases are deprecated. This may therefore report a warning or an
4865 /// error, depending on the mode.
4866 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4867 match self.anonymous_lifetime_mode {
4868 // NB. We intentionally ignore the create-parameter mode here
4869 // and instead "pass through" to resolve-lifetimes, which will then
4870 // report an error. This is because we don't want to support
4871 // impl elision for deprecated forms like
4873 // impl Foo for std::cell::Ref<u32> // note lack of '_
4874 AnonymousLifetimeMode::CreateParameter => {}
4876 // This is the normal case.
4877 AnonymousLifetimeMode::PassThrough => {}
4881 .map(|_| self.new_implicit_lifetime(span))
4885 /// Invoked to create the lifetime argument(s) for an elided trait object
4886 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4887 /// when the bound is written, even if it is written with `'_` like in
4888 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4889 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4890 match self.anonymous_lifetime_mode {
4891 // NB. We intentionally ignore the create-parameter mode here.
4892 // and instead "pass through" to resolve-lifetimes, which will apply
4893 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4894 // do not act like other elided lifetimes. In other words, given this:
4896 // impl Foo for Box<dyn Debug>
4898 // we do not introduce a fresh `'_` to serve as the bound, but instead
4899 // ultimately translate to the equivalent of:
4901 // impl Foo for Box<dyn Debug + 'static>
4903 // `resolve_lifetime` has the code to make that happen.
4904 AnonymousLifetimeMode::CreateParameter => {}
4906 // This is the normal case.
4907 AnonymousLifetimeMode::PassThrough => {}
4910 self.new_implicit_lifetime(span)
4913 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4915 id: self.next_id().node_id,
4917 name: hir::LifetimeName::Implicit,
4921 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4922 self.sess.buffer_lint_with_diagnostic(
4923 builtin::BARE_TRAIT_OBJECTS,
4926 "trait objects without an explicit `dyn` are deprecated",
4927 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4931 fn wrap_in_try_constructor(
4933 method: &'static str,
4935 unstable_span: Span,
4937 let path = &["ops", "Try", method];
4938 let from_err = P(self.expr_std_path(unstable_span, path, None,
4940 P(self.expr_call(e.span, from_err, hir_vec![e]))
4943 fn check_self_struct_ctor_feature(&self, qp: &hir::QPath) {
4944 if let hir::QPath::Resolved(_, ref p) = qp {
4945 if p.segments.len() == 1 &&
4946 p.segments[0].ident.name == keywords::SelfType.name() &&
4947 !self.sess.features_untracked().self_struct_ctor {
4948 emit_feature_err(&self.sess.parse_sess, "self_struct_ctor",
4949 p.span, GateIssue::Language,
4950 "`Self` struct constructors are unstable");
4956 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4957 // Sorting by span ensures that we get things in order within a
4958 // file, and also puts the files in a sensible order.
4959 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4960 body_ids.sort_by_key(|b| bodies[b].value.span);