1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Lowers the AST to the HIR.
13 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
14 //! much like a fold. Where lowering involves a bit more work things get more
15 //! interesting and there are some invariants you should know about. These mostly
16 //! concern spans and ids.
18 //! Spans are assigned to AST nodes during parsing and then are modified during
19 //! expansion to indicate the origin of a node and the process it went through
20 //! being expanded. Ids are assigned to AST nodes just before lowering.
22 //! For the simpler lowering steps, ids and spans should be preserved. Unlike
23 //! expansion we do not preserve the process of lowering in the spans, so spans
24 //! should not be modified here. When creating a new node (as opposed to
25 //! 'folding' an existing one), then you create a new id using `next_id()`.
27 //! You must ensure that ids are unique. That means that you should only use the
28 //! id from an AST node in a single HIR node (you can assume that AST node ids
29 //! are unique). Every new node must have a unique id. Avoid cloning HIR nodes.
30 //! If you do, you must then set the new node's id to a fresh one.
32 //! Spans are used for error messages and for tools to map semantics back to
33 //! source code. It is therefore not as important with spans as ids to be strict
34 //! about use (you can't break the compiler by screwing up a span). Obviously, a
35 //! HIR node can only have a single span. But multiple nodes can have the same
36 //! span and spans don't need to be kept in order, etc. Where code is preserved
37 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
38 //! new it is probably best to give a span for the whole AST node being lowered.
39 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
40 //! get confused if the spans from leaf AST nodes occur in multiple places
41 //! in the HIR, especially for multiple identifiers.
43 use dep_graph::DepGraph;
44 use hir::{self, ParamName};
46 use hir::map::{DefKey, DefPathData, Definitions};
47 use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX};
48 use hir::def::{Def, PathResolution, PerNS};
50 use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
51 ELIDED_LIFETIMES_IN_PATHS};
52 use middle::cstore::CrateStore;
53 use rustc_data_structures::fx::FxHashSet;
54 use rustc_data_structures::indexed_vec::IndexVec;
55 use rustc_data_structures::thin_vec::ThinVec;
57 use session::config::nightly_options;
58 use util::common::FN_OUTPUT_NAME;
59 use util::nodemap::{DefIdMap, NodeMap};
61 use std::collections::BTreeMap;
64 use smallvec::SmallVec;
69 use syntax::ext::hygiene::{Mark, SyntaxContext};
70 use syntax::print::pprust;
72 use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned};
73 use syntax::std_inject;
74 use syntax::symbol::{keywords, Symbol};
75 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
76 use syntax::parse::token::Token;
77 use syntax::visit::{self, Visitor};
78 use syntax_pos::{Span, MultiSpan};
80 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
82 pub struct LoweringContext<'a> {
83 crate_root: Option<&'static str>,
85 // Use to assign ids to hir nodes that do not directly correspond to an ast node
88 cstore: &'a dyn CrateStore,
90 resolver: &'a mut dyn Resolver,
92 /// The items being lowered are collected here.
93 items: BTreeMap<NodeId, hir::Item>,
95 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
96 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
97 bodies: BTreeMap<hir::BodyId, hir::Body>,
98 exported_macros: Vec<hir::MacroDef>,
100 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
101 trait_auto_impl: BTreeMap<DefId, NodeId>,
105 catch_scopes: Vec<NodeId>,
106 loop_scopes: Vec<NodeId>,
107 is_in_loop_condition: bool,
108 is_in_trait_impl: bool,
110 /// What to do when we encounter either an "anonymous lifetime
111 /// reference". The term "anonymous" is meant to encompass both
112 /// `'_` lifetimes as well as fully elided cases where nothing is
113 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
114 anonymous_lifetime_mode: AnonymousLifetimeMode,
116 // Used to create lifetime definitions from in-band lifetime usages.
117 // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
118 // When a named lifetime is encountered in a function or impl header and
119 // has not been defined
120 // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
121 // to this list. The results of this list are then added to the list of
122 // lifetime definitions in the corresponding impl or function generics.
123 lifetimes_to_define: Vec<(Span, ParamName)>,
125 // Whether or not in-band lifetimes are being collected. This is used to
126 // indicate whether or not we're in a place where new lifetimes will result
127 // in in-band lifetime definitions, such a function or an impl header,
128 // including implicit lifetimes from `impl_header_lifetime_elision`.
129 is_collecting_in_band_lifetimes: bool,
131 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
132 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
133 // against this list to see if it is already in-scope, or if a definition
134 // needs to be created for it.
135 in_scope_lifetimes: Vec<Ident>,
137 type_def_lifetime_params: DefIdMap<usize>,
139 current_hir_id_owner: Vec<(DefIndex, u32)>,
140 item_local_id_counters: NodeMap<u32>,
141 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
145 /// Resolve a path generated by the lowerer when expanding `for`, `if let`, etc.
152 /// Obtain the resolution for a node id
153 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
155 /// Obtain the possible resolutions for the given `use` statement.
156 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
158 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
159 /// This should only return `None` during testing.
160 fn definitions(&mut self) -> &mut Definitions;
162 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
163 /// it based on `is_value`.
167 crate_root: Option<&str>,
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.
192 Disallowed(ImplTraitPosition),
195 /// Position in which `impl Trait` is disallowed. Used for error reporting.
196 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
197 enum ImplTraitPosition {
202 impl<'a> ImplTraitContext<'a> {
204 fn disallowed() -> Self {
205 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
208 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
209 use self::ImplTraitContext::*;
211 Universal(params) => Universal(params),
212 Existential(did) => Existential(*did),
213 Disallowed(pos) => Disallowed(*pos),
220 cstore: &dyn CrateStore,
221 dep_graph: &DepGraph,
223 resolver: &mut dyn Resolver,
225 // We're constructing the HIR here; we don't care what we will
226 // read, since we haven't even constructed the *input* to
228 dep_graph.assert_ignored();
231 crate_root: std_inject::injected_crate_name(),
235 items: BTreeMap::new(),
236 trait_items: BTreeMap::new(),
237 impl_items: BTreeMap::new(),
238 bodies: BTreeMap::new(),
239 trait_impls: BTreeMap::new(),
240 trait_auto_impl: BTreeMap::new(),
241 exported_macros: Vec::new(),
242 catch_scopes: Vec::new(),
243 loop_scopes: Vec::new(),
244 is_in_loop_condition: false,
245 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
246 type_def_lifetime_params: Default::default(),
247 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
248 item_local_id_counters: Default::default(),
249 node_id_to_hir_id: IndexVec::new(),
251 is_in_trait_impl: false,
252 lifetimes_to_define: Vec::new(),
253 is_collecting_in_band_lifetimes: false,
254 in_scope_lifetimes: Vec::new(),
258 #[derive(Copy, Clone, PartialEq)]
260 /// Any path in a type context.
262 /// The `module::Type` in `module::Type::method` in an expression.
267 struct LoweredNodeId {
272 enum ParenthesizedGenericArgs {
278 /// What to do when we encounter an **anonymous** lifetime
279 /// reference. Anonymous lifetime references come in two flavors. You
280 /// have implicit, or fully elided, references to lifetimes, like the
281 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
282 /// or `Ref<'_, T>`. These often behave the same, but not always:
284 /// - certain usages of implicit references are deprecated, like
285 /// `Ref<T>`, and we sometimes just give hard errors in those cases
287 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
288 /// the same as `Box<dyn Foo + '_>`.
290 /// We describe the effects of the various modes in terms of three cases:
292 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
293 /// of a `&` (e.g., the missing lifetime in something like `&T`)
294 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
295 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
296 /// elided bounds follow special rules. Note that this only covers
297 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
298 /// '_>` is a case of "modern" elision.
299 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
300 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
301 /// non-deprecated equivalent.
303 /// Currently, the handling of lifetime elision is somewhat spread out
304 /// between HIR lowering and -- as described below -- the
305 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
306 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
307 /// everything into HIR lowering.
308 #[derive(Copy, Clone)]
309 enum AnonymousLifetimeMode {
310 /// For **Modern** cases, create a new anonymous region parameter
311 /// and reference that.
313 /// For **Dyn Bound** cases, pass responsibility to
314 /// `resolve_lifetime` code.
316 /// For **Deprecated** cases, report an error.
319 /// Give a hard error when either `&` or `'_` is written. Used to
320 /// rule out things like `where T: Foo<'_>`. Does not imply an
321 /// error on default object bounds (e.g., `Box<dyn Foo>`).
324 /// Pass responsibility to `resolve_lifetime` code for all cases.
328 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[hir::ItemId; 1]> }
330 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
331 fn visit_ty(&mut self, ty: &'a Ty) {
337 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
340 visit::walk_ty(self, ty);
343 fn visit_path_segment(
346 path_segment: &'v PathSegment,
348 if let Some(ref p) = path_segment.args {
349 if let GenericArgs::Parenthesized(_) = **p {
353 visit::walk_path_segment(self, path_span, path_segment)
357 impl<'a> LoweringContext<'a> {
358 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
359 /// Full-crate AST visitor that inserts into a fresh
360 /// `LoweringContext` any information that may be
361 /// needed from arbitrary locations in the crate.
362 /// E.g. The number of lifetime generic parameters
363 /// declared for every type and trait definition.
364 struct MiscCollector<'lcx, 'interner: 'lcx> {
365 lctx: &'lcx mut LoweringContext<'interner>,
368 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
369 fn visit_item(&mut self, item: &'lcx Item) {
370 self.lctx.allocate_hir_id_counter(item.id, item);
373 ItemKind::Struct(_, ref generics)
374 | ItemKind::Union(_, ref generics)
375 | ItemKind::Enum(_, ref generics)
376 | ItemKind::Ty(_, ref generics)
377 | ItemKind::Existential(_, ref generics)
378 | ItemKind::Trait(_, _, ref generics, ..) => {
379 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
383 .filter(|param| match param.kind {
384 ast::GenericParamKind::Lifetime { .. } => true,
388 self.lctx.type_def_lifetime_params.insert(def_id, count);
392 visit::walk_item(self, item);
395 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
396 self.lctx.allocate_hir_id_counter(item.id, item);
397 visit::walk_trait_item(self, item);
400 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
401 self.lctx.allocate_hir_id_counter(item.id, item);
402 visit::walk_impl_item(self, item);
406 struct ItemLowerer<'lcx, 'interner: 'lcx> {
407 lctx: &'lcx mut LoweringContext<'interner>,
410 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
411 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
413 F: FnOnce(&mut Self),
415 let old = self.lctx.is_in_trait_impl;
416 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
422 self.lctx.is_in_trait_impl = old;
426 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
427 fn visit_item(&mut self, item: &'lcx Item) {
428 let mut item_lowered = true;
429 self.lctx.with_hir_id_owner(item.id, |lctx| {
430 if let Some(hir_item) = lctx.lower_item(item) {
431 lctx.items.insert(item.id, hir_item);
433 item_lowered = false;
438 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
439 hir::ItemKind::Impl(_, _, _, ref generics, ..)
440 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
441 generics.params.clone()
446 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
447 let this = &mut ItemLowerer { lctx: this };
448 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 /// This method allocates a new HirId for the given NodeId and stores it in
577 /// the LoweringContext's NodeId => HirId map.
578 /// Take care not to call this method if the resulting HirId is then not
579 /// actually used in the HIR, as that would trigger an assertion in the
580 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
581 /// properly. Calling the method twice with the same NodeId is fine though.
582 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
583 self.lower_node_id_generic(ast_node_id, |this| {
584 let &mut (def_index, ref mut local_id_counter) =
585 this.current_hir_id_owner.last_mut().unwrap();
586 let local_id = *local_id_counter;
587 *local_id_counter += 1;
590 local_id: hir::ItemLocalId::from_u32(local_id),
595 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
596 self.lower_node_id_generic(ast_node_id, |this| {
597 let local_id_counter = this
598 .item_local_id_counters
600 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
601 let local_id = *local_id_counter;
603 // We want to be sure not to modify the counter in the map while it
604 // is also on the stack. Otherwise we'll get lost updates when writing
605 // back from the stack to the map.
606 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
608 *local_id_counter += 1;
612 .opt_def_index(owner)
613 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
614 that do not belong to the current owner");
618 local_id: hir::ItemLocalId::from_u32(local_id),
623 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
624 let body = hir::Body {
625 arguments: decl.map_or(hir_vec![], |decl| {
626 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
628 is_generator: self.is_generator,
632 self.bodies.insert(id, body);
636 fn next_id(&mut self) -> LoweredNodeId {
637 self.lower_node_id(self.sess.next_node_id())
640 fn expect_full_def(&mut self, id: NodeId) -> Def {
641 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
642 if pr.unresolved_segments() != 0 {
643 bug!("path not fully resolved: {:?}", pr);
649 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Def> {
650 self.resolver.get_import(id).present_items().map(|pr| {
651 if pr.unresolved_segments() != 0 {
652 bug!("path not fully resolved: {:?}", pr);
658 fn diagnostic(&self) -> &errors::Handler {
659 self.sess.diagnostic()
662 fn str_to_ident(&self, s: &'static str) -> Ident {
663 Ident::with_empty_ctxt(Symbol::gensym(s))
666 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
667 let mark = Mark::fresh(Mark::root());
668 mark.set_expn_info(source_map::ExpnInfo {
670 def_site: Some(span),
671 format: source_map::CompilerDesugaring(reason),
672 allow_internal_unstable: true,
673 allow_internal_unsafe: false,
674 local_inner_macros: false,
675 edition: source_map::hygiene::default_edition(),
677 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
680 fn with_anonymous_lifetime_mode<R>(
682 anonymous_lifetime_mode: AnonymousLifetimeMode,
683 op: impl FnOnce(&mut Self) -> R,
685 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
686 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
687 let result = op(self);
688 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
692 /// Creates a new hir::GenericParam for every new lifetime and
693 /// type parameter encountered while evaluating `f`. Definitions
694 /// are created with the parent provided. If no `parent_id` is
695 /// provided, no definitions will be returned.
697 /// Presuming that in-band lifetimes are enabled, then
698 /// `self.anonymous_lifetime_mode` will be updated to match the
699 /// argument while `f` is running (and restored afterwards).
700 fn collect_in_band_defs<T, F>(
703 anonymous_lifetime_mode: AnonymousLifetimeMode,
705 ) -> (Vec<hir::GenericParam>, T)
707 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
709 assert!(!self.is_collecting_in_band_lifetimes);
710 assert!(self.lifetimes_to_define.is_empty());
711 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
713 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
714 self.is_collecting_in_band_lifetimes = true;
716 let (in_band_ty_params, res) = f(self);
718 self.is_collecting_in_band_lifetimes = false;
719 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
721 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
723 let params = lifetimes_to_define
725 .map(|(span, hir_name)| {
726 let def_node_id = self.next_id().node_id;
728 // Get the name we'll use to make the def-path. Note
729 // that collisions are ok here and this shouldn't
730 // really show up for end-user.
731 let (str_name, kind) = match hir_name {
732 ParamName::Plain(ident) => (
733 ident.as_interned_str(),
734 hir::LifetimeParamKind::InBand,
736 ParamName::Fresh(_) => (
737 keywords::UnderscoreLifetime.name().as_interned_str(),
738 hir::LifetimeParamKind::Elided,
740 ParamName::Error => (
741 keywords::UnderscoreLifetime.name().as_interned_str(),
742 hir::LifetimeParamKind::Error,
746 // Add a definition for the in-band lifetime def
747 self.resolver.definitions().create_def_with_parent(
750 DefPathData::LifetimeParam(str_name),
751 DefIndexAddressSpace::High,
762 pure_wrt_drop: false,
763 kind: hir::GenericParamKind::Lifetime { kind }
766 .chain(in_band_ty_params.into_iter())
772 /// When there is a reference to some lifetime `'a`, and in-band
773 /// lifetimes are enabled, then we want to push that lifetime into
774 /// the vector of names to define later. In that case, it will get
775 /// added to the appropriate generics.
776 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
777 if !self.is_collecting_in_band_lifetimes {
781 if !self.sess.features_untracked().in_band_lifetimes {
785 if self.in_scope_lifetimes.contains(&ident.modern()) {
789 let hir_name = ParamName::Plain(ident);
791 if self.lifetimes_to_define.iter()
792 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
796 self.lifetimes_to_define.push((ident.span, hir_name));
799 /// When we have either an elided or `'_` lifetime in an impl
800 /// header, we convert it to an in-band lifetime.
801 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
802 assert!(self.is_collecting_in_band_lifetimes);
803 let index = self.lifetimes_to_define.len();
804 let hir_name = ParamName::Fresh(index);
805 self.lifetimes_to_define.push((span, hir_name));
809 // Evaluates `f` with the lifetimes in `params` in-scope.
810 // This is used to track which lifetimes have already been defined, and
811 // which are new in-band lifetimes that need to have a definition created
813 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
815 F: FnOnce(&mut LoweringContext<'_>) -> T,
817 let old_len = self.in_scope_lifetimes.len();
818 let lt_def_names = params.iter().filter_map(|param| match param.kind {
819 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
822 self.in_scope_lifetimes.extend(lt_def_names);
826 self.in_scope_lifetimes.truncate(old_len);
830 // Same as the method above, but accepts `hir::GenericParam`s
831 // instead of `ast::GenericParam`s.
832 // This should only be used with generics that have already had their
833 // in-band lifetimes added. In practice, this means that this function is
834 // only used when lowering a child item of a trait or impl.
835 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
836 params: &HirVec<hir::GenericParam>,
839 F: FnOnce(&mut LoweringContext<'_>) -> T,
841 let old_len = self.in_scope_lifetimes.len();
842 let lt_def_names = params.iter().filter_map(|param| match param.kind {
843 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
846 self.in_scope_lifetimes.extend(lt_def_names);
850 self.in_scope_lifetimes.truncate(old_len);
854 /// Appends in-band lifetime defs and argument-position `impl
855 /// Trait` defs to the existing set of generics.
857 /// Presuming that in-band lifetimes are enabled, then
858 /// `self.anonymous_lifetime_mode` will be updated to match the
859 /// argument while `f` is running (and restored afterwards).
860 fn add_in_band_defs<F, T>(
864 anonymous_lifetime_mode: AnonymousLifetimeMode,
866 ) -> (hir::Generics, T)
868 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
870 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
873 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
874 let mut params = Vec::new();
875 let generics = this.lower_generics(
877 ImplTraitContext::Universal(&mut params),
879 let res = f(this, &mut params);
880 (params, (generics, res))
885 lowered_generics.params = lowered_generics
892 (lowered_generics, res)
895 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
897 F: FnOnce(&mut LoweringContext<'_>) -> T,
899 let len = self.catch_scopes.len();
900 self.catch_scopes.push(catch_id);
902 let result = f(self);
905 self.catch_scopes.len(),
906 "catch scopes should be added and removed in stack order"
909 self.catch_scopes.pop().unwrap();
916 capture_clause: CaptureBy,
917 closure_node_id: NodeId,
919 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
921 let prev_is_generator = mem::replace(&mut self.is_generator, true);
922 let body_expr = body(self);
923 let span = body_expr.span;
924 let output = match ret_ty {
925 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
926 None => FunctionRetTy::Default(span),
933 let body_id = self.record_body(body_expr, Some(&decl));
934 self.is_generator = prev_is_generator;
936 let capture_clause = self.lower_capture_clause(capture_clause);
937 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
938 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
939 let generator = hir::Expr {
941 hir_id: closure_hir_id,
942 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
943 Some(hir::GeneratorMovability::Static)),
945 attrs: ThinVec::new(),
948 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
949 let gen_future = self.expr_std_path(
950 unstable_span, &["future", "from_generator"], None, ThinVec::new());
951 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
954 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
956 F: FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
958 let prev = mem::replace(&mut self.is_generator, false);
959 let result = f(self);
960 let r = self.record_body(result, decl);
961 self.is_generator = prev;
965 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
967 F: FnOnce(&mut LoweringContext<'_>) -> T,
969 // We're no longer in the base loop's condition; we're in another loop.
970 let was_in_loop_condition = self.is_in_loop_condition;
971 self.is_in_loop_condition = false;
973 let len = self.loop_scopes.len();
974 self.loop_scopes.push(loop_id);
976 let result = f(self);
979 self.loop_scopes.len(),
980 "Loop scopes should be added and removed in stack order"
983 self.loop_scopes.pop().unwrap();
985 self.is_in_loop_condition = was_in_loop_condition;
990 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
992 F: FnOnce(&mut LoweringContext<'_>) -> T,
994 let was_in_loop_condition = self.is_in_loop_condition;
995 self.is_in_loop_condition = true;
997 let result = f(self);
999 self.is_in_loop_condition = was_in_loop_condition;
1004 fn with_new_scopes<T, F>(&mut self, f: F) -> T
1006 F: FnOnce(&mut LoweringContext<'_>) -> T,
1008 let was_in_loop_condition = self.is_in_loop_condition;
1009 self.is_in_loop_condition = false;
1011 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
1012 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
1014 self.catch_scopes = catch_scopes;
1015 self.loop_scopes = loop_scopes;
1017 self.is_in_loop_condition = was_in_loop_condition;
1022 fn def_key(&mut self, id: DefId) -> DefKey {
1024 self.resolver.definitions().def_key(id.index)
1026 self.cstore.def_key(id)
1030 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1031 label.map(|label| hir::Label {
1036 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1037 let target_id = match destination {
1039 if let Def::Label(loop_id) = self.expect_full_def(id) {
1040 Ok(self.lower_node_id(loop_id).node_id)
1042 Err(hir::LoopIdError::UnresolvedLabel)
1049 .map(|id| Ok(self.lower_node_id(id).node_id))
1050 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1055 label: self.lower_label(destination.map(|(_, label)| label)),
1060 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1063 .map(|a| self.lower_attr(a))
1067 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1068 // Note that we explicitly do not walk the path. Since we don't really
1069 // lower attributes (we use the AST version) there is nowhere to keep
1070 // the HirIds. We don't actually need HIR version of attributes anyway.
1074 path: attr.path.clone(),
1075 tokens: self.lower_token_stream(attr.tokens.clone()),
1076 is_sugared_doc: attr.is_sugared_doc,
1081 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1084 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1088 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1090 TokenTree::Token(span, token) => self.lower_token(token, span),
1091 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1094 delim: delimited.delim,
1095 tts: self.lower_token_stream(delimited.tts.into()).into(),
1101 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1103 Token::Interpolated(_) => {}
1104 other => return TokenTree::Token(span, other).into(),
1107 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1108 self.lower_token_stream(tts)
1111 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1113 attrs: self.lower_attrs(&arm.attrs),
1114 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1115 guard: match arm.guard {
1116 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1119 body: P(self.lower_expr(&arm.body)),
1123 fn lower_ty_binding(&mut self, b: &TypeBinding,
1124 itctx: ImplTraitContext<'_>) -> hir::TypeBinding {
1126 id: self.lower_node_id(b.id).node_id,
1128 ty: self.lower_ty(&b.ty, itctx),
1133 fn lower_generic_arg(&mut self,
1134 arg: &ast::GenericArg,
1135 itctx: ImplTraitContext<'_>)
1136 -> hir::GenericArg {
1138 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1139 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1143 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1144 P(self.lower_ty_direct(t, itctx))
1147 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1148 let kind = match t.node {
1149 TyKind::Infer => hir::TyKind::Infer,
1150 TyKind::Err => hir::TyKind::Err,
1151 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1152 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1153 TyKind::Rptr(ref region, ref mt) => {
1154 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1155 let lifetime = match *region {
1156 Some(ref lt) => self.lower_lifetime(lt),
1157 None => self.elided_ref_lifetime(span),
1159 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1161 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1164 this.with_anonymous_lifetime_mode(
1165 AnonymousLifetimeMode::PassThrough,
1167 hir::TyKind::BareFn(P(hir::BareFnTy {
1168 generic_params: this.lower_generic_params(
1170 &NodeMap::default(),
1171 ImplTraitContext::disallowed(),
1173 unsafety: this.lower_unsafety(f.unsafety),
1175 decl: this.lower_fn_decl(&f.decl, None, false, None),
1176 arg_names: this.lower_fn_args_to_names(&f.decl),
1182 TyKind::Never => hir::TyKind::Never,
1183 TyKind::Tup(ref tys) => {
1184 hir::TyKind::Tup(tys.iter().map(|ty| {
1185 self.lower_ty_direct(ty, itctx.reborrow())
1188 TyKind::Paren(ref ty) => {
1189 return self.lower_ty_direct(ty, itctx);
1191 TyKind::Path(ref qself, ref path) => {
1192 let id = self.lower_node_id(t.id);
1193 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1194 let ty = self.ty_path(id, t.span, qpath);
1195 if let hir::TyKind::TraitObject(..) = ty.node {
1196 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1200 TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1203 def: self.expect_full_def(t.id),
1204 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1208 TyKind::Array(ref ty, ref length) => {
1209 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1211 TyKind::Typeof(ref expr) => {
1212 hir::TyKind::Typeof(self.lower_anon_const(expr))
1214 TyKind::TraitObject(ref bounds, kind) => {
1215 let mut lifetime_bound = None;
1218 .filter_map(|bound| match *bound {
1219 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1220 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1222 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1223 GenericBound::Outlives(ref lifetime) => {
1224 if lifetime_bound.is_none() {
1225 lifetime_bound = Some(self.lower_lifetime(lifetime));
1231 let lifetime_bound =
1232 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1233 if kind != TraitObjectSyntax::Dyn {
1234 self.maybe_lint_bare_trait(t.span, t.id, false);
1236 hir::TyKind::TraitObject(bounds, lifetime_bound)
1238 TyKind::ImplTrait(def_node_id, ref bounds) => {
1241 ImplTraitContext::Existential(fn_def_id) => {
1242 self.lower_existential_impl_trait(
1243 span, fn_def_id, def_node_id,
1244 |this| this.lower_param_bounds(bounds, itctx),
1247 ImplTraitContext::Universal(in_band_ty_params) => {
1248 self.lower_node_id(def_node_id);
1249 // Add a definition for the in-band Param
1250 let def_index = self
1253 .opt_def_index(def_node_id)
1256 let hir_bounds = self.lower_param_bounds(
1258 ImplTraitContext::Universal(in_band_ty_params),
1260 // Set the name to `impl Bound1 + Bound2`
1261 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1262 in_band_ty_params.push(hir::GenericParam {
1264 name: ParamName::Plain(ident),
1265 pure_wrt_drop: false,
1269 kind: hir::GenericParamKind::Type {
1271 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1275 hir::TyKind::Path(hir::QPath::Resolved(
1279 def: Def::TyParam(DefId::local(def_index)),
1280 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1284 ImplTraitContext::Disallowed(pos) => {
1285 let allowed_in = if self.sess.features_untracked()
1286 .impl_trait_in_bindings {
1287 "bindings or function and inherent method return types"
1289 "function and inherent method return types"
1291 let mut err = struct_span_err!(
1295 "`impl Trait` not allowed outside of {}",
1298 if pos == ImplTraitPosition::Binding &&
1299 nightly_options::is_nightly_build() {
1301 "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1309 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1312 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1321 fn lower_existential_impl_trait(
1324 fn_def_id: Option<DefId>,
1325 exist_ty_node_id: NodeId,
1326 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1328 // Make sure we know that some funky desugaring has been going on here.
1329 // This is a first: there is code in other places like for loop
1330 // desugaring that explicitly states that we don't want to track that.
1331 // Not tracking it makes lints in rustc and clippy very fragile as
1332 // frequently opened issues show.
1333 let exist_ty_span = self.allow_internal_unstable(
1334 CompilerDesugaringKind::ExistentialReturnType,
1338 let exist_ty_def_index = self
1341 .opt_def_index(exist_ty_node_id)
1344 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1346 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1348 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1354 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1355 let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1356 generics: hir::Generics {
1357 params: lifetime_defs,
1358 where_clause: hir::WhereClause {
1359 id: lctx.next_id().node_id,
1360 predicates: Vec::new().into(),
1365 impl_trait_fn: fn_def_id,
1367 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1368 // Generate an `existential type Foo: Trait;` declaration
1369 trace!("creating existential type with id {:#?}", exist_ty_id);
1371 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1372 let exist_ty_item = hir::Item {
1373 id: exist_ty_id.node_id,
1374 hir_id: exist_ty_id.hir_id,
1375 name: keywords::Invalid.name(),
1376 attrs: Default::default(),
1377 node: exist_ty_item_kind,
1378 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1379 span: exist_ty_span,
1382 // Insert the item into the global list. This usually happens
1383 // automatically for all AST items. But this existential type item
1384 // does not actually exist in the AST.
1385 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1387 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1388 hir::TyKind::Def(hir::ItemId { id: exist_ty_id.node_id }, lifetimes)
1392 fn lifetimes_from_impl_trait_bounds(
1394 exist_ty_id: NodeId,
1395 parent_index: DefIndex,
1396 bounds: &hir::GenericBounds,
1397 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1398 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1399 // appear in the bounds, excluding lifetimes that are created within the bounds.
1400 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1401 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1402 context: &'r mut LoweringContext<'a>,
1404 exist_ty_id: NodeId,
1405 collect_elided_lifetimes: bool,
1406 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1407 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1408 output_lifetimes: Vec<hir::GenericArg>,
1409 output_lifetime_params: Vec<hir::GenericParam>,
1412 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1413 fn nested_visit_map<'this>(
1415 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1416 hir::intravisit::NestedVisitorMap::None
1419 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1420 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1421 if parameters.parenthesized {
1422 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1423 self.collect_elided_lifetimes = false;
1424 hir::intravisit::walk_generic_args(self, span, parameters);
1425 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1427 hir::intravisit::walk_generic_args(self, span, parameters);
1431 fn visit_ty(&mut self, t: &'v hir::Ty) {
1432 // Don't collect elided lifetimes used inside of `fn()` syntax
1433 if let hir::TyKind::BareFn(_) = t.node {
1434 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1435 self.collect_elided_lifetimes = false;
1437 // Record the "stack height" of `for<'a>` lifetime bindings
1438 // to be able to later fully undo their introduction.
1439 let old_len = self.currently_bound_lifetimes.len();
1440 hir::intravisit::walk_ty(self, t);
1441 self.currently_bound_lifetimes.truncate(old_len);
1443 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1445 hir::intravisit::walk_ty(self, t)
1449 fn visit_poly_trait_ref(
1451 trait_ref: &'v hir::PolyTraitRef,
1452 modifier: hir::TraitBoundModifier,
1454 // Record the "stack height" of `for<'a>` lifetime bindings
1455 // to be able to later fully undo their introduction.
1456 let old_len = self.currently_bound_lifetimes.len();
1457 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1458 self.currently_bound_lifetimes.truncate(old_len);
1461 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1462 // Record the introduction of 'a in `for<'a> ...`
1463 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1464 // Introduce lifetimes one at a time so that we can handle
1465 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1466 let lt_name = hir::LifetimeName::Param(param.name);
1467 self.currently_bound_lifetimes.push(lt_name);
1470 hir::intravisit::walk_generic_param(self, param);
1473 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1474 let name = match lifetime.name {
1475 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1476 if self.collect_elided_lifetimes {
1477 // Use `'_` for both implicit and underscore lifetimes in
1478 // `abstract type Foo<'_>: SomeTrait<'_>;`
1479 hir::LifetimeName::Underscore
1484 hir::LifetimeName::Param(_) => lifetime.name,
1485 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1488 if !self.currently_bound_lifetimes.contains(&name)
1489 && !self.already_defined_lifetimes.contains(&name) {
1490 self.already_defined_lifetimes.insert(name);
1492 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1493 id: self.context.next_id().node_id,
1494 span: lifetime.span,
1498 // We need to manually create the ids here, because the
1499 // definitions will go into the explicit `existential type`
1500 // declaration and thus need to have their owner set to that item
1501 let def_node_id = self.context.sess.next_node_id();
1502 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1503 self.context.resolver.definitions().create_def_with_parent(
1506 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1507 DefIndexAddressSpace::High,
1512 let (name, kind) = match name {
1513 hir::LifetimeName::Underscore => (
1514 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident()),
1515 hir::LifetimeParamKind::Elided,
1517 hir::LifetimeName::Param(param_name) => (
1519 hir::LifetimeParamKind::Explicit,
1521 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1524 self.output_lifetime_params.push(hir::GenericParam {
1527 span: lifetime.span,
1528 pure_wrt_drop: false,
1531 kind: hir::GenericParamKind::Lifetime { kind }
1537 let mut lifetime_collector = ImplTraitLifetimeCollector {
1539 parent: parent_index,
1541 collect_elided_lifetimes: true,
1542 currently_bound_lifetimes: Vec::new(),
1543 already_defined_lifetimes: FxHashSet::default(),
1544 output_lifetimes: Vec::new(),
1545 output_lifetime_params: Vec::new(),
1548 for bound in bounds {
1549 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1553 lifetime_collector.output_lifetimes.into(),
1554 lifetime_collector.output_lifetime_params.into(),
1558 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1563 .map(|x| self.lower_foreign_item(x))
1568 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1575 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1577 node: hir::VariantKind {
1578 name: v.node.ident.name,
1579 attrs: self.lower_attrs(&v.node.attrs),
1580 data: self.lower_variant_data(&v.node.data),
1581 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1590 qself: &Option<QSelf>,
1592 param_mode: ParamMode,
1593 mut itctx: ImplTraitContext<'_>,
1595 let qself_position = qself.as_ref().map(|q| q.position);
1596 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1598 let resolution = self.resolver
1600 .unwrap_or_else(|| PathResolution::new(Def::Err));
1602 let proj_start = p.segments.len() - resolution.unresolved_segments();
1603 let path = P(hir::Path {
1604 def: resolution.base_def(),
1605 segments: p.segments[..proj_start]
1608 .map(|(i, segment)| {
1609 let param_mode = match (qself_position, param_mode) {
1610 (Some(j), ParamMode::Optional) if i < j => {
1611 // This segment is part of the trait path in a
1612 // qualified path - one of `a`, `b` or `Trait`
1613 // in `<X as a::b::Trait>::T::U::method`.
1619 // Figure out if this is a type/trait segment,
1620 // which may need lifetime elision performed.
1621 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1622 krate: def_id.krate,
1623 index: this.def_key(def_id).parent.expect("missing parent"),
1625 let type_def_id = match resolution.base_def() {
1626 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1627 Some(parent_def_id(self, def_id))
1629 Def::Variant(def_id) if i + 1 == proj_start => {
1630 Some(parent_def_id(self, def_id))
1633 | Def::Union(def_id)
1635 | Def::TyAlias(def_id)
1636 | Def::Trait(def_id) if i + 1 == proj_start =>
1642 let parenthesized_generic_args = match resolution.base_def() {
1643 // `a::b::Trait(Args)`
1644 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1645 // `a::b::Trait(Args)::TraitItem`
1646 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1647 if i + 2 == proj_start =>
1649 ParenthesizedGenericArgs::Ok
1651 // Avoid duplicated errors
1652 Def::Err => ParenthesizedGenericArgs::Ok,
1658 | Def::Variant(..) if i + 1 == proj_start =>
1660 ParenthesizedGenericArgs::Err
1662 // A warning for now, for compatibility reasons
1663 _ => ParenthesizedGenericArgs::Warn,
1666 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1667 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1670 assert!(!def_id.is_local());
1672 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1673 let n = item_generics.own_counts().lifetimes;
1674 self.type_def_lifetime_params.insert(def_id, n);
1677 self.lower_path_segment(
1682 parenthesized_generic_args,
1691 // Simple case, either no projections, or only fully-qualified.
1692 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1693 if resolution.unresolved_segments() == 0 {
1694 return hir::QPath::Resolved(qself, path);
1697 // Create the innermost type that we're projecting from.
1698 let mut ty = if path.segments.is_empty() {
1699 // If the base path is empty that means there exists a
1700 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1701 qself.expect("missing QSelf for <T>::...")
1703 // Otherwise, the base path is an implicit `Self` type path,
1704 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1705 // `<I as Iterator>::Item::default`.
1706 let new_id = self.next_id();
1707 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1710 // Anything after the base path are associated "extensions",
1711 // out of which all but the last one are associated types,
1712 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1713 // * base path is `std::vec::Vec<T>`
1714 // * "extensions" are `IntoIter`, `Item` and `clone`
1715 // * type nodes are:
1716 // 1. `std::vec::Vec<T>` (created above)
1717 // 2. `<std::vec::Vec<T>>::IntoIter`
1718 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1719 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1720 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1721 let segment = P(self.lower_path_segment(
1726 ParenthesizedGenericArgs::Warn,
1730 let qpath = hir::QPath::TypeRelative(ty, segment);
1732 // It's finished, return the extension of the right node type.
1733 if i == p.segments.len() - 1 {
1737 // Wrap the associated extension in another type node.
1738 let new_id = self.next_id();
1739 ty = P(self.ty_path(new_id, p.span, qpath));
1742 // Should've returned in the for loop above.
1745 "lower_qpath: no final extension segment in {}..{}",
1751 fn lower_path_extra(
1755 param_mode: ParamMode,
1756 explicit_owner: Option<NodeId>,
1760 segments: p.segments
1763 self.lower_path_segment(
1768 ParenthesizedGenericArgs::Err,
1769 ImplTraitContext::disallowed(),
1778 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1779 let def = self.expect_full_def(id);
1780 self.lower_path_extra(def, p, param_mode, None)
1783 fn lower_path_segment(
1786 segment: &PathSegment,
1787 param_mode: ParamMode,
1788 expected_lifetimes: usize,
1789 parenthesized_generic_args: ParenthesizedGenericArgs,
1790 itctx: ImplTraitContext<'_>,
1791 explicit_owner: Option<NodeId>,
1792 ) -> hir::PathSegment {
1793 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1794 let msg = "parenthesized parameters may only be used with a trait";
1795 match **generic_args {
1796 GenericArgs::AngleBracketed(ref data) => {
1797 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1799 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1800 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1801 ParenthesizedGenericArgs::Warn => {
1802 self.sess.buffer_lint(
1803 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1808 (hir::GenericArgs::none(), true)
1810 ParenthesizedGenericArgs::Err => {
1811 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1812 .span_label(data.span, "only traits may use parentheses")
1814 (hir::GenericArgs::none(), true)
1819 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1822 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1823 GenericArg::Lifetime(_) => true,
1826 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1827 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1828 if !generic_args.parenthesized && !has_lifetimes {
1830 self.elided_path_lifetimes(path_span, expected_lifetimes)
1832 .map(|lt| GenericArg::Lifetime(lt))
1833 .chain(generic_args.args.into_iter())
1835 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1836 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1837 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1838 let no_bindings = generic_args.bindings.is_empty();
1839 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1840 // If there are no (non-implicit) generic args or associated-type
1841 // bindings, our suggestion includes the angle brackets
1842 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1844 // Otherwise—sorry, this is kind of gross—we need to infer the
1845 // place to splice in the `'_, ` from the generics that do exist
1846 let first_generic_span = first_generic_span
1847 .expect("already checked that type args or bindings exist");
1848 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1850 self.sess.buffer_lint_with_diagnostic(
1851 ELIDED_LIFETIMES_IN_PATHS,
1854 "hidden lifetime parameters in types are deprecated",
1855 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1856 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1862 let def = self.expect_full_def(segment.id);
1863 let id = if let Some(owner) = explicit_owner {
1864 self.lower_node_id_with_owner(segment.id, owner)
1866 self.lower_node_id(segment.id)
1869 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
1870 segment.ident, segment.id, id,
1873 hir::PathSegment::new(
1882 fn lower_angle_bracketed_parameter_data(
1884 data: &AngleBracketedArgs,
1885 param_mode: ParamMode,
1886 mut itctx: ImplTraitContext<'_>,
1887 ) -> (hir::GenericArgs, bool) {
1888 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1889 let has_types = args.iter().any(|arg| match arg {
1890 ast::GenericArg::Type(_) => true,
1894 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1895 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1896 parenthesized: false,
1898 !has_types && param_mode == ParamMode::Optional)
1901 fn lower_parenthesized_parameter_data(
1903 data: &ParenthesisedArgs,
1904 ) -> (hir::GenericArgs, bool) {
1905 // Switch to `PassThrough` mode for anonymous lifetimes: this
1906 // means that we permit things like `&Ref<T>`, where `Ref` has
1907 // a hidden lifetime parameter. This is needed for backwards
1908 // compatibility, even in contexts like an impl header where
1909 // we generally don't permit such things (see #51008).
1910 self.with_anonymous_lifetime_mode(
1911 AnonymousLifetimeMode::PassThrough,
1913 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1916 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
1918 let mk_tup = |this: &mut Self, tys, span| {
1919 let LoweredNodeId { node_id, hir_id } = this.next_id();
1920 hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1925 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1928 id: this.next_id().node_id,
1929 ident: Ident::from_str(FN_OUTPUT_NAME),
1932 .map(|ty| this.lower_ty(&ty, ImplTraitContext::disallowed()))
1933 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1934 span: output.as_ref().map_or(span, |ty| ty.span),
1937 parenthesized: true,
1945 fn lower_local(&mut self, l: &Local) -> (P<hir::Local>, SmallVec<[hir::ItemId; 1]>) {
1946 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1947 let mut ids = SmallVec::<[hir::ItemId; 1]>::new();
1948 if self.sess.features_untracked().impl_trait_in_bindings {
1949 if let Some(ref ty) = l.ty {
1950 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
1951 visitor.visit_ty(ty);
1954 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
1960 .map(|t| self.lower_ty(t,
1961 if self.sess.features_untracked().impl_trait_in_bindings {
1962 ImplTraitContext::Existential(Some(parent_def_id))
1964 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
1967 pat: self.lower_pat(&l.pat),
1968 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1970 attrs: l.attrs.clone(),
1971 source: hir::LocalSource::Normal,
1975 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1977 Mutability::Mutable => hir::MutMutable,
1978 Mutability::Immutable => hir::MutImmutable,
1982 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1983 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1987 pat: self.lower_pat(&arg.pat),
1991 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1994 .map(|arg| match arg.pat.node {
1995 PatKind::Ident(_, ident, _) => ident,
1996 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
2001 // Lowers a function declaration.
2003 // decl: the unlowered (ast) function declaration.
2004 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
2005 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2006 // make_ret_async is also `Some`.
2007 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
2008 // This guards against trait declarations and implementations where impl Trait is
2010 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2011 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
2012 // return type impl Trait item.
2016 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2017 impl_trait_return_allow: bool,
2018 make_ret_async: Option<NodeId>,
2019 ) -> P<hir::FnDecl> {
2020 let inputs = decl.inputs
2023 if let Some((_, ref mut ibty)) = in_band_ty_params {
2024 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2026 self.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2029 .collect::<HirVec<_>>();
2031 let output = if let Some(ret_id) = make_ret_async {
2032 self.lower_async_fn_ret_ty(
2035 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
2040 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2041 Some((def_id, _)) if impl_trait_return_allow => {
2042 hir::Return(self.lower_ty(ty,
2043 ImplTraitContext::Existential(Some(def_id))))
2046 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2049 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2056 variadic: decl.variadic,
2057 implicit_self: decl.inputs.get(0).map_or(
2058 hir::ImplicitSelfKind::None,
2060 let is_mutable_pat = match arg.pat.node {
2061 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2062 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2063 mt == Mutability::Mutable,
2068 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2069 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2070 // Given we are only considering `ImplicitSelf` types, we needn't consider
2071 // the case where we have a mutable pattern to a reference as that would
2072 // no longer be an `ImplicitSelf`.
2073 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2074 mt.mutbl == ast::Mutability::Mutable =>
2075 hir::ImplicitSelfKind::MutRef,
2076 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2077 hir::ImplicitSelfKind::ImmRef,
2078 _ => hir::ImplicitSelfKind::None,
2085 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
2087 // fn_span: the span of the async function declaration. Used for error reporting.
2088 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
2089 // output: unlowered output type (`T` in `-> T`)
2090 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
2091 fn lower_async_fn_ret_ty(
2094 output: &FunctionRetTy,
2096 return_impl_trait_id: NodeId,
2097 ) -> hir::FunctionRetTy {
2098 // Get lifetimes used in the input arguments to the function. Our output type must also
2099 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
2100 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
2101 // is a subset of the other. We really want some new lifetime that is a subset of all input
2102 // lifetimes, but that doesn't exist at the moment.
2104 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
2105 context: &'r mut LoweringContext<'a>,
2106 // Lifetimes bound by HRTB
2107 currently_bound_lifetimes: Vec<hir::LifetimeName>,
2108 // Whether to count elided lifetimes.
2109 // Disabled inside of `Fn` or `fn` syntax.
2110 collect_elided_lifetimes: bool,
2111 // The lifetime found.
2112 // Multiple different or elided lifetimes cannot appear in async fn for now.
2113 output_lifetime: Option<(hir::LifetimeName, Span)>,
2116 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
2117 fn nested_visit_map<'this>(
2119 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
2120 hir::intravisit::NestedVisitorMap::None
2123 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
2124 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2125 if parameters.parenthesized {
2126 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2127 self.collect_elided_lifetimes = false;
2128 hir::intravisit::walk_generic_args(self, span, parameters);
2129 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2131 hir::intravisit::walk_generic_args(self, span, parameters);
2135 fn visit_ty(&mut self, t: &'v hir::Ty) {
2136 // Don't collect elided lifetimes used inside of `fn()` syntax
2137 if let &hir::TyKind::BareFn(_) = &t.node {
2138 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2139 self.collect_elided_lifetimes = false;
2141 // Record the "stack height" of `for<'a>` lifetime bindings
2142 // to be able to later fully undo their introduction.
2143 let old_len = self.currently_bound_lifetimes.len();
2144 hir::intravisit::walk_ty(self, t);
2145 self.currently_bound_lifetimes.truncate(old_len);
2147 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2149 hir::intravisit::walk_ty(self, t);
2153 fn visit_poly_trait_ref(
2155 trait_ref: &'v hir::PolyTraitRef,
2156 modifier: hir::TraitBoundModifier,
2158 // Record the "stack height" of `for<'a>` lifetime bindings
2159 // to be able to later fully undo their introduction.
2160 let old_len = self.currently_bound_lifetimes.len();
2161 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2162 self.currently_bound_lifetimes.truncate(old_len);
2165 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2166 // Record the introduction of 'a in `for<'a> ...`
2167 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2168 // Introduce lifetimes one at a time so that we can handle
2169 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2170 let lt_name = hir::LifetimeName::Param(param.name);
2171 self.currently_bound_lifetimes.push(lt_name);
2174 hir::intravisit::walk_generic_param(self, param);
2177 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2178 let name = match lifetime.name {
2179 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2180 if self.collect_elided_lifetimes {
2181 // Use `'_` for both implicit and underscore lifetimes in
2182 // `abstract type Foo<'_>: SomeTrait<'_>;`
2183 hir::LifetimeName::Underscore
2188 hir::LifetimeName::Param(_) => lifetime.name,
2189 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
2192 if !self.currently_bound_lifetimes.contains(&name) {
2193 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2194 // We don't currently have a reliable way to desugar `async fn` with
2195 // multiple potentially unrelated input lifetimes into
2196 // `-> impl Trait + 'lt`, so we report an error in this case.
2197 if current_lt_name != name {
2200 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2202 "multiple different lifetimes used in arguments of `async fn`",
2204 .span_label(current_lt_span, "first lifetime here")
2205 .span_label(lifetime.span, "different lifetime here")
2206 .help("`async fn` can only accept borrowed values \
2207 with identical lifetimes")
2209 } else if current_lt_name.is_elided() && name.is_elided() {
2212 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2214 "multiple elided lifetimes used in arguments of `async fn`",
2216 .span_label(current_lt_span, "first lifetime here")
2217 .span_label(lifetime.span, "different lifetime here")
2218 .help("consider giving these arguments named lifetimes")
2222 self.output_lifetime = Some((name, lifetime.span));
2228 let bound_lifetime = {
2229 let mut lifetime_collector = AsyncFnLifetimeCollector {
2231 currently_bound_lifetimes: Vec::new(),
2232 collect_elided_lifetimes: true,
2233 output_lifetime: None,
2237 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2239 lifetime_collector.output_lifetime
2242 let span = match output {
2243 FunctionRetTy::Ty(ty) => ty.span,
2244 FunctionRetTy::Default(span) => *span,
2247 let impl_trait_ty = self.lower_existential_impl_trait(
2248 span, Some(fn_def_id), return_impl_trait_id, |this| {
2249 let output_ty = match output {
2250 FunctionRetTy::Ty(ty) => {
2251 this.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2253 FunctionRetTy::Default(span) => {
2254 let LoweredNodeId { node_id, hir_id } = this.next_id();
2258 node: hir::TyKind::Tup(hir_vec![]),
2265 let future_params = P(hir::GenericArgs {
2267 bindings: hir_vec![hir::TypeBinding {
2268 ident: Ident::from_str(FN_OUTPUT_NAME),
2270 id: this.next_id().node_id,
2273 parenthesized: false,
2277 this.std_path(span, &["future", "Future"], Some(future_params), false);
2279 let LoweredNodeId { node_id, hir_id } = this.next_id();
2280 let mut bounds = vec![
2281 hir::GenericBound::Trait(
2283 trait_ref: hir::TraitRef {
2288 bound_generic_params: hir_vec![],
2291 hir::TraitBoundModifier::None
2295 if let Some((name, span)) = bound_lifetime {
2296 bounds.push(hir::GenericBound::Outlives(
2297 hir::Lifetime { id: this.next_id().node_id, name, span }));
2300 hir::HirVec::from(bounds)
2303 let LoweredNodeId { node_id, hir_id } = self.next_id();
2304 let impl_trait_ty = P(hir::Ty {
2306 node: impl_trait_ty,
2311 hir::FunctionRetTy::Return(impl_trait_ty)
2314 fn lower_param_bound(
2317 itctx: ImplTraitContext<'_>,
2318 ) -> hir::GenericBound {
2320 GenericBound::Trait(ref ty, modifier) => {
2321 hir::GenericBound::Trait(
2322 self.lower_poly_trait_ref(ty, itctx),
2323 self.lower_trait_bound_modifier(modifier),
2326 GenericBound::Outlives(ref lifetime) => {
2327 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2332 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2333 let span = l.ident.span;
2335 ident if ident.name == keywords::StaticLifetime.name() =>
2336 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2337 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2338 match self.anonymous_lifetime_mode {
2339 AnonymousLifetimeMode::CreateParameter => {
2340 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2341 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2344 AnonymousLifetimeMode::PassThrough => {
2345 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2348 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2351 self.maybe_collect_in_band_lifetime(ident);
2352 let param_name = ParamName::Plain(ident);
2353 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2358 fn new_named_lifetime(
2362 name: hir::LifetimeName,
2363 ) -> hir::Lifetime {
2365 id: self.lower_node_id(id).node_id,
2371 fn lower_generic_params(
2373 params: &[GenericParam],
2374 add_bounds: &NodeMap<Vec<GenericBound>>,
2375 mut itctx: ImplTraitContext<'_>,
2376 ) -> hir::HirVec<hir::GenericParam> {
2377 params.iter().map(|param| {
2378 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2382 fn lower_generic_param(&mut self,
2383 param: &GenericParam,
2384 add_bounds: &NodeMap<Vec<GenericBound>>,
2385 mut itctx: ImplTraitContext<'_>)
2386 -> hir::GenericParam {
2387 let mut bounds = self.with_anonymous_lifetime_mode(
2388 AnonymousLifetimeMode::ReportError,
2389 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2393 GenericParamKind::Lifetime => {
2394 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2395 self.is_collecting_in_band_lifetimes = false;
2397 let lt = self.with_anonymous_lifetime_mode(
2398 AnonymousLifetimeMode::ReportError,
2399 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2401 let param_name = match lt.name {
2402 hir::LifetimeName::Param(param_name) => param_name,
2403 hir::LifetimeName::Implicit
2404 | hir::LifetimeName::Underscore
2405 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2406 hir::LifetimeName::Error => ParamName::Error,
2408 let param = hir::GenericParam {
2412 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2413 attrs: self.lower_attrs(¶m.attrs),
2415 kind: hir::GenericParamKind::Lifetime {
2416 kind: hir::LifetimeParamKind::Explicit,
2420 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2424 GenericParamKind::Type { ref default, .. } => {
2425 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2426 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2427 // Instead, use gensym("Self") to create a distinct name that looks the same.
2428 let ident = if param.ident.name == keywords::SelfType.name() {
2429 param.ident.gensym()
2434 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2435 if !add_bounds.is_empty() {
2436 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2437 bounds = bounds.into_iter()
2443 id: self.lower_node_id(param.id).node_id,
2444 name: hir::ParamName::Plain(ident),
2445 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2446 attrs: self.lower_attrs(¶m.attrs),
2449 kind: hir::GenericParamKind::Type {
2450 default: default.as_ref().map(|x| {
2451 self.lower_ty(x, ImplTraitContext::disallowed())
2453 synthetic: param.attrs.iter()
2454 .filter(|attr| attr.check_name("rustc_synthetic"))
2455 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2465 generics: &Generics,
2466 itctx: ImplTraitContext<'_>)
2469 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2470 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2471 // paths where report_error is called are also the only paths that advance to after
2472 // the match statement, so the error reporting could probably just be moved there.
2473 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
2474 for pred in &generics.where_clause.predicates {
2475 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2476 'next_bound: for bound in &bound_pred.bounds {
2477 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2478 let report_error = |this: &mut Self| {
2479 this.diagnostic().span_err(
2480 bound_pred.bounded_ty.span,
2481 "`?Trait` bounds are only permitted at the \
2482 point where a type parameter is declared",
2485 // Check if the where clause type is a plain type parameter.
2486 match bound_pred.bounded_ty.node {
2487 TyKind::Path(None, ref path)
2488 if path.segments.len() == 1
2489 && bound_pred.bound_generic_params.is_empty() =>
2491 if let Some(Def::TyParam(def_id)) = self.resolver
2492 .get_resolution(bound_pred.bounded_ty.id)
2493 .map(|d| d.base_def())
2495 if let Some(node_id) =
2496 self.resolver.definitions().as_local_node_id(def_id)
2498 for param in &generics.params {
2500 GenericParamKind::Type { .. } => {
2501 if node_id == param.id {
2502 add_bounds.entry(param.id)
2504 .push(bound.clone());
2505 continue 'next_bound;
2515 _ => report_error(self),
2523 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2524 where_clause: self.lower_where_clause(&generics.where_clause),
2525 span: generics.span,
2529 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2530 self.with_anonymous_lifetime_mode(
2531 AnonymousLifetimeMode::ReportError,
2534 id: this.lower_node_id(wc.id).node_id,
2535 predicates: wc.predicates
2537 .map(|predicate| this.lower_where_predicate(predicate))
2544 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2546 WherePredicate::BoundPredicate(WhereBoundPredicate {
2547 ref bound_generic_params,
2552 self.with_in_scope_lifetime_defs(
2553 &bound_generic_params,
2555 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2556 bound_generic_params: this.lower_generic_params(
2557 bound_generic_params,
2558 &NodeMap::default(),
2559 ImplTraitContext::disallowed(),
2561 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
2564 .filter_map(|bound| match *bound {
2565 // Ignore `?Trait` bounds.
2566 // Tthey were copied into type parameters already.
2567 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2568 _ => Some(this.lower_param_bound(
2570 ImplTraitContext::disallowed(),
2579 WherePredicate::RegionPredicate(WhereRegionPredicate {
2583 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2585 lifetime: self.lower_lifetime(lifetime),
2586 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2588 WherePredicate::EqPredicate(WhereEqPredicate {
2593 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2594 id: self.lower_node_id(id).node_id,
2595 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
2596 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
2602 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2604 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2608 .map(|f| self.lower_struct_field(f))
2610 self.lower_node_id(id).node_id,
2612 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2616 .map(|f| self.lower_struct_field(f))
2618 self.lower_node_id(id).node_id,
2620 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2624 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2625 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2626 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2627 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2629 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.ref_id);
2637 fn lower_poly_trait_ref(
2640 mut itctx: ImplTraitContext<'_>,
2641 ) -> hir::PolyTraitRef {
2642 let bound_generic_params = self.lower_generic_params(
2643 &p.bound_generic_params,
2644 &NodeMap::default(),
2647 let trait_ref = self.with_parent_impl_lifetime_defs(
2648 &bound_generic_params,
2649 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2653 bound_generic_params,
2659 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2662 id: self.lower_node_id(f.id).node_id,
2663 ident: match f.ident {
2664 Some(ident) => ident,
2665 // FIXME(jseyfried) positional field hygiene
2666 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2668 vis: self.lower_visibility(&f.vis, None),
2669 ty: self.lower_ty(&f.ty, ImplTraitContext::disallowed()),
2670 attrs: self.lower_attrs(&f.attrs),
2674 fn lower_field(&mut self, f: &Field) -> hir::Field {
2676 id: self.next_id().node_id,
2678 expr: P(self.lower_expr(&f.expr)),
2680 is_shorthand: f.is_shorthand,
2684 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2686 ty: self.lower_ty(&mt.ty, itctx),
2687 mutbl: self.lower_mutability(mt.mutbl),
2691 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2692 -> hir::GenericBounds {
2693 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2696 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2697 let mut expr = None;
2699 let mut stmts = vec![];
2701 for (index, stmt) in b.stmts.iter().enumerate() {
2702 if index == b.stmts.len() - 1 {
2703 if let StmtKind::Expr(ref e) = stmt.node {
2704 expr = Some(P(self.lower_expr(e)));
2706 stmts.extend(self.lower_stmt(stmt));
2709 stmts.extend(self.lower_stmt(stmt));
2713 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2718 stmts: stmts.into(),
2720 rules: self.lower_block_check_mode(&b.rules),
2723 recovered: b.recovered,
2727 fn lower_async_body(
2733 self.lower_body(Some(decl), |this| {
2734 if let IsAsync::Async { closure_id, .. } = asyncness {
2735 let async_expr = this.make_async_expr(
2736 CaptureBy::Value, closure_id, None,
2738 let body = this.lower_block(body, false);
2739 this.expr_block(body, ThinVec::new())
2741 this.expr(body.span, async_expr, ThinVec::new())
2743 let body = this.lower_block(body, false);
2744 this.expr_block(body, ThinVec::new())
2753 attrs: &hir::HirVec<Attribute>,
2754 vis: &mut hir::Visibility,
2756 ) -> hir::ItemKind {
2758 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2759 ItemKind::Use(ref use_tree) => {
2760 // Start with an empty prefix
2763 span: use_tree.span,
2766 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2768 ItemKind::Static(ref t, m, ref e) => {
2769 let value = self.lower_body(None, |this| this.lower_expr(e));
2770 hir::ItemKind::Static(
2773 if self.sess.features_untracked().impl_trait_in_bindings {
2774 ImplTraitContext::Existential(None)
2776 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2779 self.lower_mutability(m),
2783 ItemKind::Const(ref t, ref e) => {
2784 let value = self.lower_body(None, |this| this.lower_expr(e));
2785 hir::ItemKind::Const(
2788 if self.sess.features_untracked().impl_trait_in_bindings {
2789 ImplTraitContext::Existential(None)
2791 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2797 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2798 let fn_def_id = self.resolver.definitions().local_def_id(id);
2799 self.with_new_scopes(|this| {
2800 // Note: we don't need to change the return type from `T` to
2801 // `impl Future<Output = T>` here because lower_body
2802 // only cares about the input argument patterns in the function
2803 // declaration (decl), not the return types.
2804 let body_id = this.lower_async_body(decl, header.asyncness, body);
2806 let (generics, fn_decl) = this.add_in_band_defs(
2809 AnonymousLifetimeMode::PassThrough,
2810 |this, idty| this.lower_fn_decl(
2812 Some((fn_def_id, idty)),
2814 header.asyncness.opt_return_id()
2820 this.lower_fn_header(header),
2826 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2827 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2828 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2829 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2830 self.lower_ty(t, ImplTraitContext::disallowed()),
2831 self.lower_generics(generics, ImplTraitContext::disallowed()),
2833 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2834 generics: self.lower_generics(generics, ImplTraitContext::disallowed()),
2835 bounds: self.lower_param_bounds(b, ImplTraitContext::disallowed()),
2836 impl_trait_fn: None,
2838 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2840 variants: enum_definition
2843 .map(|x| self.lower_variant(x))
2846 self.lower_generics(generics, ImplTraitContext::disallowed()),
2848 ItemKind::Struct(ref struct_def, ref generics) => {
2849 let struct_def = self.lower_variant_data(struct_def);
2850 hir::ItemKind::Struct(
2852 self.lower_generics(generics, ImplTraitContext::disallowed()),
2855 ItemKind::Union(ref vdata, ref generics) => {
2856 let vdata = self.lower_variant_data(vdata);
2857 hir::ItemKind::Union(
2859 self.lower_generics(generics, ImplTraitContext::disallowed()),
2871 let def_id = self.resolver.definitions().local_def_id(id);
2873 // Lower the "impl header" first. This ordering is important
2874 // for in-band lifetimes! Consider `'a` here:
2876 // impl Foo<'a> for u32 {
2877 // fn method(&'a self) { .. }
2880 // Because we start by lowering the `Foo<'a> for u32`
2881 // part, we will add `'a` to the list of generics on
2882 // the impl. When we then encounter it later in the
2883 // method, it will not be considered an in-band
2884 // lifetime to be added, but rather a reference to a
2886 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2889 AnonymousLifetimeMode::CreateParameter,
2891 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2892 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
2895 if let Some(ref trait_ref) = trait_ref {
2896 if let Def::Trait(def_id) = trait_ref.path.def {
2897 this.trait_impls.entry(def_id).or_default().push(id);
2901 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
2903 (trait_ref, lowered_ty)
2907 let new_impl_items = self.with_in_scope_lifetime_defs(
2908 &ast_generics.params,
2912 .map(|item| this.lower_impl_item_ref(item))
2917 hir::ItemKind::Impl(
2918 self.lower_unsafety(unsafety),
2919 self.lower_impl_polarity(polarity),
2920 self.lower_defaultness(defaultness, true /* [1] */),
2927 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2928 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
2931 .map(|item| self.lower_trait_item_ref(item))
2933 hir::ItemKind::Trait(
2934 self.lower_is_auto(is_auto),
2935 self.lower_unsafety(unsafety),
2936 self.lower_generics(generics, ImplTraitContext::disallowed()),
2941 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
2942 self.lower_generics(generics, ImplTraitContext::disallowed()),
2943 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2945 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2948 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2949 // not cause an assertion failure inside the `lower_defaultness` function
2957 vis: &mut hir::Visibility,
2959 attrs: &hir::HirVec<Attribute>,
2960 ) -> hir::ItemKind {
2961 debug!("lower_use_tree(tree={:?})", tree);
2962 debug!("lower_use_tree: vis = {:?}", vis);
2964 let path = &tree.prefix;
2965 let segments = prefix
2968 .chain(path.segments.iter())
2973 UseTreeKind::Simple(rename, id1, id2) => {
2974 *name = tree.ident().name;
2976 // First apply the prefix to the path
2977 let mut path = Path {
2982 // Correctly resolve `self` imports
2983 if path.segments.len() > 1
2984 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2986 let _ = path.segments.pop();
2987 if rename.is_none() {
2988 *name = path.segments.last().unwrap().ident.name;
2992 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2993 let mut defs = self.expect_full_def_from_use(id);
2994 // we want to return *something* from this function, so hang onto the first item
2996 let ret_def = defs.next().unwrap_or(Def::Err);
2998 // Here, we are looping over namespaces, if they exist for the definition
2999 // being imported. We only handle type and value namespaces because we
3000 // won't be dealing with macros in the rest of the compiler.
3001 // Essentially a single `use` which imports two names is desugared into
3003 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
3004 let vis = vis.clone();
3005 let name = name.clone();
3006 let mut path = path.clone();
3007 for seg in &mut path.segments {
3008 seg.id = self.sess.next_node_id();
3010 let span = path.span;
3011 self.resolver.definitions().create_def_with_parent(
3015 DefIndexAddressSpace::High,
3018 self.allocate_hir_id_counter(new_node_id, &path);
3020 self.with_hir_id_owner(new_node_id, |this| {
3021 let new_id = this.lower_node_id(new_node_id);
3023 this.lower_path_extra(def, &path, ParamMode::Explicit, None);
3024 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
3025 let vis_kind = match vis.node {
3026 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3027 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3028 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3029 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3030 let id = this.next_id();
3031 let path = this.renumber_segment_ids(path);
3032 hir::VisibilityKind::Restricted {
3039 let vis = respan(vis.span, vis_kind);
3045 hir_id: new_id.hir_id,
3047 attrs: attrs.clone(),
3057 P(self.lower_path_extra(ret_def, &path, ParamMode::Explicit, None));
3058 hir::ItemKind::Use(path, hir::UseKind::Single)
3060 UseTreeKind::Glob => {
3061 let path = P(self.lower_path(
3067 ParamMode::Explicit,
3069 hir::ItemKind::Use(path, hir::UseKind::Glob)
3071 UseTreeKind::Nested(ref trees) => {
3072 // Nested imports are desugared into simple
3073 // imports. So if we start with
3076 // pub(x) use foo::{a, b};
3079 // we will create three items:
3082 // pub(x) use foo::a;
3083 // pub(x) use foo::b;
3084 // pub(x) use foo::{}; // <-- this is called the `ListStem`
3087 // The first two are produced by recursively invoking
3088 // `lower_use_tree` (and indeed there may be things
3089 // like `use foo::{a::{b, c}}` and so forth). They
3090 // wind up being directly added to
3091 // `self.items`. However, the structure of this
3092 // function also requires us to return one item, and
3093 // for that we return the `{}` import (called the
3098 span: prefix.span.to(path.span),
3101 // Add all the nested PathListItems to the HIR.
3102 for &(ref use_tree, id) in trees {
3103 self.allocate_hir_id_counter(id, &use_tree);
3108 } = self.lower_node_id(id);
3110 let mut vis = vis.clone();
3111 let mut name = name.clone();
3112 let mut prefix = prefix.clone();
3114 // Give the segments new ids since they are being cloned.
3115 for seg in &mut prefix.segments {
3116 seg.id = self.sess.next_node_id();
3119 // Each `use` import is an item and thus are owners of the
3120 // names in the path. Up to this point the nested import is
3121 // the current owner, since we want each desugared import to
3122 // own its own names, we have to adjust the owner before
3123 // lowering the rest of the import.
3124 self.with_hir_id_owner(new_id, |this| {
3125 let item = this.lower_use_tree(use_tree,
3132 let vis_kind = match vis.node {
3133 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3134 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3135 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3136 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3137 let id = this.next_id();
3138 let path = this.renumber_segment_ids(path);
3139 hir::VisibilityKind::Restricted {
3146 let vis = respan(vis.span, vis_kind);
3154 attrs: attrs.clone(),
3157 span: use_tree.span,
3163 // Subtle and a bit hacky: we lower the privacy level
3164 // of the list stem to "private" most of the time, but
3165 // not for "restricted" paths. The key thing is that
3166 // we don't want it to stay as `pub` (with no caveats)
3167 // because that affects rustdoc and also the lints
3168 // about `pub` items. But we can't *always* make it
3169 // private -- particularly not for restricted paths --
3170 // because it contains node-ids that would then be
3171 // unused, failing the check that HirIds are "densely
3174 hir::VisibilityKind::Public |
3175 hir::VisibilityKind::Crate(_) |
3176 hir::VisibilityKind::Inherited => {
3177 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3179 hir::VisibilityKind::Restricted { .. } => {
3180 // do nothing here, as described in the comment on the match
3184 let def = self.expect_full_def_from_use(id).next().unwrap_or(Def::Err);
3185 let path = P(self.lower_path_extra(def, &prefix, ParamMode::Explicit, None));
3186 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3191 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
3192 /// many times in the HIR tree; for each occurrence, we need to assign distinct
3193 /// node-ids. (See e.g. #56128.)
3194 fn renumber_segment_ids(&mut self, path: &P<hir::Path>) -> P<hir::Path> {
3195 debug!("renumber_segment_ids(path = {:?})", path);
3196 let mut path = path.clone();
3197 for seg in path.segments.iter_mut() {
3198 if seg.id.is_some() {
3199 seg.id = Some(self.next_id().node_id);
3205 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3206 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3207 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
3209 let (generics, node) = match i.node {
3210 TraitItemKind::Const(ref ty, ref default) => (
3211 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3212 hir::TraitItemKind::Const(
3213 self.lower_ty(ty, ImplTraitContext::disallowed()),
3216 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
3219 TraitItemKind::Method(ref sig, None) => {
3220 let names = self.lower_fn_args_to_names(&sig.decl);
3221 let (generics, sig) = self.lower_method_sig(
3228 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3230 TraitItemKind::Method(ref sig, Some(ref body)) => {
3231 let body_id = self.lower_body(Some(&sig.decl), |this| {
3232 let body = this.lower_block(body, false);
3233 this.expr_block(body, ThinVec::new())
3235 let (generics, sig) = self.lower_method_sig(
3242 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3244 TraitItemKind::Type(ref bounds, ref default) => (
3245 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3246 hir::TraitItemKind::Type(
3247 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3250 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3253 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3260 attrs: self.lower_attrs(&i.attrs),
3267 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3268 let (kind, has_default) = match i.node {
3269 TraitItemKind::Const(_, ref default) => {
3270 (hir::AssociatedItemKind::Const, default.is_some())
3272 TraitItemKind::Type(_, ref default) => {
3273 (hir::AssociatedItemKind::Type, default.is_some())
3275 TraitItemKind::Method(ref sig, ref default) => (
3276 hir::AssociatedItemKind::Method {
3277 has_self: sig.decl.has_self(),
3281 TraitItemKind::Macro(..) => unimplemented!(),
3284 id: hir::TraitItemId { node_id: i.id },
3287 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3292 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3293 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3294 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3296 let (generics, node) = match i.node {
3297 ImplItemKind::Const(ref ty, ref expr) => {
3298 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3300 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3301 hir::ImplItemKind::Const(
3302 self.lower_ty(ty, ImplTraitContext::disallowed()),
3307 ImplItemKind::Method(ref sig, ref body) => {
3308 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3309 let impl_trait_return_allow = !self.is_in_trait_impl;
3310 let (generics, sig) = self.lower_method_sig(
3314 impl_trait_return_allow,
3315 sig.header.asyncness.opt_return_id(),
3317 (generics, hir::ImplItemKind::Method(sig, body_id))
3319 ImplItemKind::Type(ref ty) => (
3320 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3321 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3323 ImplItemKind::Existential(ref bounds) => (
3324 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3325 hir::ImplItemKind::Existential(
3326 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3329 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3336 attrs: self.lower_attrs(&i.attrs),
3338 vis: self.lower_visibility(&i.vis, None),
3339 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3344 // [1] since `default impl` is not yet implemented, this is always true in impls
3347 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3349 id: hir::ImplItemId { node_id: i.id },
3352 vis: self.lower_visibility(&i.vis, Some(i.id)),
3353 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3354 kind: match i.node {
3355 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3356 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3357 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3358 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3359 has_self: sig.decl.has_self(),
3361 ImplItemKind::Macro(..) => unimplemented!(),
3365 // [1] since `default impl` is not yet implemented, this is always true in impls
3368 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3371 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3375 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3377 ItemKind::Use(ref use_tree) => {
3378 let mut vec = smallvec![hir::ItemId { id: i.id }];
3379 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3382 ItemKind::MacroDef(..) => SmallVec::new(),
3384 ItemKind::Impl(.., None, _, _) => smallvec![hir::ItemId { id: i.id }],
3385 ItemKind::Static(ref ty, ..) => {
3386 let mut ids = smallvec![hir::ItemId { id: i.id }];
3387 if self.sess.features_untracked().impl_trait_in_bindings {
3388 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3389 visitor.visit_ty(ty);
3393 ItemKind::Const(ref ty, ..) => {
3394 let mut ids = smallvec![hir::ItemId { id: i.id }];
3395 if self.sess.features_untracked().impl_trait_in_bindings {
3396 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3397 visitor.visit_ty(ty);
3401 _ => smallvec![hir::ItemId { id: i.id }],
3405 fn lower_item_id_use_tree(&mut self,
3408 vec: &mut SmallVec<[hir::ItemId; 1]>)
3411 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3412 vec.push(hir::ItemId { id });
3413 self.lower_item_id_use_tree(nested, id, vec);
3415 UseTreeKind::Glob => {}
3416 UseTreeKind::Simple(_, id1, id2) => {
3417 for (_, &id) in self.expect_full_def_from_use(base_id)
3419 .zip([id1, id2].iter())
3421 vec.push(hir::ItemId { id });
3427 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3428 let mut name = i.ident.name;
3429 let mut vis = self.lower_visibility(&i.vis, None);
3430 let attrs = self.lower_attrs(&i.attrs);
3431 if let ItemKind::MacroDef(ref def) = i.node {
3432 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3433 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3434 let body = self.lower_token_stream(def.stream());
3435 self.exported_macros.push(hir::MacroDef {
3448 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3450 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3463 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3464 let node_id = self.lower_node_id(i.id).node_id;
3465 let def_id = self.resolver.definitions().local_def_id(node_id);
3469 attrs: self.lower_attrs(&i.attrs),
3470 node: match i.node {
3471 ForeignItemKind::Fn(ref fdec, ref generics) => {
3472 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3475 AnonymousLifetimeMode::PassThrough,
3478 // Disallow impl Trait in foreign items
3479 this.lower_fn_decl(fdec, None, false, None),
3480 this.lower_fn_args_to_names(fdec),
3485 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3487 ForeignItemKind::Static(ref t, m) => {
3488 hir::ForeignItemKind::Static(
3489 self.lower_ty(t, ImplTraitContext::disallowed()), m)
3491 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3492 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3494 vis: self.lower_visibility(&i.vis, None),
3499 fn lower_method_sig(
3501 generics: &Generics,
3504 impl_trait_return_allow: bool,
3505 is_async: Option<NodeId>,
3506 ) -> (hir::Generics, hir::MethodSig) {
3507 let header = self.lower_fn_header(sig.header);
3508 let (generics, decl) = self.add_in_band_defs(
3511 AnonymousLifetimeMode::PassThrough,
3512 |this, idty| this.lower_fn_decl(
3514 Some((fn_def_id, idty)),
3515 impl_trait_return_allow,
3519 (generics, hir::MethodSig { header, decl })
3522 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3524 IsAuto::Yes => hir::IsAuto::Yes,
3525 IsAuto::No => hir::IsAuto::No,
3529 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3531 unsafety: self.lower_unsafety(h.unsafety),
3532 asyncness: self.lower_asyncness(h.asyncness),
3533 constness: self.lower_constness(h.constness),
3538 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3540 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3541 Unsafety::Normal => hir::Unsafety::Normal,
3545 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3547 Constness::Const => hir::Constness::Const,
3548 Constness::NotConst => hir::Constness::NotConst,
3552 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3554 IsAsync::Async { .. } => hir::IsAsync::Async,
3555 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3559 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3561 UnOp::Deref => hir::UnDeref,
3562 UnOp::Not => hir::UnNot,
3563 UnOp::Neg => hir::UnNeg,
3567 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3569 node: match b.node {
3570 BinOpKind::Add => hir::BinOpKind::Add,
3571 BinOpKind::Sub => hir::BinOpKind::Sub,
3572 BinOpKind::Mul => hir::BinOpKind::Mul,
3573 BinOpKind::Div => hir::BinOpKind::Div,
3574 BinOpKind::Rem => hir::BinOpKind::Rem,
3575 BinOpKind::And => hir::BinOpKind::And,
3576 BinOpKind::Or => hir::BinOpKind::Or,
3577 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3578 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3579 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3580 BinOpKind::Shl => hir::BinOpKind::Shl,
3581 BinOpKind::Shr => hir::BinOpKind::Shr,
3582 BinOpKind::Eq => hir::BinOpKind::Eq,
3583 BinOpKind::Lt => hir::BinOpKind::Lt,
3584 BinOpKind::Le => hir::BinOpKind::Le,
3585 BinOpKind::Ne => hir::BinOpKind::Ne,
3586 BinOpKind::Ge => hir::BinOpKind::Ge,
3587 BinOpKind::Gt => hir::BinOpKind::Gt,
3593 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3594 let node = match p.node {
3595 PatKind::Wild => hir::PatKind::Wild,
3596 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3597 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3598 // `None` can occur in body-less function signatures
3599 def @ None | def @ Some(Def::Local(_)) => {
3600 let canonical_id = match def {
3601 Some(Def::Local(id)) => id,
3604 hir::PatKind::Binding(
3605 self.lower_binding_mode(binding_mode),
3608 sub.as_ref().map(|x| self.lower_pat(x)),
3611 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3616 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3621 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3622 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3623 let qpath = self.lower_qpath(
3627 ParamMode::Optional,
3628 ImplTraitContext::disallowed(),
3630 hir::PatKind::TupleStruct(
3632 pats.iter().map(|x| self.lower_pat(x)).collect(),
3636 PatKind::Path(ref qself, ref path) => {
3637 let qpath = self.lower_qpath(
3641 ParamMode::Optional,
3642 ImplTraitContext::disallowed(),
3644 hir::PatKind::Path(qpath)
3646 PatKind::Struct(ref path, ref fields, etc) => {
3647 let qpath = self.lower_qpath(
3651 ParamMode::Optional,
3652 ImplTraitContext::disallowed(),
3659 node: hir::FieldPat {
3660 id: self.next_id().node_id,
3661 ident: f.node.ident,
3662 pat: self.lower_pat(&f.node.pat),
3663 is_shorthand: f.node.is_shorthand,
3667 hir::PatKind::Struct(qpath, fs, etc)
3669 PatKind::Tuple(ref elts, ddpos) => {
3670 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3672 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3673 PatKind::Ref(ref inner, mutbl) => {
3674 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3676 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3677 P(self.lower_expr(e1)),
3678 P(self.lower_expr(e2)),
3679 self.lower_range_end(end),
3681 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3682 before.iter().map(|x| self.lower_pat(x)).collect(),
3683 slice.as_ref().map(|x| self.lower_pat(x)),
3684 after.iter().map(|x| self.lower_pat(x)).collect(),
3686 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3687 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3690 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3699 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3701 RangeEnd::Included(_) => hir::RangeEnd::Included,
3702 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3706 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3707 self.with_new_scopes(|this| {
3708 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3712 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3717 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3718 let kind = match e.node {
3719 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3720 ExprKind::ObsoleteInPlace(..) => {
3721 self.sess.abort_if_errors();
3722 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3724 ExprKind::Array(ref exprs) => {
3725 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3727 ExprKind::Repeat(ref expr, ref count) => {
3728 let expr = P(self.lower_expr(expr));
3729 let count = self.lower_anon_const(count);
3730 hir::ExprKind::Repeat(expr, count)
3732 ExprKind::Tup(ref elts) => {
3733 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3735 ExprKind::Call(ref f, ref args) => {
3736 let f = P(self.lower_expr(f));
3737 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3739 ExprKind::MethodCall(ref seg, ref args) => {
3740 let hir_seg = self.lower_path_segment(
3743 ParamMode::Optional,
3745 ParenthesizedGenericArgs::Err,
3746 ImplTraitContext::disallowed(),
3749 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3750 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3752 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3753 let binop = self.lower_binop(binop);
3754 let lhs = P(self.lower_expr(lhs));
3755 let rhs = P(self.lower_expr(rhs));
3756 hir::ExprKind::Binary(binop, lhs, rhs)
3758 ExprKind::Unary(op, ref ohs) => {
3759 let op = self.lower_unop(op);
3760 let ohs = P(self.lower_expr(ohs));
3761 hir::ExprKind::Unary(op, ohs)
3763 ExprKind::Lit(ref l) => hir::ExprKind::Lit(P((*l).clone())),
3764 ExprKind::Cast(ref expr, ref ty) => {
3765 let expr = P(self.lower_expr(expr));
3766 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3768 ExprKind::Type(ref expr, ref ty) => {
3769 let expr = P(self.lower_expr(expr));
3770 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3772 ExprKind::AddrOf(m, ref ohs) => {
3773 let m = self.lower_mutability(m);
3774 let ohs = P(self.lower_expr(ohs));
3775 hir::ExprKind::AddrOf(m, ohs)
3777 // More complicated than you might expect because the else branch
3778 // might be `if let`.
3779 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3780 let else_opt = else_opt.as_ref().map(|els| {
3782 ExprKind::IfLet(..) => {
3783 // wrap the if-let expr in a block
3784 let span = els.span;
3785 let els = P(self.lower_expr(els));
3786 let LoweredNodeId { node_id, hir_id } = self.next_id();
3787 let blk = P(hir::Block {
3792 rules: hir::DefaultBlock,
3794 targeted_by_break: false,
3795 recovered: blk.recovered,
3797 P(self.expr_block(blk, ThinVec::new()))
3799 _ => P(self.lower_expr(els)),
3803 let then_blk = self.lower_block(blk, false);
3804 let then_expr = self.expr_block(then_blk, ThinVec::new());
3806 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3808 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3809 hir::ExprKind::While(
3810 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3811 this.lower_block(body, false),
3812 this.lower_label(opt_label),
3815 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3816 hir::ExprKind::Loop(
3817 this.lower_block(body, false),
3818 this.lower_label(opt_label),
3819 hir::LoopSource::Loop,
3822 ExprKind::TryBlock(ref body) => {
3823 self.with_catch_scope(body.id, |this| {
3825 this.allow_internal_unstable(CompilerDesugaringKind::TryBlock, body.span);
3826 let mut block = this.lower_block(body, true).into_inner();
3827 let tail = block.expr.take().map_or_else(
3829 let LoweredNodeId { node_id, hir_id } = this.next_id();
3830 let span = this.sess.source_map().end_point(unstable_span);
3834 node: hir::ExprKind::Tup(hir_vec![]),
3835 attrs: ThinVec::new(),
3839 |x: P<hir::Expr>| x.into_inner(),
3841 block.expr = Some(this.wrap_in_try_constructor(
3842 "from_ok", tail, unstable_span));
3843 hir::ExprKind::Block(P(block), None)
3846 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3847 P(self.lower_expr(expr)),
3848 arms.iter().map(|x| self.lower_arm(x)).collect(),
3849 hir::MatchSource::Normal,
3851 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3852 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3853 this.with_new_scopes(|this| {
3854 let block = this.lower_block(block, false);
3855 this.expr_block(block, ThinVec::new())
3860 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3862 if let IsAsync::Async { closure_id, .. } = asyncness {
3863 let outer_decl = FnDecl {
3864 inputs: decl.inputs.clone(),
3865 output: FunctionRetTy::Default(fn_decl_span),
3868 // We need to lower the declaration outside the new scope, because we
3869 // have to conserve the state of being inside a loop condition for the
3870 // closure argument types.
3871 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3873 self.with_new_scopes(|this| {
3874 // FIXME(cramertj) allow `async` non-`move` closures with
3875 if capture_clause == CaptureBy::Ref &&
3876 !decl.inputs.is_empty()
3882 "`async` non-`move` closures with arguments \
3883 are not currently supported",
3885 .help("consider using `let` statements to manually capture \
3886 variables by reference before entering an \
3887 `async move` closure")
3891 // Transform `async |x: u8| -> X { ... }` into
3892 // `|x: u8| future_from_generator(|| -> X { ... })`
3893 let body_id = this.lower_body(Some(&outer_decl), |this| {
3894 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3897 let async_body = this.make_async_expr(
3898 capture_clause, closure_id, async_ret_ty,
3900 this.with_new_scopes(|this| this.lower_expr(body))
3902 this.expr(fn_decl_span, async_body, ThinVec::new())
3904 hir::ExprKind::Closure(
3905 this.lower_capture_clause(capture_clause),
3913 // Lower outside new scope to preserve `is_in_loop_condition`.
3914 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3916 self.with_new_scopes(|this| {
3917 let mut is_generator = false;
3918 let body_id = this.lower_body(Some(decl), |this| {
3919 let e = this.lower_expr(body);
3920 is_generator = this.is_generator;
3923 let generator_option = if is_generator {
3924 if !decl.inputs.is_empty() {
3929 "generators cannot have explicit arguments"
3931 this.sess.abort_if_errors();
3933 Some(match movability {
3934 Movability::Movable => hir::GeneratorMovability::Movable,
3935 Movability::Static => hir::GeneratorMovability::Static,
3938 if movability == Movability::Static {
3943 "closures cannot be static"
3948 hir::ExprKind::Closure(
3949 this.lower_capture_clause(capture_clause),
3958 ExprKind::Block(ref blk, opt_label) => {
3959 hir::ExprKind::Block(self.lower_block(blk,
3960 opt_label.is_some()),
3961 self.lower_label(opt_label))
3963 ExprKind::Assign(ref el, ref er) => {
3964 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3966 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
3967 self.lower_binop(op),
3968 P(self.lower_expr(el)),
3969 P(self.lower_expr(er)),
3971 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
3972 ExprKind::Index(ref el, ref er) => {
3973 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
3975 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3976 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3977 let id = self.next_id();
3978 let e1 = self.lower_expr(e1);
3979 let e2 = self.lower_expr(e2);
3980 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
3981 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
3982 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3983 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3984 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
3985 hir::ExprKind::Call(new, hir_vec![e1, e2])
3987 ExprKind::Range(ref e1, ref e2, lims) => {
3988 use syntax::ast::RangeLimits::*;
3990 let path = match (e1, e2, lims) {
3991 (&None, &None, HalfOpen) => "RangeFull",
3992 (&Some(..), &None, HalfOpen) => "RangeFrom",
3993 (&None, &Some(..), HalfOpen) => "RangeTo",
3994 (&Some(..), &Some(..), HalfOpen) => "Range",
3995 (&None, &Some(..), Closed) => "RangeToInclusive",
3996 (&Some(..), &Some(..), Closed) => unreachable!(),
3997 (_, &None, Closed) => self.diagnostic()
3998 .span_fatal(e.span, "inclusive range with no end")
4002 let fields = e1.iter()
4003 .map(|e| ("start", e))
4004 .chain(e2.iter().map(|e| ("end", e)))
4006 let expr = P(self.lower_expr(&e));
4007 let ident = Ident::new(Symbol::intern(s), e.span);
4008 self.field(ident, expr, e.span)
4010 .collect::<P<[hir::Field]>>();
4012 let is_unit = fields.is_empty();
4013 let struct_path = ["ops", path];
4014 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
4015 let struct_path = hir::QPath::Resolved(None, P(struct_path));
4017 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4023 hir::ExprKind::Path(struct_path)
4025 hir::ExprKind::Struct(struct_path, fields, None)
4028 attrs: e.attrs.clone(),
4031 ExprKind::Path(ref qself, ref path) => {
4032 let qpath = self.lower_qpath(
4036 ParamMode::Optional,
4037 ImplTraitContext::disallowed(),
4039 hir::ExprKind::Path(qpath)
4041 ExprKind::Break(opt_label, ref opt_expr) => {
4042 let destination = if self.is_in_loop_condition && opt_label.is_none() {
4045 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4048 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4050 hir::ExprKind::Break(
4052 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
4055 ExprKind::Continue(opt_label) => {
4056 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
4059 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4062 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4065 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
4066 ExprKind::InlineAsm(ref asm) => {
4067 let hir_asm = hir::InlineAsm {
4068 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
4069 outputs: asm.outputs
4071 .map(|out| hir::InlineAsmOutput {
4072 constraint: out.constraint.clone(),
4074 is_indirect: out.is_indirect,
4075 span: out.expr.span,
4078 asm: asm.asm.clone(),
4079 asm_str_style: asm.asm_str_style,
4080 clobbers: asm.clobbers.clone().into(),
4081 volatile: asm.volatile,
4082 alignstack: asm.alignstack,
4083 dialect: asm.dialect,
4086 let outputs = asm.outputs
4088 .map(|out| self.lower_expr(&out.expr))
4090 let inputs = asm.inputs
4092 .map(|&(_, ref input)| self.lower_expr(input))
4094 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
4096 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4101 ParamMode::Optional,
4102 ImplTraitContext::disallowed(),
4104 fields.iter().map(|x| self.lower_field(x)).collect(),
4105 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4107 ExprKind::Paren(ref ex) => {
4108 let mut ex = self.lower_expr(ex);
4109 // include parens in span, but only if it is a super-span.
4110 if e.span.contains(ex.span) {
4113 // merge attributes into the inner expression.
4114 let mut attrs = e.attrs.clone();
4115 attrs.extend::<Vec<_>>(ex.attrs.into());
4120 ExprKind::Yield(ref opt_expr) => {
4121 self.is_generator = true;
4124 .map(|x| self.lower_expr(x))
4126 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
4128 hir::ExprKind::Yield(P(expr))
4131 // Desugar ExprIfLet
4132 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
4133 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4136 // match <sub_expr> {
4138 // _ => [<else_opt> | ()]
4141 let mut arms = vec![];
4143 // `<pat> => <body>`
4145 let body = self.lower_block(body, false);
4146 let body_expr = P(self.expr_block(body, ThinVec::new()));
4147 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4148 arms.push(self.arm(pats, body_expr));
4151 // _ => [<else_opt>|()]
4153 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4154 let wildcard_pattern = self.pat_wild(e.span);
4155 let body = if let Some(else_expr) = wildcard_arm {
4156 P(self.lower_expr(else_expr))
4158 self.expr_tuple(e.span, hir_vec![])
4160 arms.push(self.arm(hir_vec![wildcard_pattern], body));
4163 let contains_else_clause = else_opt.is_some();
4165 let sub_expr = P(self.lower_expr(sub_expr));
4167 hir::ExprKind::Match(
4170 hir::MatchSource::IfLetDesugar {
4171 contains_else_clause,
4176 // Desugar ExprWhileLet
4177 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4178 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4181 // [opt_ident]: loop {
4182 // match <sub_expr> {
4188 // Note that the block AND the condition are evaluated in the loop scope.
4189 // This is done to allow `break` from inside the condition of the loop.
4190 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4192 this.lower_block(body, false),
4193 this.expr_break(e.span, ThinVec::new()),
4194 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4198 // `<pat> => <body>`
4200 let body_expr = P(self.expr_block(body, ThinVec::new()));
4201 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4202 self.arm(pats, body_expr)
4207 let pat_under = self.pat_wild(e.span);
4208 self.arm(hir_vec![pat_under], break_expr)
4211 // `match <sub_expr> { ... }`
4212 let arms = hir_vec![pat_arm, break_arm];
4213 let match_expr = self.expr(
4215 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4219 // `[opt_ident]: loop { ... }`
4220 let loop_block = P(self.block_expr(P(match_expr)));
4221 let loop_expr = hir::ExprKind::Loop(
4223 self.lower_label(opt_label),
4224 hir::LoopSource::WhileLet,
4226 // add attributes to the outer returned expr node
4230 // Desugar ExprForLoop
4231 // From: `[opt_ident]: for <pat> in <head> <body>`
4232 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4236 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4238 // [opt_ident]: loop {
4240 // match ::std::iter::Iterator::next(&mut iter) {
4241 // ::std::option::Option::Some(val) => __next = val,
4242 // ::std::option::Option::None => break
4244 // let <pat> = __next;
4245 // StmtKind::Expr(<body>);
4253 let head = self.lower_expr(head);
4254 let head_sp = head.span;
4255 let desugared_span = self.allow_internal_unstable(
4256 CompilerDesugaringKind::ForLoop,
4260 let iter = self.str_to_ident("iter");
4262 let next_ident = self.str_to_ident("__next");
4263 let next_pat = self.pat_ident_binding_mode(
4266 hir::BindingAnnotation::Mutable,
4269 // `::std::option::Option::Some(val) => next = val`
4271 let val_ident = self.str_to_ident("val");
4272 let val_pat = self.pat_ident(pat.span, val_ident);
4273 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4274 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4275 let assign = P(self.expr(
4277 hir::ExprKind::Assign(next_expr, val_expr),
4280 let some_pat = self.pat_some(pat.span, val_pat);
4281 self.arm(hir_vec![some_pat], assign)
4284 // `::std::option::Option::None => break`
4287 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4288 let pat = self.pat_none(e.span);
4289 self.arm(hir_vec![pat], break_expr)
4293 let iter_pat = self.pat_ident_binding_mode(
4296 hir::BindingAnnotation::Mutable
4299 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4301 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4302 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4303 let next_path = &["iter", "Iterator", "next"];
4304 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4305 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4306 let arms = hir_vec![pat_arm, break_arm];
4310 hir::ExprKind::Match(
4313 hir::MatchSource::ForLoopDesugar
4318 let match_stmt = respan(
4320 hir::StmtKind::Expr(match_expr, self.next_id().node_id)
4323 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4326 let next_let = self.stmt_let_pat(
4330 hir::LocalSource::ForLoopDesugar,
4333 // `let <pat> = __next`
4334 let pat = self.lower_pat(pat);
4335 let pat_let = self.stmt_let_pat(
4339 hir::LocalSource::ForLoopDesugar,
4342 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4343 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4344 let body_stmt = respan(
4346 hir::StmtKind::Expr(body_expr, self.next_id().node_id)
4349 let loop_block = P(self.block_all(
4351 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4355 // `[opt_ident]: loop { ... }`
4356 let loop_expr = hir::ExprKind::Loop(
4358 self.lower_label(opt_label),
4359 hir::LoopSource::ForLoop,
4361 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4362 let loop_expr = P(hir::Expr {
4367 attrs: ThinVec::new(),
4370 // `mut iter => { ... }`
4371 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4373 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4374 let into_iter_expr = {
4375 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4376 let into_iter = P(self.expr_std_path(
4377 head_sp, into_iter_path, None, ThinVec::new()));
4378 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4381 let match_expr = P(self.expr_match(
4385 hir::MatchSource::ForLoopDesugar,
4388 // `{ let _result = ...; _result }`
4389 // underscore prevents an unused_variables lint if the head diverges
4390 let result_ident = self.str_to_ident("_result");
4391 let (let_stmt, let_stmt_binding) =
4392 self.stmt_let(e.span, false, result_ident, match_expr);
4394 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4395 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4396 // add the attributes to the outer returned expr node
4397 return self.expr_block(block, e.attrs.clone());
4400 // Desugar ExprKind::Try
4402 ExprKind::Try(ref sub_expr) => {
4405 // match Try::into_result(<expr>) {
4406 // Ok(val) => #[allow(unreachable_code)] val,
4407 // Err(err) => #[allow(unreachable_code)]
4408 // // If there is an enclosing `catch {...}`
4409 // break 'catch_target Try::from_error(From::from(err)),
4411 // return Try::from_error(From::from(err)),
4415 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4417 // Try::into_result(<expr>)
4420 let sub_expr = self.lower_expr(sub_expr);
4422 let path = &["ops", "Try", "into_result"];
4423 let path = P(self.expr_std_path(
4424 unstable_span, path, None, ThinVec::new()));
4425 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4428 // #[allow(unreachable_code)]
4430 // allow(unreachable_code)
4432 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4433 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4434 let uc_nested = attr::mk_nested_word_item(uc_ident);
4435 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4437 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4439 let attrs = vec![attr];
4441 // Ok(val) => #[allow(unreachable_code)] val,
4443 let val_ident = self.str_to_ident("val");
4444 let val_pat = self.pat_ident(e.span, val_ident);
4445 let val_expr = P(self.expr_ident_with_attrs(
4449 ThinVec::from(attrs.clone()),
4451 let ok_pat = self.pat_ok(e.span, val_pat);
4453 self.arm(hir_vec![ok_pat], val_expr)
4456 // Err(err) => #[allow(unreachable_code)]
4457 // return Try::from_error(From::from(err)),
4459 let err_ident = self.str_to_ident("err");
4460 let err_local = self.pat_ident(e.span, err_ident);
4462 let path = &["convert", "From", "from"];
4463 let from = P(self.expr_std_path(
4464 e.span, path, None, ThinVec::new()));
4465 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4467 self.expr_call(e.span, from, hir_vec![err_expr])
4470 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4471 let thin_attrs = ThinVec::from(attrs);
4472 let catch_scope = self.catch_scopes.last().map(|x| *x);
4473 let ret_expr = if let Some(catch_node) = catch_scope {
4476 hir::ExprKind::Break(
4479 target_id: Ok(catch_node),
4481 Some(from_err_expr),
4486 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4489 let err_pat = self.pat_err(e.span, err_local);
4490 self.arm(hir_vec![err_pat], ret_expr)
4493 hir::ExprKind::Match(
4495 hir_vec![err_arm, ok_arm],
4496 hir::MatchSource::TryDesugar,
4500 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4503 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4510 attrs: e.attrs.clone(),
4514 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
4515 smallvec![match s.node {
4516 StmtKind::Local(ref l) => {
4517 let (l, item_ids) = self.lower_local(l);
4518 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
4520 .map(|item_id| Spanned {
4521 node: hir::StmtKind::Decl(
4523 node: hir::DeclKind::Item(item_id),
4526 self.next_id().node_id,
4532 node: hir::StmtKind::Decl(
4534 node: hir::DeclKind::Local(l),
4537 self.lower_node_id(s.id).node_id,
4543 StmtKind::Item(ref it) => {
4544 // Can only use the ID once.
4545 let mut id = Some(s.id);
4546 return self.lower_item_id(it)
4548 .map(|item_id| Spanned {
4549 node: hir::StmtKind::Decl(
4551 node: hir::DeclKind::Item(item_id),
4555 .map(|id| self.lower_node_id(id).node_id)
4556 .unwrap_or_else(|| self.next_id().node_id),
4562 StmtKind::Expr(ref e) => Spanned {
4563 node: hir::StmtKind::Expr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4566 StmtKind::Semi(ref e) => Spanned {
4567 node: hir::StmtKind::Semi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4570 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4574 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4576 CaptureBy::Value => hir::CaptureByValue,
4577 CaptureBy::Ref => hir::CaptureByRef,
4581 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4582 /// the address space of that item instead of the item currently being
4583 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4584 /// lower a `Visibility` value although we haven't lowered the owning
4585 /// `ImplItem` in question yet.
4586 fn lower_visibility(
4589 explicit_owner: Option<NodeId>,
4590 ) -> hir::Visibility {
4591 let node = match v.node {
4592 VisibilityKind::Public => hir::VisibilityKind::Public,
4593 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4594 VisibilityKind::Restricted { ref path, id } => {
4595 debug!("lower_visibility: restricted path id = {:?}", id);
4596 let lowered_id = if let Some(owner) = explicit_owner {
4597 self.lower_node_id_with_owner(id, owner)
4599 self.lower_node_id(id)
4601 let def = self.expect_full_def(id);
4602 hir::VisibilityKind::Restricted {
4603 path: P(self.lower_path_extra(
4606 ParamMode::Explicit,
4609 id: lowered_id.node_id,
4610 hir_id: lowered_id.hir_id,
4613 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4615 respan(v.span, node)
4618 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4620 Defaultness::Default => hir::Defaultness::Default {
4621 has_value: has_value,
4623 Defaultness::Final => {
4625 hir::Defaultness::Final
4630 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4632 BlockCheckMode::Default => hir::DefaultBlock,
4633 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4637 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4639 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4640 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4641 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4642 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4646 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4648 CompilerGenerated => hir::CompilerGenerated,
4649 UserProvided => hir::UserProvided,
4653 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4655 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4656 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4660 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4662 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4663 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4667 // Helper methods for building HIR.
4669 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4678 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4680 id: self.next_id().node_id,
4684 is_shorthand: false,
4688 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4689 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4690 P(self.expr(span, expr_break, attrs))
4697 args: hir::HirVec<hir::Expr>,
4699 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4702 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4703 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4706 fn expr_ident_with_attrs(
4711 attrs: ThinVec<Attribute>,
4713 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4717 def: Def::Local(binding),
4718 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4722 self.expr(span, expr_path, attrs)
4725 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4726 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4732 components: &[&str],
4733 params: Option<P<hir::GenericArgs>>,
4734 attrs: ThinVec<Attribute>,
4736 let path = self.std_path(span, components, params, true);
4739 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4748 arms: hir::HirVec<hir::Arm>,
4749 source: hir::MatchSource,
4751 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4754 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4755 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4758 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4759 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4762 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4763 let LoweredNodeId { node_id, hir_id } = self.next_id();
4776 ex: Option<P<hir::Expr>>,
4778 source: hir::LocalSource,
4780 let LoweredNodeId { node_id, hir_id } = self.next_id();
4782 let local = P(hir::Local {
4789 attrs: ThinVec::new(),
4792 let decl = respan(sp, hir::DeclKind::Local(local));
4793 respan(sp, hir::StmtKind::Decl(P(decl), self.next_id().node_id))
4802 ) -> (hir::Stmt, NodeId) {
4803 let pat = if mutbl {
4804 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4806 self.pat_ident(sp, ident)
4808 let pat_id = pat.id;
4810 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4815 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4816 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4822 stmts: hir::HirVec<hir::Stmt>,
4823 expr: Option<P<hir::Expr>>,
4825 let LoweredNodeId { node_id, hir_id } = self.next_id();
4832 rules: hir::DefaultBlock,
4834 targeted_by_break: false,
4839 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4840 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4843 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4844 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4847 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4848 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4851 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4852 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4858 components: &[&str],
4859 subpats: hir::HirVec<P<hir::Pat>>,
4861 let path = self.std_path(span, components, None, true);
4862 let qpath = hir::QPath::Resolved(None, P(path));
4863 let pt = if subpats.is_empty() {
4864 hir::PatKind::Path(qpath)
4866 hir::PatKind::TupleStruct(qpath, subpats, None)
4871 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4872 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4875 fn pat_ident_binding_mode(
4879 bm: hir::BindingAnnotation,
4881 let LoweredNodeId { node_id, hir_id } = self.next_id();
4886 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4891 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4892 self.pat(span, hir::PatKind::Wild)
4895 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4896 let LoweredNodeId { node_id, hir_id } = self.next_id();
4905 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4906 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4907 /// The path is also resolved according to `is_value`.
4911 components: &[&str],
4912 params: Option<P<hir::GenericArgs>>,
4915 let mut path = self.resolver
4916 .resolve_str_path(span, self.crate_root, components, is_value);
4917 path.segments.last_mut().unwrap().args = params;
4920 for seg in path.segments.iter_mut() {
4921 if let Some(id) = seg.id {
4922 seg.id = Some(self.lower_node_id(id).node_id);
4928 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4930 let node = match qpath {
4931 hir::QPath::Resolved(None, path) => {
4932 // Turn trait object paths into `TyKind::TraitObject` instead.
4934 Def::Trait(_) | Def::TraitAlias(_) => {
4935 let principal = hir::PolyTraitRef {
4936 bound_generic_params: hir::HirVec::new(),
4937 trait_ref: hir::TraitRef {
4938 path: path.and_then(|path| path),
4940 hir_ref_id: id.hir_id,
4945 // The original ID is taken by the `PolyTraitRef`,
4946 // so the `Ty` itself needs a different one.
4947 id = self.next_id();
4948 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4950 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
4953 _ => hir::TyKind::Path(qpath),
4963 /// Invoked to create the lifetime argument for a type `&T`
4964 /// with no explicit lifetime.
4965 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4966 match self.anonymous_lifetime_mode {
4967 // Intercept when we are in an impl header and introduce an in-band lifetime.
4968 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4970 AnonymousLifetimeMode::CreateParameter => {
4971 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4973 id: self.next_id().node_id,
4975 name: hir::LifetimeName::Param(fresh_name),
4979 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
4981 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4985 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
4986 /// return a "error lifetime".
4987 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
4988 let (id, msg, label) = match id {
4989 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
4992 self.next_id().node_id,
4993 "`&` without an explicit lifetime name cannot be used here",
4994 "explicit lifetime name needed here",
4998 let mut err = struct_span_err!(
5005 err.span_label(span, label);
5008 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5011 /// Invoked to create the lifetime argument(s) for a path like
5012 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
5013 /// sorts of cases are deprecated. This may therefore report a warning or an
5014 /// error, depending on the mode.
5015 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
5016 match self.anonymous_lifetime_mode {
5017 // NB. We intentionally ignore the create-parameter mode here
5018 // and instead "pass through" to resolve-lifetimes, which will then
5019 // report an error. This is because we don't want to support
5020 // impl elision for deprecated forms like
5022 // impl Foo for std::cell::Ref<u32> // note lack of '_
5023 AnonymousLifetimeMode::CreateParameter => {}
5025 AnonymousLifetimeMode::ReportError => {
5027 .map(|_| self.new_error_lifetime(None, span))
5031 // This is the normal case.
5032 AnonymousLifetimeMode::PassThrough => {}
5036 .map(|_| self.new_implicit_lifetime(span))
5040 /// Invoked to create the lifetime argument(s) for an elided trait object
5041 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
5042 /// when the bound is written, even if it is written with `'_` like in
5043 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
5044 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
5045 match self.anonymous_lifetime_mode {
5046 // NB. We intentionally ignore the create-parameter mode here.
5047 // and instead "pass through" to resolve-lifetimes, which will apply
5048 // the object-lifetime-defaulting rules. Elided object lifetime defaults
5049 // do not act like other elided lifetimes. In other words, given this:
5051 // impl Foo for Box<dyn Debug>
5053 // we do not introduce a fresh `'_` to serve as the bound, but instead
5054 // ultimately translate to the equivalent of:
5056 // impl Foo for Box<dyn Debug + 'static>
5058 // `resolve_lifetime` has the code to make that happen.
5059 AnonymousLifetimeMode::CreateParameter => {}
5061 AnonymousLifetimeMode::ReportError => {
5062 // ReportError applies to explicit use of `'_`.
5065 // This is the normal case.
5066 AnonymousLifetimeMode::PassThrough => {}
5069 self.new_implicit_lifetime(span)
5072 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
5074 id: self.next_id().node_id,
5076 name: hir::LifetimeName::Implicit,
5080 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
5081 self.sess.buffer_lint_with_diagnostic(
5082 builtin::BARE_TRAIT_OBJECTS,
5085 "trait objects without an explicit `dyn` are deprecated",
5086 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
5090 fn wrap_in_try_constructor(
5092 method: &'static str,
5094 unstable_span: Span,
5096 let path = &["ops", "Try", method];
5097 let from_err = P(self.expr_std_path(unstable_span, path, None,
5099 P(self.expr_call(e.span, from_err, hir_vec![e]))
5103 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5104 // Sorting by span ensures that we get things in order within a
5105 // file, and also puts the files in a sensible order.
5106 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5107 body_ids.sort_by_key(|b| bodies[b].value.span);