1 //! Lowers the AST to the HIR.
3 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
4 //! much like a fold. Where lowering involves a bit more work things get more
5 //! interesting and there are some invariants you should know about. These mostly
6 //! concern spans and ids.
8 //! Spans are assigned to AST nodes during parsing and then are modified during
9 //! expansion to indicate the origin of a node and the process it went through
10 //! being expanded. Ids are assigned to AST nodes just before lowering.
12 //! For the simpler lowering steps, ids and spans should be preserved. Unlike
13 //! expansion we do not preserve the process of lowering in the spans, so spans
14 //! should not be modified here. When creating a new node (as opposed to
15 //! 'folding' an existing one), then you create a new id using `next_id()`.
17 //! You must ensure that ids are unique. That means that you should only use the
18 //! id from an AST node in a single HIR node (you can assume that AST node ids
19 //! are unique). Every new node must have a unique id. Avoid cloning HIR nodes.
20 //! If you do, you must then set the new node's id to a fresh one.
22 //! Spans are used for error messages and for tools to map semantics back to
23 //! source code. It is therefore not as important with spans as ids to be strict
24 //! about use (you can't break the compiler by screwing up a span). Obviously, a
25 //! HIR node can only have a single span. But multiple nodes can have the same
26 //! span and spans don't need to be kept in order, etc. Where code is preserved
27 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
28 //! new it is probably best to give a span for the whole AST node being lowered.
29 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
30 //! get confused if the spans from leaf AST nodes occur in multiple places
31 //! in the HIR, especially for multiple identifiers.
33 use dep_graph::DepGraph;
34 use errors::Applicability;
35 use hir::{self, ParamName};
37 use hir::map::{DefKey, DefPathData, Definitions};
38 use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX};
39 use hir::def::{Def, PathResolution, PerNS};
41 use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
42 ELIDED_LIFETIMES_IN_PATHS};
43 use middle::cstore::CrateStore;
44 use rustc_data_structures::fx::FxHashSet;
45 use rustc_data_structures::indexed_vec::IndexVec;
46 use rustc_data_structures::thin_vec::ThinVec;
48 use session::config::nightly_options;
49 use util::common::FN_OUTPUT_NAME;
50 use util::nodemap::{DefIdMap, NodeMap};
52 use std::collections::{BTreeSet, BTreeMap};
55 use smallvec::SmallVec;
60 use syntax::ext::hygiene::{Mark, SyntaxContext};
61 use syntax::print::pprust;
63 use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned};
64 use syntax::std_inject;
65 use syntax::symbol::{keywords, Symbol};
66 use syntax::tokenstream::{TokenStream, TokenTree};
67 use syntax::parse::token::Token;
68 use syntax::visit::{self, Visitor};
69 use syntax_pos::{Span, MultiSpan};
71 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
73 pub struct LoweringContext<'a> {
74 crate_root: Option<&'static str>,
76 // Used to assign ids to HIR nodes that do not directly correspond to an AST node.
79 cstore: &'a dyn CrateStore,
81 resolver: &'a mut dyn Resolver,
83 /// The items being lowered are collected here.
84 items: BTreeMap<NodeId, hir::Item>,
86 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
87 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
88 bodies: BTreeMap<hir::BodyId, hir::Body>,
89 exported_macros: Vec<hir::MacroDef>,
91 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
92 trait_auto_impl: BTreeMap<DefId, NodeId>,
94 modules: BTreeMap<NodeId, hir::ModuleItems>,
98 catch_scopes: Vec<NodeId>,
99 loop_scopes: Vec<NodeId>,
100 is_in_loop_condition: bool,
101 is_in_trait_impl: bool,
103 /// What to do when we encounter either an "anonymous lifetime
104 /// reference". The term "anonymous" is meant to encompass both
105 /// `'_` lifetimes as well as fully elided cases where nothing is
106 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
107 anonymous_lifetime_mode: AnonymousLifetimeMode,
109 // Used to create lifetime definitions from in-band lifetime usages.
110 // e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
111 // When a named lifetime is encountered in a function or impl header and
112 // has not been defined
113 // (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
114 // to this list. The results of this list are then added to the list of
115 // lifetime definitions in the corresponding impl or function generics.
116 lifetimes_to_define: Vec<(Span, ParamName)>,
118 // Whether or not in-band lifetimes are being collected. This is used to
119 // indicate whether or not we're in a place where new lifetimes will result
120 // in in-band lifetime definitions, such a function or an impl header,
121 // including implicit lifetimes from `impl_header_lifetime_elision`.
122 is_collecting_in_band_lifetimes: bool,
124 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
125 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
126 // against this list to see if it is already in-scope, or if a definition
127 // needs to be created for it.
128 in_scope_lifetimes: Vec<Ident>,
130 current_module: NodeId,
132 type_def_lifetime_params: DefIdMap<usize>,
134 current_hir_id_owner: Vec<(DefIndex, u32)>,
135 item_local_id_counters: NodeMap<u32>,
136 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
140 /// Resolve a path generated by the lowerer when expanding `for`, `if let`, etc.
147 /// Obtain the resolution for a node-id.
148 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
150 /// Obtain the possible resolutions for the given `use` statement.
151 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
153 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
154 /// This should only return `None` during testing.
155 fn definitions(&mut self) -> &mut Definitions;
157 /// Given suffix `["b", "c", "d"]`, creates a HIR path for `[::crate_root]::b::c::d` and
158 /// resolves it based on `is_value`.
162 crate_root: Option<&str>,
169 enum ImplTraitContext<'a> {
170 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
171 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
172 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
174 /// Newly generated parameters should be inserted into the given `Vec`.
175 Universal(&'a mut Vec<hir::GenericParam>),
177 /// Treat `impl Trait` as shorthand for a new existential parameter.
178 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
179 /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
181 /// We optionally store a `DefId` for the parent item here so we can look up necessary
182 /// information later. It is `None` when no information about the context should be stored,
183 /// e.g., for consts and statics.
184 Existential(Option<DefId>),
186 /// `impl Trait` is not accepted in this position.
187 Disallowed(ImplTraitPosition),
190 /// Position in which `impl Trait` is disallowed. Used for error reporting.
191 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
192 enum ImplTraitPosition {
197 impl<'a> ImplTraitContext<'a> {
199 fn disallowed() -> Self {
200 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
203 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
204 use self::ImplTraitContext::*;
206 Universal(params) => Universal(params),
207 Existential(did) => Existential(*did),
208 Disallowed(pos) => Disallowed(*pos),
215 cstore: &dyn CrateStore,
216 dep_graph: &DepGraph,
218 resolver: &mut dyn Resolver,
220 // We're constructing the HIR here; we don't care what we will
221 // read, since we haven't even constructed the *input* to
223 dep_graph.assert_ignored();
226 crate_root: std_inject::injected_crate_name(),
230 items: BTreeMap::new(),
231 trait_items: BTreeMap::new(),
232 impl_items: BTreeMap::new(),
233 bodies: BTreeMap::new(),
234 trait_impls: BTreeMap::new(),
235 trait_auto_impl: BTreeMap::new(),
236 modules: BTreeMap::new(),
237 exported_macros: Vec::new(),
238 catch_scopes: Vec::new(),
239 loop_scopes: Vec::new(),
240 is_in_loop_condition: false,
241 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
242 type_def_lifetime_params: Default::default(),
243 current_module: CRATE_NODE_ID,
244 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
245 item_local_id_counters: Default::default(),
246 node_id_to_hir_id: IndexVec::new(),
248 is_in_trait_impl: false,
249 lifetimes_to_define: Vec::new(),
250 is_collecting_in_band_lifetimes: false,
251 in_scope_lifetimes: Vec::new(),
255 #[derive(Copy, Clone, PartialEq)]
257 /// Any path in a type context.
259 /// The `module::Type` in `module::Type::method` in an expression.
264 struct LoweredNodeId {
269 enum ParenthesizedGenericArgs {
275 /// What to do when we encounter an **anonymous** lifetime
276 /// reference. Anonymous lifetime references come in two flavors. You
277 /// have implicit, or fully elided, references to lifetimes, like the
278 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
279 /// or `Ref<'_, T>`. These often behave the same, but not always:
281 /// - certain usages of implicit references are deprecated, like
282 /// `Ref<T>`, and we sometimes just give hard errors in those cases
284 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
285 /// the same as `Box<dyn Foo + '_>`.
287 /// We describe the effects of the various modes in terms of three cases:
289 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
290 /// of a `&` (e.g., the missing lifetime in something like `&T`)
291 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
292 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
293 /// elided bounds follow special rules. Note that this only covers
294 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
295 /// '_>` is a case of "modern" elision.
296 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
297 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
298 /// non-deprecated equivalent.
300 /// Currently, the handling of lifetime elision is somewhat spread out
301 /// between HIR lowering and -- as described below -- the
302 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
303 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
304 /// everything into HIR lowering.
305 #[derive(Copy, Clone)]
306 enum AnonymousLifetimeMode {
307 /// For **Modern** cases, create a new anonymous region parameter
308 /// and reference that.
310 /// For **Dyn Bound** cases, pass responsibility to
311 /// `resolve_lifetime` code.
313 /// For **Deprecated** cases, report an error.
316 /// Give a hard error when either `&` or `'_` is written. Used to
317 /// rule out things like `where T: Foo<'_>`. Does not imply an
318 /// error on default object bounds (e.g., `Box<dyn Foo>`).
321 /// Pass responsibility to `resolve_lifetime` code for all cases.
325 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[hir::ItemId; 1]> }
327 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
328 fn visit_ty(&mut self, ty: &'a Ty) {
334 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
337 visit::walk_ty(self, ty);
340 fn visit_path_segment(
343 path_segment: &'v PathSegment,
345 if let Some(ref p) = path_segment.args {
346 if let GenericArgs::Parenthesized(_) = **p {
350 visit::walk_path_segment(self, path_span, path_segment)
354 impl<'a> LoweringContext<'a> {
355 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
356 /// Full-crate AST visitor that inserts into a fresh
357 /// `LoweringContext` any information that may be
358 /// needed from arbitrary locations in the crate,
359 /// e.g., the number of lifetime generic parameters
360 /// declared for every type and trait definition.
361 struct MiscCollector<'lcx, 'interner: 'lcx> {
362 lctx: &'lcx mut LoweringContext<'interner>,
365 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
366 fn visit_item(&mut self, item: &'lcx Item) {
367 self.lctx.allocate_hir_id_counter(item.id, item);
370 ItemKind::Struct(_, ref generics)
371 | ItemKind::Union(_, ref generics)
372 | ItemKind::Enum(_, ref generics)
373 | ItemKind::Ty(_, ref generics)
374 | ItemKind::Existential(_, ref generics)
375 | ItemKind::Trait(_, _, ref generics, ..) => {
376 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
380 .filter(|param| match param.kind {
381 ast::GenericParamKind::Lifetime { .. } => true,
385 self.lctx.type_def_lifetime_params.insert(def_id, count);
389 visit::walk_item(self, item);
392 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
393 self.lctx.allocate_hir_id_counter(item.id, item);
394 visit::walk_trait_item(self, item);
397 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
398 self.lctx.allocate_hir_id_counter(item.id, item);
399 visit::walk_impl_item(self, item);
403 struct ItemLowerer<'lcx, 'interner: 'lcx> {
404 lctx: &'lcx mut LoweringContext<'interner>,
407 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
408 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
410 F: FnOnce(&mut Self),
412 let old = self.lctx.is_in_trait_impl;
413 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
419 self.lctx.is_in_trait_impl = old;
423 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
424 fn visit_mod(&mut self, m: &'lcx Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
425 self.lctx.modules.insert(n, hir::ModuleItems {
426 items: BTreeSet::new(),
427 trait_items: BTreeSet::new(),
428 impl_items: BTreeSet::new(),
431 let old = self.lctx.current_module;
432 self.lctx.current_module = n;
433 visit::walk_mod(self, m);
434 self.lctx.current_module = old;
437 fn visit_item(&mut self, item: &'lcx Item) {
438 let mut item_lowered = true;
439 self.lctx.with_hir_id_owner(item.id, |lctx| {
440 if let Some(hir_item) = lctx.lower_item(item) {
441 lctx.insert_item(item.id, hir_item);
443 item_lowered = false;
448 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
449 hir::ItemKind::Impl(_, _, _, ref generics, ..)
450 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
451 generics.params.clone()
456 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
457 let this = &mut ItemLowerer { lctx: this };
458 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
459 this.with_trait_impl_ref(opt_trait_ref, |this| {
460 visit::walk_item(this, item)
463 visit::walk_item(this, item);
469 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
470 self.lctx.with_hir_id_owner(item.id, |lctx| {
471 let id = hir::TraitItemId { node_id: item.id };
472 let hir_item = lctx.lower_trait_item(item);
473 lctx.trait_items.insert(id, hir_item);
474 lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
477 visit::walk_trait_item(self, item);
480 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
481 self.lctx.with_hir_id_owner(item.id, |lctx| {
482 let id = hir::ImplItemId { node_id: item.id };
483 let hir_item = lctx.lower_impl_item(item);
484 lctx.impl_items.insert(id, hir_item);
485 lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
487 visit::walk_impl_item(self, item);
491 self.lower_node_id(CRATE_NODE_ID);
492 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
494 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
495 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
497 let module = self.lower_mod(&c.module);
498 let attrs = self.lower_attrs(&c.attrs);
499 let body_ids = body_ids(&self.bodies);
503 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
509 exported_macros: hir::HirVec::from(self.exported_macros),
511 trait_items: self.trait_items,
512 impl_items: self.impl_items,
515 trait_impls: self.trait_impls,
516 trait_auto_impl: self.trait_auto_impl,
517 modules: self.modules,
521 fn insert_item(&mut self, id: NodeId, item: hir::Item) {
522 self.items.insert(id, item);
523 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
526 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
527 if self.item_local_id_counters.insert(owner, 0).is_some() {
529 "Tried to allocate item_local_id_counter for {:?} twice",
533 // Always allocate the first `HirId` for the owner itself.
534 self.lower_node_id_with_owner(owner, owner)
537 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
539 F: FnOnce(&mut Self) -> hir::HirId,
541 if ast_node_id == DUMMY_NODE_ID {
542 return LoweredNodeId {
543 node_id: DUMMY_NODE_ID,
544 hir_id: hir::DUMMY_HIR_ID,
548 let min_size = ast_node_id.as_usize() + 1;
550 if min_size > self.node_id_to_hir_id.len() {
551 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
554 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
556 if existing_hir_id == hir::DUMMY_HIR_ID {
557 // Generate a new `HirId`.
558 let hir_id = alloc_hir_id(self);
559 self.node_id_to_hir_id[ast_node_id] = hir_id;
561 node_id: ast_node_id,
566 node_id: ast_node_id,
567 hir_id: existing_hir_id,
572 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
574 F: FnOnce(&mut Self) -> T,
576 let counter = self.item_local_id_counters
577 .insert(owner, HIR_ID_COUNTER_LOCKED)
578 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
579 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
580 self.current_hir_id_owner.push((def_index, counter));
582 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
584 debug_assert!(def_index == new_def_index);
585 debug_assert!(new_counter >= counter);
587 let prev = self.item_local_id_counters
588 .insert(owner, new_counter)
590 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
594 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
595 /// the `LoweringContext`'s `NodeId => HirId` map.
596 /// Take care not to call this method if the resulting `HirId` is then not
597 /// actually used in the HIR, as that would trigger an assertion in the
598 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
599 /// properly. Calling the method twice with the same `NodeId` is fine though.
600 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
601 self.lower_node_id_generic(ast_node_id, |this| {
602 let &mut (def_index, ref mut local_id_counter) =
603 this.current_hir_id_owner.last_mut().unwrap();
604 let local_id = *local_id_counter;
605 *local_id_counter += 1;
608 local_id: hir::ItemLocalId::from_u32(local_id),
613 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
614 self.lower_node_id_generic(ast_node_id, |this| {
615 let local_id_counter = this
616 .item_local_id_counters
618 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
619 let local_id = *local_id_counter;
621 // We want to be sure not to modify the counter in the map while it
622 // is also on the stack. Otherwise we'll get lost updates when writing
623 // back from the stack to the map.
624 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
626 *local_id_counter += 1;
630 .opt_def_index(owner)
631 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
632 that do not belong to the current owner");
636 local_id: hir::ItemLocalId::from_u32(local_id),
641 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
642 let body = hir::Body {
643 arguments: decl.map_or(hir_vec![], |decl| {
644 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
646 is_generator: self.is_generator,
650 self.bodies.insert(id, body);
654 fn next_id(&mut self) -> LoweredNodeId {
655 self.lower_node_id(self.sess.next_node_id())
658 fn expect_full_def(&mut self, id: NodeId) -> Def {
659 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
660 if pr.unresolved_segments() != 0 {
661 bug!("path not fully resolved: {:?}", pr);
667 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Def> {
668 self.resolver.get_import(id).present_items().map(|pr| {
669 if pr.unresolved_segments() != 0 {
670 bug!("path not fully resolved: {:?}", pr);
676 fn diagnostic(&self) -> &errors::Handler {
677 self.sess.diagnostic()
680 fn str_to_ident(&self, s: &'static str) -> Ident {
681 Ident::with_empty_ctxt(Symbol::gensym(s))
684 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
685 let mark = Mark::fresh(Mark::root());
686 mark.set_expn_info(source_map::ExpnInfo {
688 def_site: Some(span),
689 format: source_map::CompilerDesugaring(reason),
690 allow_internal_unstable: true,
691 allow_internal_unsafe: false,
692 local_inner_macros: false,
693 edition: source_map::hygiene::default_edition(),
695 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
698 fn with_anonymous_lifetime_mode<R>(
700 anonymous_lifetime_mode: AnonymousLifetimeMode,
701 op: impl FnOnce(&mut Self) -> R,
703 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
704 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
705 let result = op(self);
706 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
710 /// Creates a new hir::GenericParam for every new lifetime and
711 /// type parameter encountered while evaluating `f`. Definitions
712 /// are created with the parent provided. If no `parent_id` is
713 /// provided, no definitions will be returned.
715 /// Presuming that in-band lifetimes are enabled, then
716 /// `self.anonymous_lifetime_mode` will be updated to match the
717 /// argument while `f` is running (and restored afterwards).
718 fn collect_in_band_defs<T, F>(
721 anonymous_lifetime_mode: AnonymousLifetimeMode,
723 ) -> (Vec<hir::GenericParam>, T)
725 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
727 assert!(!self.is_collecting_in_band_lifetimes);
728 assert!(self.lifetimes_to_define.is_empty());
729 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
731 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
732 self.is_collecting_in_band_lifetimes = true;
734 let (in_band_ty_params, res) = f(self);
736 self.is_collecting_in_band_lifetimes = false;
737 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
739 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
741 let params = lifetimes_to_define
743 .map(|(span, hir_name)| {
744 let LoweredNodeId { node_id, hir_id } = self.next_id();
746 // Get the name we'll use to make the def-path. Note
747 // that collisions are ok here and this shouldn't
748 // really show up for end-user.
749 let (str_name, kind) = match hir_name {
750 ParamName::Plain(ident) => (
751 ident.as_interned_str(),
752 hir::LifetimeParamKind::InBand,
754 ParamName::Fresh(_) => (
755 keywords::UnderscoreLifetime.name().as_interned_str(),
756 hir::LifetimeParamKind::Elided,
758 ParamName::Error => (
759 keywords::UnderscoreLifetime.name().as_interned_str(),
760 hir::LifetimeParamKind::Error,
764 // Add a definition for the in-band lifetime def.
765 self.resolver.definitions().create_def_with_parent(
768 DefPathData::LifetimeParam(str_name),
769 DefIndexAddressSpace::High,
781 pure_wrt_drop: false,
782 kind: hir::GenericParamKind::Lifetime { kind }
785 .chain(in_band_ty_params.into_iter())
791 /// When there is a reference to some lifetime `'a`, and in-band
792 /// lifetimes are enabled, then we want to push that lifetime into
793 /// the vector of names to define later. In that case, it will get
794 /// added to the appropriate generics.
795 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
796 if !self.is_collecting_in_band_lifetimes {
800 if !self.sess.features_untracked().in_band_lifetimes {
804 if self.in_scope_lifetimes.contains(&ident.modern()) {
808 let hir_name = ParamName::Plain(ident);
810 if self.lifetimes_to_define.iter()
811 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
815 self.lifetimes_to_define.push((ident.span, hir_name));
818 /// When we have either an elided or `'_` lifetime in an impl
819 /// header, we convert it to an in-band lifetime.
820 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
821 assert!(self.is_collecting_in_band_lifetimes);
822 let index = self.lifetimes_to_define.len();
823 let hir_name = ParamName::Fresh(index);
824 self.lifetimes_to_define.push((span, hir_name));
828 // Evaluates `f` with the lifetimes in `params` in-scope.
829 // This is used to track which lifetimes have already been defined, and
830 // which are new in-band lifetimes that need to have a definition created
832 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
834 F: FnOnce(&mut LoweringContext<'_>) -> T,
836 let old_len = self.in_scope_lifetimes.len();
837 let lt_def_names = params.iter().filter_map(|param| match param.kind {
838 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
841 self.in_scope_lifetimes.extend(lt_def_names);
845 self.in_scope_lifetimes.truncate(old_len);
849 // Same as the method above, but accepts `hir::GenericParam`s
850 // instead of `ast::GenericParam`s.
851 // This should only be used with generics that have already had their
852 // in-band lifetimes added. In practice, this means that this function is
853 // only used when lowering a child item of a trait or impl.
854 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
855 params: &HirVec<hir::GenericParam>,
858 F: FnOnce(&mut LoweringContext<'_>) -> T,
860 let old_len = self.in_scope_lifetimes.len();
861 let lt_def_names = params.iter().filter_map(|param| match param.kind {
862 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
865 self.in_scope_lifetimes.extend(lt_def_names);
869 self.in_scope_lifetimes.truncate(old_len);
873 /// Appends in-band lifetime defs and argument-position `impl
874 /// Trait` defs to the existing set of generics.
876 /// Presuming that in-band lifetimes are enabled, then
877 /// `self.anonymous_lifetime_mode` will be updated to match the
878 /// argument while `f` is running (and restored afterwards).
879 fn add_in_band_defs<F, T>(
883 anonymous_lifetime_mode: AnonymousLifetimeMode,
885 ) -> (hir::Generics, T)
887 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
889 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
892 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
893 let mut params = Vec::new();
894 let generics = this.lower_generics(
896 ImplTraitContext::Universal(&mut params),
898 let res = f(this, &mut params);
899 (params, (generics, res))
904 lowered_generics.params = lowered_generics
911 (lowered_generics, res)
914 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
916 F: FnOnce(&mut LoweringContext<'_>) -> T,
918 let len = self.catch_scopes.len();
919 self.catch_scopes.push(catch_id);
921 let result = f(self);
924 self.catch_scopes.len(),
925 "catch scopes should be added and removed in stack order"
928 self.catch_scopes.pop().unwrap();
935 capture_clause: CaptureBy,
936 closure_node_id: NodeId,
938 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
940 let prev_is_generator = mem::replace(&mut self.is_generator, true);
941 let body_expr = body(self);
942 let span = body_expr.span;
943 let output = match ret_ty {
944 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
945 None => FunctionRetTy::Default(span),
952 let body_id = self.record_body(body_expr, Some(&decl));
953 self.is_generator = prev_is_generator;
955 let capture_clause = self.lower_capture_clause(capture_clause);
956 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
957 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
958 let generator = hir::Expr {
960 hir_id: closure_hir_id,
961 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
962 Some(hir::GeneratorMovability::Static)),
964 attrs: ThinVec::new(),
967 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
968 let gen_future = self.expr_std_path(
969 unstable_span, &["future", "from_generator"], None, ThinVec::new());
970 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
973 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
975 F: FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
977 let prev = mem::replace(&mut self.is_generator, false);
978 let result = f(self);
979 let r = self.record_body(result, decl);
980 self.is_generator = prev;
984 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
986 F: FnOnce(&mut LoweringContext<'_>) -> T,
988 // We're no longer in the base loop's condition; we're in another loop.
989 let was_in_loop_condition = self.is_in_loop_condition;
990 self.is_in_loop_condition = false;
992 let len = self.loop_scopes.len();
993 self.loop_scopes.push(loop_id);
995 let result = f(self);
998 self.loop_scopes.len(),
999 "Loop scopes should be added and removed in stack order"
1002 self.loop_scopes.pop().unwrap();
1004 self.is_in_loop_condition = was_in_loop_condition;
1009 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
1011 F: FnOnce(&mut LoweringContext<'_>) -> T,
1013 let was_in_loop_condition = self.is_in_loop_condition;
1014 self.is_in_loop_condition = true;
1016 let result = f(self);
1018 self.is_in_loop_condition = was_in_loop_condition;
1023 fn with_new_scopes<T, F>(&mut self, f: F) -> T
1025 F: FnOnce(&mut LoweringContext<'_>) -> T,
1027 let was_in_loop_condition = self.is_in_loop_condition;
1028 self.is_in_loop_condition = false;
1030 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
1031 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
1033 self.catch_scopes = catch_scopes;
1034 self.loop_scopes = loop_scopes;
1036 self.is_in_loop_condition = was_in_loop_condition;
1041 fn def_key(&mut self, id: DefId) -> DefKey {
1043 self.resolver.definitions().def_key(id.index)
1045 self.cstore.def_key(id)
1049 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1050 label.map(|label| hir::Label {
1055 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1056 let target_id = match destination {
1058 if let Def::Label(loop_id) = self.expect_full_def(id) {
1059 Ok(self.lower_node_id(loop_id).node_id)
1061 Err(hir::LoopIdError::UnresolvedLabel)
1068 .map(|id| Ok(self.lower_node_id(id).node_id))
1069 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1074 label: self.lower_label(destination.map(|(_, label)| label)),
1079 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1082 .map(|a| self.lower_attr(a))
1086 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1087 // Note that we explicitly do not walk the path. Since we don't really
1088 // lower attributes (we use the AST version) there is nowhere to keep
1089 // the `HirId`s. We don't actually need HIR version of attributes anyway.
1093 path: attr.path.clone(),
1094 tokens: self.lower_token_stream(attr.tokens.clone()),
1095 is_sugared_doc: attr.is_sugared_doc,
1100 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1103 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1107 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1109 TokenTree::Token(span, token) => self.lower_token(token, span),
1110 TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1113 self.lower_token_stream(tts.into()).into(),
1118 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1120 Token::Interpolated(_) => {}
1121 other => return TokenTree::Token(span, other).into(),
1124 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1125 self.lower_token_stream(tts)
1128 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1130 attrs: self.lower_attrs(&arm.attrs),
1131 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1132 guard: match arm.guard {
1133 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1136 body: P(self.lower_expr(&arm.body)),
1140 fn lower_ty_binding(&mut self, b: &TypeBinding,
1141 itctx: ImplTraitContext<'_>) -> hir::TypeBinding {
1142 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
1148 ty: self.lower_ty(&b.ty, itctx),
1153 fn lower_generic_arg(&mut self,
1154 arg: &ast::GenericArg,
1155 itctx: ImplTraitContext<'_>)
1156 -> hir::GenericArg {
1158 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1159 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1163 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1164 P(self.lower_ty_direct(t, itctx))
1167 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1168 let kind = match t.node {
1169 TyKind::Infer => hir::TyKind::Infer,
1170 TyKind::Err => hir::TyKind::Err,
1171 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1172 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1173 TyKind::Rptr(ref region, ref mt) => {
1174 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1175 let lifetime = match *region {
1176 Some(ref lt) => self.lower_lifetime(lt),
1177 None => self.elided_ref_lifetime(span),
1179 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1181 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1184 this.with_anonymous_lifetime_mode(
1185 AnonymousLifetimeMode::PassThrough,
1187 hir::TyKind::BareFn(P(hir::BareFnTy {
1188 generic_params: this.lower_generic_params(
1190 &NodeMap::default(),
1191 ImplTraitContext::disallowed(),
1193 unsafety: this.lower_unsafety(f.unsafety),
1195 decl: this.lower_fn_decl(&f.decl, None, false, None),
1196 arg_names: this.lower_fn_args_to_names(&f.decl),
1202 TyKind::Never => hir::TyKind::Never,
1203 TyKind::Tup(ref tys) => {
1204 hir::TyKind::Tup(tys.iter().map(|ty| {
1205 self.lower_ty_direct(ty, itctx.reborrow())
1208 TyKind::Paren(ref ty) => {
1209 return self.lower_ty_direct(ty, itctx);
1211 TyKind::Path(ref qself, ref path) => {
1212 let id = self.lower_node_id(t.id);
1213 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1214 let ty = self.ty_path(id, t.span, qpath);
1215 if let hir::TyKind::TraitObject(..) = ty.node {
1216 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1220 TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1223 def: self.expect_full_def(t.id),
1224 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfUpper.ident())],
1228 TyKind::Array(ref ty, ref length) => {
1229 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1231 TyKind::Typeof(ref expr) => {
1232 hir::TyKind::Typeof(self.lower_anon_const(expr))
1234 TyKind::TraitObject(ref bounds, kind) => {
1235 let mut lifetime_bound = None;
1238 .filter_map(|bound| match *bound {
1239 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1240 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1242 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1243 GenericBound::Outlives(ref lifetime) => {
1244 if lifetime_bound.is_none() {
1245 lifetime_bound = Some(self.lower_lifetime(lifetime));
1251 let lifetime_bound =
1252 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1253 if kind != TraitObjectSyntax::Dyn {
1254 self.maybe_lint_bare_trait(t.span, t.id, false);
1256 hir::TyKind::TraitObject(bounds, lifetime_bound)
1258 TyKind::ImplTrait(def_node_id, ref bounds) => {
1261 ImplTraitContext::Existential(fn_def_id) => {
1262 self.lower_existential_impl_trait(
1263 span, fn_def_id, def_node_id,
1264 |this| this.lower_param_bounds(bounds, itctx),
1267 ImplTraitContext::Universal(in_band_ty_params) => {
1268 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(def_node_id);
1269 // Add a definition for the in-band `Param`.
1270 let def_index = self
1273 .opt_def_index(def_node_id)
1276 let hir_bounds = self.lower_param_bounds(
1278 ImplTraitContext::Universal(in_band_ty_params),
1280 // Set the name to `impl Bound1 + Bound2`.
1281 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1282 in_band_ty_params.push(hir::GenericParam {
1285 name: ParamName::Plain(ident),
1286 pure_wrt_drop: false,
1290 kind: hir::GenericParamKind::Type {
1292 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1296 hir::TyKind::Path(hir::QPath::Resolved(
1300 def: Def::TyParam(DefId::local(def_index)),
1301 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1305 ImplTraitContext::Disallowed(pos) => {
1306 let allowed_in = if self.sess.features_untracked()
1307 .impl_trait_in_bindings {
1308 "bindings or function and inherent method return types"
1310 "function and inherent method return types"
1312 let mut err = struct_span_err!(
1316 "`impl Trait` not allowed outside of {}",
1319 if pos == ImplTraitPosition::Binding &&
1320 nightly_options::is_nightly_build() {
1322 "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1330 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1333 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1342 fn lower_existential_impl_trait(
1345 fn_def_id: Option<DefId>,
1346 exist_ty_node_id: NodeId,
1347 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1349 // Make sure we know that some funky desugaring has been going on here.
1350 // This is a first: there is code in other places like for loop
1351 // desugaring that explicitly states that we don't want to track that.
1352 // Not tracking it makes lints in rustc and clippy very fragile as
1353 // frequently opened issues show.
1354 let exist_ty_span = self.allow_internal_unstable(
1355 CompilerDesugaringKind::ExistentialReturnType,
1359 let exist_ty_def_index = self
1362 .opt_def_index(exist_ty_node_id)
1365 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1367 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1369 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1375 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1376 let LoweredNodeId { node_id, hir_id } = lctx.next_id();
1377 let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1378 generics: hir::Generics {
1379 params: lifetime_defs,
1380 where_clause: hir::WhereClause {
1383 predicates: Vec::new().into(),
1388 impl_trait_fn: fn_def_id,
1390 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1391 // Generate an `existential type Foo: Trait;` declaration.
1392 trace!("creating existential type with id {:#?}", exist_ty_id);
1394 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1395 let exist_ty_item = hir::Item {
1396 id: exist_ty_id.node_id,
1397 hir_id: exist_ty_id.hir_id,
1398 ident: keywords::Invalid.ident(),
1399 attrs: Default::default(),
1400 node: exist_ty_item_kind,
1401 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1402 span: exist_ty_span,
1405 // Insert the item into the global list. This usually happens
1406 // automatically for all AST items. But this existential type item
1407 // does not actually exist in the AST.
1408 lctx.insert_item(exist_ty_id.node_id, exist_ty_item);
1410 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1411 hir::TyKind::Def(hir::ItemId { id: exist_ty_id.node_id }, lifetimes)
1415 fn lifetimes_from_impl_trait_bounds(
1417 exist_ty_id: NodeId,
1418 parent_index: DefIndex,
1419 bounds: &hir::GenericBounds,
1420 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1421 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1422 // appear in the bounds, excluding lifetimes that are created within the bounds.
1423 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1424 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1425 context: &'r mut LoweringContext<'a>,
1427 exist_ty_id: NodeId,
1428 collect_elided_lifetimes: bool,
1429 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1430 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1431 output_lifetimes: Vec<hir::GenericArg>,
1432 output_lifetime_params: Vec<hir::GenericParam>,
1435 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1436 fn nested_visit_map<'this>(
1438 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1439 hir::intravisit::NestedVisitorMap::None
1442 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1443 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1444 if parameters.parenthesized {
1445 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1446 self.collect_elided_lifetimes = false;
1447 hir::intravisit::walk_generic_args(self, span, parameters);
1448 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1450 hir::intravisit::walk_generic_args(self, span, parameters);
1454 fn visit_ty(&mut self, t: &'v hir::Ty) {
1455 // Don't collect elided lifetimes used inside of `fn()` syntax.
1456 if let hir::TyKind::BareFn(_) = t.node {
1457 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1458 self.collect_elided_lifetimes = false;
1460 // Record the "stack height" of `for<'a>` lifetime bindings
1461 // to be able to later fully undo their introduction.
1462 let old_len = self.currently_bound_lifetimes.len();
1463 hir::intravisit::walk_ty(self, t);
1464 self.currently_bound_lifetimes.truncate(old_len);
1466 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1468 hir::intravisit::walk_ty(self, t)
1472 fn visit_poly_trait_ref(
1474 trait_ref: &'v hir::PolyTraitRef,
1475 modifier: hir::TraitBoundModifier,
1477 // Record the "stack height" of `for<'a>` lifetime bindings
1478 // to be able to later fully undo their introduction.
1479 let old_len = self.currently_bound_lifetimes.len();
1480 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1481 self.currently_bound_lifetimes.truncate(old_len);
1484 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1485 // Record the introduction of 'a in `for<'a> ...`.
1486 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1487 // Introduce lifetimes one at a time so that we can handle
1488 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1489 let lt_name = hir::LifetimeName::Param(param.name);
1490 self.currently_bound_lifetimes.push(lt_name);
1493 hir::intravisit::walk_generic_param(self, param);
1496 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1497 let name = match lifetime.name {
1498 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1499 if self.collect_elided_lifetimes {
1500 // Use `'_` for both implicit and underscore lifetimes in
1501 // `abstract type Foo<'_>: SomeTrait<'_>;`.
1502 hir::LifetimeName::Underscore
1507 hir::LifetimeName::Param(_) => lifetime.name,
1508 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1511 if !self.currently_bound_lifetimes.contains(&name)
1512 && !self.already_defined_lifetimes.contains(&name) {
1513 self.already_defined_lifetimes.insert(name);
1515 let LoweredNodeId { node_id, hir_id } = self.context.next_id();
1516 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1519 span: lifetime.span,
1523 // We need to manually create the ids here, because the
1524 // definitions will go into the explicit `existential type`
1525 // declaration and thus need to have their owner set to that item
1526 let def_node_id = self.context.sess.next_node_id();
1527 let LoweredNodeId { node_id: _, hir_id } =
1528 self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1529 self.context.resolver.definitions().create_def_with_parent(
1532 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1533 DefIndexAddressSpace::High,
1538 let (name, kind) = match name {
1539 hir::LifetimeName::Underscore => (
1540 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident()),
1541 hir::LifetimeParamKind::Elided,
1543 hir::LifetimeName::Param(param_name) => (
1545 hir::LifetimeParamKind::Explicit,
1547 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1550 self.output_lifetime_params.push(hir::GenericParam {
1554 span: lifetime.span,
1555 pure_wrt_drop: false,
1558 kind: hir::GenericParamKind::Lifetime { kind }
1564 let mut lifetime_collector = ImplTraitLifetimeCollector {
1566 parent: parent_index,
1568 collect_elided_lifetimes: true,
1569 currently_bound_lifetimes: Vec::new(),
1570 already_defined_lifetimes: FxHashSet::default(),
1571 output_lifetimes: Vec::new(),
1572 output_lifetime_params: Vec::new(),
1575 for bound in bounds {
1576 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1580 lifetime_collector.output_lifetimes.into(),
1581 lifetime_collector.output_lifetime_params.into(),
1585 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1590 .map(|x| self.lower_foreign_item(x))
1595 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1602 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1604 node: hir::VariantKind {
1605 ident: v.node.ident,
1606 attrs: self.lower_attrs(&v.node.attrs),
1607 data: self.lower_variant_data(&v.node.data),
1608 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1617 qself: &Option<QSelf>,
1619 param_mode: ParamMode,
1620 mut itctx: ImplTraitContext<'_>,
1622 let qself_position = qself.as_ref().map(|q| q.position);
1623 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1625 let resolution = self.resolver
1627 .unwrap_or_else(|| PathResolution::new(Def::Err));
1629 let proj_start = p.segments.len() - resolution.unresolved_segments();
1630 let path = P(hir::Path {
1631 def: resolution.base_def(),
1632 segments: p.segments[..proj_start]
1635 .map(|(i, segment)| {
1636 let param_mode = match (qself_position, param_mode) {
1637 (Some(j), ParamMode::Optional) if i < j => {
1638 // This segment is part of the trait path in a
1639 // qualified path - one of `a`, `b` or `Trait`
1640 // in `<X as a::b::Trait>::T::U::method`.
1646 // Figure out if this is a type/trait segment,
1647 // which may need lifetime elision performed.
1648 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1649 krate: def_id.krate,
1650 index: this.def_key(def_id).parent.expect("missing parent"),
1652 let type_def_id = match resolution.base_def() {
1653 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1654 Some(parent_def_id(self, def_id))
1656 Def::Variant(def_id) if i + 1 == proj_start => {
1657 Some(parent_def_id(self, def_id))
1660 | Def::Union(def_id)
1662 | Def::TyAlias(def_id)
1663 | Def::Trait(def_id) if i + 1 == proj_start =>
1669 let parenthesized_generic_args = match resolution.base_def() {
1670 // `a::b::Trait(Args)`
1671 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1672 // `a::b::Trait(Args)::TraitItem`
1673 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1674 if i + 2 == proj_start =>
1676 ParenthesizedGenericArgs::Ok
1678 // Avoid duplicated errors.
1679 Def::Err => ParenthesizedGenericArgs::Ok,
1685 | Def::Variant(..) if i + 1 == proj_start =>
1687 ParenthesizedGenericArgs::Err
1689 // A warning for now, for compatibility reasons
1690 _ => ParenthesizedGenericArgs::Warn,
1693 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1694 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1697 assert!(!def_id.is_local());
1699 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1700 let n = item_generics.own_counts().lifetimes;
1701 self.type_def_lifetime_params.insert(def_id, n);
1704 self.lower_path_segment(
1709 parenthesized_generic_args,
1718 // Simple case, either no projections, or only fully-qualified.
1719 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
1720 if resolution.unresolved_segments() == 0 {
1721 return hir::QPath::Resolved(qself, path);
1724 // Create the innermost type that we're projecting from.
1725 let mut ty = if path.segments.is_empty() {
1726 // If the base path is empty that means there exists a
1727 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
1728 qself.expect("missing QSelf for <T>::...")
1730 // Otherwise, the base path is an implicit `Self` type path,
1731 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1732 // `<I as Iterator>::Item::default`.
1733 let new_id = self.next_id();
1734 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1737 // Anything after the base path are associated "extensions",
1738 // out of which all but the last one are associated types,
1739 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1740 // * base path is `std::vec::Vec<T>`
1741 // * "extensions" are `IntoIter`, `Item` and `clone`
1742 // * type nodes are:
1743 // 1. `std::vec::Vec<T>` (created above)
1744 // 2. `<std::vec::Vec<T>>::IntoIter`
1745 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1746 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1747 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1748 let segment = P(self.lower_path_segment(
1753 ParenthesizedGenericArgs::Warn,
1757 let qpath = hir::QPath::TypeRelative(ty, segment);
1759 // It's finished, return the extension of the right node type.
1760 if i == p.segments.len() - 1 {
1764 // Wrap the associated extension in another type node.
1765 let new_id = self.next_id();
1766 ty = P(self.ty_path(new_id, p.span, qpath));
1769 // We should've returned in the for loop above.
1772 "lower_qpath: no final extension segment in {}..{}",
1778 fn lower_path_extra(
1782 param_mode: ParamMode,
1783 explicit_owner: Option<NodeId>,
1787 segments: p.segments
1790 self.lower_path_segment(
1795 ParenthesizedGenericArgs::Err,
1796 ImplTraitContext::disallowed(),
1805 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1806 let def = self.expect_full_def(id);
1807 self.lower_path_extra(def, p, param_mode, None)
1810 fn lower_path_segment(
1813 segment: &PathSegment,
1814 param_mode: ParamMode,
1815 expected_lifetimes: usize,
1816 parenthesized_generic_args: ParenthesizedGenericArgs,
1817 itctx: ImplTraitContext<'_>,
1818 explicit_owner: Option<NodeId>,
1819 ) -> hir::PathSegment {
1820 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1821 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
1822 match **generic_args {
1823 GenericArgs::AngleBracketed(ref data) => {
1824 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1826 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1827 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1828 ParenthesizedGenericArgs::Warn => {
1829 self.sess.buffer_lint(
1830 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1835 (hir::GenericArgs::none(), true)
1837 ParenthesizedGenericArgs::Err => {
1838 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
1839 err.span_label(data.span, "only `Fn` traits may use parentheses");
1840 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
1841 // Do not suggest going from `Trait()` to `Trait<>`
1842 if data.inputs.len() > 0 {
1843 err.span_suggestion(
1845 "use angle brackets instead",
1846 format!("<{}>", &snippet[1..snippet.len() - 1]),
1847 Applicability::MaybeIncorrect,
1852 (self.lower_angle_bracketed_parameter_data(
1853 &data.as_angle_bracketed_args(),
1861 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1864 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1865 GenericArg::Lifetime(_) => true,
1868 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1869 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1870 if !generic_args.parenthesized && !has_lifetimes {
1872 self.elided_path_lifetimes(path_span, expected_lifetimes)
1874 .map(|lt| GenericArg::Lifetime(lt))
1875 .chain(generic_args.args.into_iter())
1877 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1878 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1879 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1880 let no_bindings = generic_args.bindings.is_empty();
1881 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1882 // If there are no (non-implicit) generic args or associated-type
1883 // bindings, our suggestion includes the angle brackets.
1884 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1886 // Otherwise—sorry, this is kind of gross—we need to infer the
1887 // place to splice in the `'_, ` from the generics that do exist.
1888 let first_generic_span = first_generic_span
1889 .expect("already checked that type args or bindings exist");
1890 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1892 self.sess.buffer_lint_with_diagnostic(
1893 ELIDED_LIFETIMES_IN_PATHS,
1896 "hidden lifetime parameters in types are deprecated",
1897 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1898 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1904 let def = self.expect_full_def(segment.id);
1905 let id = if let Some(owner) = explicit_owner {
1906 self.lower_node_id_with_owner(segment.id, owner)
1908 self.lower_node_id(segment.id)
1911 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
1912 segment.ident, segment.id, id,
1915 hir::PathSegment::new(
1925 fn lower_angle_bracketed_parameter_data(
1927 data: &AngleBracketedArgs,
1928 param_mode: ParamMode,
1929 mut itctx: ImplTraitContext<'_>,
1930 ) -> (hir::GenericArgs, bool) {
1931 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1932 let has_types = args.iter().any(|arg| match arg {
1933 ast::GenericArg::Type(_) => true,
1937 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1938 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1939 parenthesized: false,
1941 !has_types && param_mode == ParamMode::Optional)
1944 fn lower_parenthesized_parameter_data(
1946 data: &ParenthesizedArgs,
1947 ) -> (hir::GenericArgs, bool) {
1948 // Switch to `PassThrough` mode for anonymous lifetimes: this
1949 // means that we permit things like `&Ref<T>`, where `Ref` has
1950 // a hidden lifetime parameter. This is needed for backwards
1951 // compatibility, even in contexts like an impl header where
1952 // we generally don't permit such things (see #51008).
1953 self.with_anonymous_lifetime_mode(
1954 AnonymousLifetimeMode::PassThrough,
1956 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
1959 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
1961 let mk_tup = |this: &mut Self, tys, span| {
1962 let LoweredNodeId { node_id, hir_id } = this.next_id();
1963 hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1965 let LoweredNodeId { node_id, hir_id } = this.next_id();
1969 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1974 ident: Ident::from_str(FN_OUTPUT_NAME),
1977 .map(|ty| this.lower_ty(&ty, ImplTraitContext::disallowed()))
1978 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1979 span: output.as_ref().map_or(span, |ty| ty.span),
1982 parenthesized: true,
1990 fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[hir::ItemId; 1]>) {
1991 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1992 let mut ids = SmallVec::<[hir::ItemId; 1]>::new();
1993 if self.sess.features_untracked().impl_trait_in_bindings {
1994 if let Some(ref ty) = l.ty {
1995 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
1996 visitor.visit_ty(ty);
1999 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2005 .map(|t| self.lower_ty(t,
2006 if self.sess.features_untracked().impl_trait_in_bindings {
2007 ImplTraitContext::Existential(Some(parent_def_id))
2009 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2012 pat: self.lower_pat(&l.pat),
2013 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2015 attrs: l.attrs.clone(),
2016 source: hir::LocalSource::Normal,
2020 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
2022 Mutability::Mutable => hir::MutMutable,
2023 Mutability::Immutable => hir::MutImmutable,
2027 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
2028 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
2032 pat: self.lower_pat(&arg.pat),
2036 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2039 .map(|arg| match arg.pat.node {
2040 PatKind::Ident(_, ident, _) => ident,
2041 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
2046 // Lowers a function declaration.
2048 // decl: the unlowered (ast) function declaration.
2049 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
2050 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2051 // make_ret_async is also `Some`.
2052 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
2053 // This guards against trait declarations and implementations where impl Trait is
2055 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2056 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
2057 // return type impl Trait item.
2061 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2062 impl_trait_return_allow: bool,
2063 make_ret_async: Option<NodeId>,
2064 ) -> P<hir::FnDecl> {
2065 let inputs = decl.inputs
2068 if let Some((_, ref mut ibty)) = in_band_ty_params {
2069 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2071 self.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2074 .collect::<HirVec<_>>();
2076 let output = if let Some(ret_id) = make_ret_async {
2077 self.lower_async_fn_ret_ty(
2080 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
2085 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2086 Some((def_id, _)) if impl_trait_return_allow => {
2087 hir::Return(self.lower_ty(ty,
2088 ImplTraitContext::Existential(Some(def_id))))
2091 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2094 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2101 variadic: decl.variadic,
2102 implicit_self: decl.inputs.get(0).map_or(
2103 hir::ImplicitSelfKind::None,
2105 let is_mutable_pat = match arg.pat.node {
2106 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2107 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2108 mt == Mutability::Mutable,
2113 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2114 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2115 // Given we are only considering `ImplicitSelf` types, we needn't consider
2116 // the case where we have a mutable pattern to a reference as that would
2117 // no longer be an `ImplicitSelf`.
2118 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2119 mt.mutbl == ast::Mutability::Mutable =>
2120 hir::ImplicitSelfKind::MutRef,
2121 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2122 hir::ImplicitSelfKind::ImmRef,
2123 _ => hir::ImplicitSelfKind::None,
2130 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
2132 // fn_span: the span of the async function declaration. Used for error reporting.
2133 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
2134 // output: unlowered output type (`T` in `-> T`)
2135 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
2136 fn lower_async_fn_ret_ty(
2139 output: &FunctionRetTy,
2141 return_impl_trait_id: NodeId,
2142 ) -> hir::FunctionRetTy {
2143 // Get lifetimes used in the input arguments to the function. Our output type must also
2144 // have the same lifetime.
2145 // FIXME(cramertj): multiple different lifetimes are not allowed because
2146 // `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither is a subset
2147 // of the other. We really want some new lifetime that is a subset of all input lifetimes,
2148 // but that doesn't exist at the moment.
2150 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
2151 context: &'r mut LoweringContext<'a>,
2152 // Lifetimes bound by HRTB.
2153 currently_bound_lifetimes: Vec<hir::LifetimeName>,
2154 // Whether to count elided lifetimes.
2155 // Disabled inside of `Fn` or `fn` syntax.
2156 collect_elided_lifetimes: bool,
2157 // The lifetime found.
2158 // Multiple different or elided lifetimes cannot appear in async fn for now.
2159 output_lifetime: Option<(hir::LifetimeName, Span)>,
2162 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
2163 fn nested_visit_map<'this>(
2165 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
2166 hir::intravisit::NestedVisitorMap::None
2169 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
2170 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2171 if parameters.parenthesized {
2172 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2173 self.collect_elided_lifetimes = false;
2174 hir::intravisit::walk_generic_args(self, span, parameters);
2175 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2177 hir::intravisit::walk_generic_args(self, span, parameters);
2181 fn visit_ty(&mut self, t: &'v hir::Ty) {
2182 // Don't collect elided lifetimes used inside of `fn()` syntax.
2183 if let &hir::TyKind::BareFn(_) = &t.node {
2184 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2185 self.collect_elided_lifetimes = false;
2187 // Record the "stack height" of `for<'a>` lifetime bindings
2188 // to be able to later fully undo their introduction.
2189 let old_len = self.currently_bound_lifetimes.len();
2190 hir::intravisit::walk_ty(self, t);
2191 self.currently_bound_lifetimes.truncate(old_len);
2193 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2195 hir::intravisit::walk_ty(self, t);
2199 fn visit_poly_trait_ref(
2201 trait_ref: &'v hir::PolyTraitRef,
2202 modifier: hir::TraitBoundModifier,
2204 // Record the "stack height" of `for<'a>` lifetime bindings
2205 // to be able to later fully undo their introduction.
2206 let old_len = self.currently_bound_lifetimes.len();
2207 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2208 self.currently_bound_lifetimes.truncate(old_len);
2211 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2212 // Record the introduction of 'a in `for<'a> ...`
2213 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2214 // Introduce lifetimes one at a time so that we can handle
2215 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2216 let lt_name = hir::LifetimeName::Param(param.name);
2217 self.currently_bound_lifetimes.push(lt_name);
2220 hir::intravisit::walk_generic_param(self, param);
2223 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2224 let name = match lifetime.name {
2225 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2226 if self.collect_elided_lifetimes {
2227 // Use `'_` for both implicit and underscore lifetimes in
2228 // `abstract type Foo<'_>: SomeTrait<'_>;`
2229 hir::LifetimeName::Underscore
2234 hir::LifetimeName::Param(_) => lifetime.name,
2235 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
2238 if !self.currently_bound_lifetimes.contains(&name) {
2239 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2240 // We don't currently have a reliable way to desugar `async fn` with
2241 // multiple potentially unrelated input lifetimes into
2242 // `-> impl Trait + 'lt`, so we report an error in this case.
2243 if current_lt_name != name {
2246 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2248 "multiple different lifetimes used in arguments of `async fn`",
2250 .span_label(current_lt_span, "first lifetime here")
2251 .span_label(lifetime.span, "different lifetime here")
2252 .help("`async fn` can only accept borrowed values \
2253 with identical lifetimes")
2255 } else if current_lt_name.is_elided() && name.is_elided() {
2258 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2260 "multiple elided lifetimes used in arguments of `async fn`",
2262 .span_label(current_lt_span, "first lifetime here")
2263 .span_label(lifetime.span, "different lifetime here")
2264 .help("consider giving these arguments named lifetimes")
2268 self.output_lifetime = Some((name, lifetime.span));
2274 let bound_lifetime = {
2275 let mut lifetime_collector = AsyncFnLifetimeCollector {
2277 currently_bound_lifetimes: Vec::new(),
2278 collect_elided_lifetimes: true,
2279 output_lifetime: None,
2283 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2285 lifetime_collector.output_lifetime
2288 let span = match output {
2289 FunctionRetTy::Ty(ty) => ty.span,
2290 FunctionRetTy::Default(span) => *span,
2293 let impl_trait_ty = self.lower_existential_impl_trait(
2294 span, Some(fn_def_id), return_impl_trait_id, |this| {
2295 let output_ty = match output {
2296 FunctionRetTy::Ty(ty) => {
2297 this.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2299 FunctionRetTy::Default(span) => {
2300 let LoweredNodeId { node_id, hir_id } = this.next_id();
2304 node: hir::TyKind::Tup(hir_vec![]),
2311 let LoweredNodeId { node_id, hir_id } = this.next_id();
2312 let future_params = P(hir::GenericArgs {
2314 bindings: hir_vec![hir::TypeBinding {
2315 ident: Ident::from_str(FN_OUTPUT_NAME),
2321 parenthesized: false,
2325 this.std_path(span, &["future", "Future"], Some(future_params), false);
2327 let LoweredNodeId { node_id, hir_id } = this.next_id();
2328 let mut bounds = vec![
2329 hir::GenericBound::Trait(
2331 trait_ref: hir::TraitRef {
2336 bound_generic_params: hir_vec![],
2339 hir::TraitBoundModifier::None
2343 if let Some((name, span)) = bound_lifetime {
2344 let LoweredNodeId { node_id, hir_id } = this.next_id();
2345 bounds.push(hir::GenericBound::Outlives(
2346 hir::Lifetime { id: node_id, hir_id, name, span }));
2349 hir::HirVec::from(bounds)
2352 let LoweredNodeId { node_id, hir_id } = self.next_id();
2353 let impl_trait_ty = P(hir::Ty {
2355 node: impl_trait_ty,
2360 hir::FunctionRetTy::Return(impl_trait_ty)
2363 fn lower_param_bound(
2366 itctx: ImplTraitContext<'_>,
2367 ) -> hir::GenericBound {
2369 GenericBound::Trait(ref ty, modifier) => {
2370 hir::GenericBound::Trait(
2371 self.lower_poly_trait_ref(ty, itctx),
2372 self.lower_trait_bound_modifier(modifier),
2375 GenericBound::Outlives(ref lifetime) => {
2376 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2381 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2382 let span = l.ident.span;
2384 ident if ident.name == keywords::StaticLifetime.name() =>
2385 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2386 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2387 match self.anonymous_lifetime_mode {
2388 AnonymousLifetimeMode::CreateParameter => {
2389 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2390 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2393 AnonymousLifetimeMode::PassThrough => {
2394 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2397 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2400 self.maybe_collect_in_band_lifetime(ident);
2401 let param_name = ParamName::Plain(ident);
2402 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2407 fn new_named_lifetime(
2411 name: hir::LifetimeName,
2412 ) -> hir::Lifetime {
2413 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(id);
2423 fn lower_generic_params(
2425 params: &[GenericParam],
2426 add_bounds: &NodeMap<Vec<GenericBound>>,
2427 mut itctx: ImplTraitContext<'_>,
2428 ) -> hir::HirVec<hir::GenericParam> {
2429 params.iter().map(|param| {
2430 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2434 fn lower_generic_param(&mut self,
2435 param: &GenericParam,
2436 add_bounds: &NodeMap<Vec<GenericBound>>,
2437 mut itctx: ImplTraitContext<'_>)
2438 -> hir::GenericParam {
2439 let mut bounds = self.with_anonymous_lifetime_mode(
2440 AnonymousLifetimeMode::ReportError,
2441 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2445 GenericParamKind::Lifetime => {
2446 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2447 self.is_collecting_in_band_lifetimes = false;
2449 let lt = self.with_anonymous_lifetime_mode(
2450 AnonymousLifetimeMode::ReportError,
2451 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2453 let param_name = match lt.name {
2454 hir::LifetimeName::Param(param_name) => param_name,
2455 hir::LifetimeName::Implicit
2456 | hir::LifetimeName::Underscore
2457 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2458 hir::LifetimeName::Error => ParamName::Error,
2460 let param = hir::GenericParam {
2465 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2466 attrs: self.lower_attrs(¶m.attrs),
2468 kind: hir::GenericParamKind::Lifetime {
2469 kind: hir::LifetimeParamKind::Explicit,
2473 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2477 GenericParamKind::Type { ref default, .. } => {
2478 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2479 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2480 // Instead, use `gensym("Self")` to create a distinct name that looks the same.
2481 let ident = if param.ident.name == keywords::SelfUpper.name() {
2482 param.ident.gensym()
2487 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2488 if !add_bounds.is_empty() {
2489 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2490 bounds = bounds.into_iter()
2494 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(param.id);
2499 name: hir::ParamName::Plain(ident),
2500 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2501 attrs: self.lower_attrs(¶m.attrs),
2504 kind: hir::GenericParamKind::Type {
2505 default: default.as_ref().map(|x| {
2506 self.lower_ty(x, ImplTraitContext::disallowed())
2508 synthetic: param.attrs.iter()
2509 .filter(|attr| attr.check_name("rustc_synthetic"))
2510 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2520 generics: &Generics,
2521 itctx: ImplTraitContext<'_>)
2524 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2525 // FIXME: this could probably be done with less rightward drift. Also looks like two control
2526 // paths where report_error is called are also the only paths that advance to after
2527 // the match statement, so the error reporting could probably just be moved there.
2528 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
2529 for pred in &generics.where_clause.predicates {
2530 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2531 'next_bound: for bound in &bound_pred.bounds {
2532 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2533 let report_error = |this: &mut Self| {
2534 this.diagnostic().span_err(
2535 bound_pred.bounded_ty.span,
2536 "`?Trait` bounds are only permitted at the \
2537 point where a type parameter is declared",
2540 // Check if the where clause type is a plain type parameter.
2541 match bound_pred.bounded_ty.node {
2542 TyKind::Path(None, ref path)
2543 if path.segments.len() == 1
2544 && bound_pred.bound_generic_params.is_empty() =>
2546 if let Some(Def::TyParam(def_id)) = self.resolver
2547 .get_resolution(bound_pred.bounded_ty.id)
2548 .map(|d| d.base_def())
2550 if let Some(node_id) =
2551 self.resolver.definitions().as_local_node_id(def_id)
2553 for param in &generics.params {
2555 GenericParamKind::Type { .. } => {
2556 if node_id == param.id {
2557 add_bounds.entry(param.id)
2559 .push(bound.clone());
2560 continue 'next_bound;
2570 _ => report_error(self),
2578 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2579 where_clause: self.lower_where_clause(&generics.where_clause),
2580 span: generics.span,
2584 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2585 self.with_anonymous_lifetime_mode(
2586 AnonymousLifetimeMode::ReportError,
2588 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(wc.id);
2593 predicates: wc.predicates
2595 .map(|predicate| this.lower_where_predicate(predicate))
2602 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2604 WherePredicate::BoundPredicate(WhereBoundPredicate {
2605 ref bound_generic_params,
2610 self.with_in_scope_lifetime_defs(
2611 &bound_generic_params,
2613 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2614 bound_generic_params: this.lower_generic_params(
2615 bound_generic_params,
2616 &NodeMap::default(),
2617 ImplTraitContext::disallowed(),
2619 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
2622 .filter_map(|bound| match *bound {
2623 // Ignore `?Trait` bounds.
2624 // They were copied into type parameters already.
2625 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2626 _ => Some(this.lower_param_bound(
2628 ImplTraitContext::disallowed(),
2637 WherePredicate::RegionPredicate(WhereRegionPredicate {
2641 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2643 lifetime: self.lower_lifetime(lifetime),
2644 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2646 WherePredicate::EqPredicate(WhereEqPredicate {
2652 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(id);
2654 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2657 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
2658 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
2665 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2667 VariantData::Struct(ref fields, id) => {
2668 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(id);
2670 hir::VariantData::Struct(
2674 .map(|f| self.lower_struct_field(f))
2680 VariantData::Tuple(ref fields, id) => {
2681 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(id);
2683 hir::VariantData::Tuple(
2687 .map(|f| self.lower_struct_field(f))
2693 VariantData::Unit(id) => {
2694 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(id);
2696 hir::VariantData::Unit(node_id, hir_id)
2701 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2702 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2703 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2704 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2706 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.ref_id);
2714 fn lower_poly_trait_ref(
2717 mut itctx: ImplTraitContext<'_>,
2718 ) -> hir::PolyTraitRef {
2719 let bound_generic_params = self.lower_generic_params(
2720 &p.bound_generic_params,
2721 &NodeMap::default(),
2724 let trait_ref = self.with_parent_impl_lifetime_defs(
2725 &bound_generic_params,
2726 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2730 bound_generic_params,
2736 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2737 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(f.id);
2743 ident: match f.ident {
2744 Some(ident) => ident,
2745 // FIXME(jseyfried): positional field hygiene
2746 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2748 vis: self.lower_visibility(&f.vis, None),
2749 ty: self.lower_ty(&f.ty, ImplTraitContext::disallowed()),
2750 attrs: self.lower_attrs(&f.attrs),
2754 fn lower_field(&mut self, f: &Field) -> hir::Field {
2755 let LoweredNodeId { node_id, hir_id } = self.next_id();
2761 expr: P(self.lower_expr(&f.expr)),
2763 is_shorthand: f.is_shorthand,
2767 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2769 ty: self.lower_ty(&mt.ty, itctx),
2770 mutbl: self.lower_mutability(mt.mutbl),
2774 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2775 -> hir::GenericBounds {
2776 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2779 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2780 let mut expr = None;
2782 let mut stmts = vec![];
2784 for (index, stmt) in b.stmts.iter().enumerate() {
2785 if index == b.stmts.len() - 1 {
2786 if let StmtKind::Expr(ref e) = stmt.node {
2787 expr = Some(P(self.lower_expr(e)));
2789 stmts.extend(self.lower_stmt(stmt));
2792 stmts.extend(self.lower_stmt(stmt));
2796 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2801 stmts: stmts.into(),
2803 rules: self.lower_block_check_mode(&b.rules),
2809 fn lower_async_body(
2815 self.lower_body(Some(decl), |this| {
2816 if let IsAsync::Async { closure_id, .. } = asyncness {
2817 let async_expr = this.make_async_expr(
2818 CaptureBy::Value, closure_id, None,
2820 let body = this.lower_block(body, false);
2821 this.expr_block(body, ThinVec::new())
2823 this.expr(body.span, async_expr, ThinVec::new())
2825 let body = this.lower_block(body, false);
2826 this.expr_block(body, ThinVec::new())
2835 attrs: &hir::HirVec<Attribute>,
2836 vis: &mut hir::Visibility,
2838 ) -> hir::ItemKind {
2840 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2841 ItemKind::Use(ref use_tree) => {
2842 // Start with an empty prefix
2845 span: use_tree.span,
2848 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
2850 ItemKind::Static(ref t, m, ref e) => {
2851 let value = self.lower_body(None, |this| this.lower_expr(e));
2852 hir::ItemKind::Static(
2855 if self.sess.features_untracked().impl_trait_in_bindings {
2856 ImplTraitContext::Existential(None)
2858 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2861 self.lower_mutability(m),
2865 ItemKind::Const(ref t, ref e) => {
2866 let value = self.lower_body(None, |this| this.lower_expr(e));
2867 hir::ItemKind::Const(
2870 if self.sess.features_untracked().impl_trait_in_bindings {
2871 ImplTraitContext::Existential(None)
2873 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2879 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2880 let fn_def_id = self.resolver.definitions().local_def_id(id);
2881 self.with_new_scopes(|this| {
2882 // Note: we don't need to change the return type from `T` to
2883 // `impl Future<Output = T>` here because lower_body
2884 // only cares about the input argument patterns in the function
2885 // declaration (decl), not the return types.
2886 let body_id = this.lower_async_body(decl, header.asyncness, body);
2888 let (generics, fn_decl) = this.add_in_band_defs(
2891 AnonymousLifetimeMode::PassThrough,
2892 |this, idty| this.lower_fn_decl(
2894 Some((fn_def_id, idty)),
2896 header.asyncness.opt_return_id()
2902 this.lower_fn_header(header),
2908 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2909 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2910 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2911 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2912 self.lower_ty(t, ImplTraitContext::disallowed()),
2913 self.lower_generics(generics, ImplTraitContext::disallowed()),
2915 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2916 generics: self.lower_generics(generics, ImplTraitContext::disallowed()),
2917 bounds: self.lower_param_bounds(b, ImplTraitContext::disallowed()),
2918 impl_trait_fn: None,
2920 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2922 variants: enum_definition
2925 .map(|x| self.lower_variant(x))
2928 self.lower_generics(generics, ImplTraitContext::disallowed()),
2930 ItemKind::Struct(ref struct_def, ref generics) => {
2931 let struct_def = self.lower_variant_data(struct_def);
2932 hir::ItemKind::Struct(
2934 self.lower_generics(generics, ImplTraitContext::disallowed()),
2937 ItemKind::Union(ref vdata, ref generics) => {
2938 let vdata = self.lower_variant_data(vdata);
2939 hir::ItemKind::Union(
2941 self.lower_generics(generics, ImplTraitContext::disallowed()),
2953 let def_id = self.resolver.definitions().local_def_id(id);
2955 // Lower the "impl header" first. This ordering is important
2956 // for in-band lifetimes! Consider `'a` here:
2958 // impl Foo<'a> for u32 {
2959 // fn method(&'a self) { .. }
2962 // Because we start by lowering the `Foo<'a> for u32`
2963 // part, we will add `'a` to the list of generics on
2964 // the impl. When we then encounter it later in the
2965 // method, it will not be considered an in-band
2966 // lifetime to be added, but rather a reference to a
2968 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2971 AnonymousLifetimeMode::CreateParameter,
2973 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2974 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
2977 if let Some(ref trait_ref) = trait_ref {
2978 if let Def::Trait(def_id) = trait_ref.path.def {
2979 this.trait_impls.entry(def_id).or_default().push(id);
2983 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
2985 (trait_ref, lowered_ty)
2989 let new_impl_items = self.with_in_scope_lifetime_defs(
2990 &ast_generics.params,
2994 .map(|item| this.lower_impl_item_ref(item))
2999 hir::ItemKind::Impl(
3000 self.lower_unsafety(unsafety),
3001 self.lower_impl_polarity(polarity),
3002 self.lower_defaultness(defaultness, true /* [1] */),
3009 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
3010 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
3013 .map(|item| self.lower_trait_item_ref(item))
3015 hir::ItemKind::Trait(
3016 self.lower_is_auto(is_auto),
3017 self.lower_unsafety(unsafety),
3018 self.lower_generics(generics, ImplTraitContext::disallowed()),
3023 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
3024 self.lower_generics(generics, ImplTraitContext::disallowed()),
3025 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3027 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
3030 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
3031 // not cause an assertion failure inside the `lower_defaultness` function.
3039 vis: &mut hir::Visibility,
3041 attrs: &hir::HirVec<Attribute>,
3042 ) -> hir::ItemKind {
3043 debug!("lower_use_tree(tree={:?})", tree);
3044 debug!("lower_use_tree: vis = {:?}", vis);
3046 let path = &tree.prefix;
3047 let segments = prefix
3050 .chain(path.segments.iter())
3055 UseTreeKind::Simple(rename, id1, id2) => {
3056 *ident = tree.ident();
3058 // First, apply the prefix to the path.
3059 let mut path = Path {
3064 // Correctly resolve `self` imports.
3065 if path.segments.len() > 1
3066 && path.segments.last().unwrap().ident.name == keywords::SelfLower.name()
3068 let _ = path.segments.pop();
3069 if rename.is_none() {
3070 *ident = path.segments.last().unwrap().ident;
3074 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
3075 let mut defs = self.expect_full_def_from_use(id);
3076 // We want to return *something* from this function, so hold onto the first item
3078 let ret_def = defs.next().unwrap_or(Def::Err);
3080 // Here, we are looping over namespaces, if they exist for the definition
3081 // being imported. We only handle type and value namespaces because we
3082 // won't be dealing with macros in the rest of the compiler.
3083 // Essentially a single `use` which imports two names is desugared into
3085 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
3086 let vis = vis.clone();
3087 let ident = ident.clone();
3088 let mut path = path.clone();
3089 for seg in &mut path.segments {
3090 seg.id = self.sess.next_node_id();
3092 let span = path.span;
3093 self.resolver.definitions().create_def_with_parent(
3097 DefIndexAddressSpace::High,
3100 self.allocate_hir_id_counter(new_node_id, &path);
3102 self.with_hir_id_owner(new_node_id, |this| {
3103 let new_id = this.lower_node_id(new_node_id);
3105 this.lower_path_extra(def, &path, ParamMode::Explicit, None);
3106 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
3107 let vis_kind = match vis.node {
3108 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3109 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3110 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3111 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3112 let id = this.next_id();
3113 let path = this.renumber_segment_ids(path);
3114 hir::VisibilityKind::Restricted {
3121 let vis = respan(vis.span, vis_kind);
3127 hir_id: new_id.hir_id,
3129 attrs: attrs.clone(),
3139 P(self.lower_path_extra(ret_def, &path, ParamMode::Explicit, None));
3140 hir::ItemKind::Use(path, hir::UseKind::Single)
3142 UseTreeKind::Glob => {
3143 let path = P(self.lower_path(
3149 ParamMode::Explicit,
3151 hir::ItemKind::Use(path, hir::UseKind::Glob)
3153 UseTreeKind::Nested(ref trees) => {
3154 // Nested imports are desugared into simple imports.
3155 // So, if we start with
3158 // pub(x) use foo::{a, b};
3161 // we will create three items:
3164 // pub(x) use foo::a;
3165 // pub(x) use foo::b;
3166 // pub(x) use foo::{}; // <-- this is called the `ListStem`
3169 // The first two are produced by recursively invoking
3170 // `lower_use_tree` (and indeed there may be things
3171 // like `use foo::{a::{b, c}}` and so forth). They
3172 // wind up being directly added to
3173 // `self.items`. However, the structure of this
3174 // function also requires us to return one item, and
3175 // for that we return the `{}` import (called the
3180 span: prefix.span.to(path.span),
3183 // Add all the nested `PathListItem`s to the HIR.
3184 for &(ref use_tree, id) in trees {
3185 self.allocate_hir_id_counter(id, &use_tree);
3190 } = self.lower_node_id(id);
3192 let mut vis = vis.clone();
3193 let mut ident = ident.clone();
3194 let mut prefix = prefix.clone();
3196 // Give the segments new node-ids since they are being cloned.
3197 for seg in &mut prefix.segments {
3198 seg.id = self.sess.next_node_id();
3201 // Each `use` import is an item and thus are owners of the
3202 // names in the path. Up to this point the nested import is
3203 // the current owner, since we want each desugared import to
3204 // own its own names, we have to adjust the owner before
3205 // lowering the rest of the import.
3206 self.with_hir_id_owner(new_id, |this| {
3207 let item = this.lower_use_tree(use_tree,
3214 let vis_kind = match vis.node {
3215 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3216 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3217 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3218 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3219 let id = this.next_id();
3220 let path = this.renumber_segment_ids(path);
3221 hir::VisibilityKind::Restricted {
3228 let vis = respan(vis.span, vis_kind);
3236 attrs: attrs.clone(),
3239 span: use_tree.span,
3245 // Subtle and a bit hacky: we lower the privacy level
3246 // of the list stem to "private" most of the time, but
3247 // not for "restricted" paths. The key thing is that
3248 // we don't want it to stay as `pub` (with no caveats)
3249 // because that affects rustdoc and also the lints
3250 // about `pub` items. But we can't *always* make it
3251 // private -- particularly not for restricted paths --
3252 // because it contains node-ids that would then be
3253 // unused, failing the check that HirIds are "densely
3256 hir::VisibilityKind::Public |
3257 hir::VisibilityKind::Crate(_) |
3258 hir::VisibilityKind::Inherited => {
3259 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3261 hir::VisibilityKind::Restricted { .. } => {
3262 // Do nothing here, as described in the comment on the match.
3266 let def = self.expect_full_def_from_use(id).next().unwrap_or(Def::Err);
3267 let path = P(self.lower_path_extra(def, &prefix, ParamMode::Explicit, None));
3268 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3273 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
3274 /// many times in the HIR tree; for each occurrence, we need to assign distinct
3275 /// node-ids. (See e.g., #56128.)
3276 fn renumber_segment_ids(&mut self, path: &P<hir::Path>) -> P<hir::Path> {
3277 debug!("renumber_segment_ids(path = {:?})", path);
3278 let mut path = path.clone();
3279 for seg in path.segments.iter_mut() {
3280 if seg.id.is_some() {
3281 seg.id = Some(self.next_id().node_id);
3287 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3288 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3289 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
3291 let (generics, node) = match i.node {
3292 TraitItemKind::Const(ref ty, ref default) => (
3293 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3294 hir::TraitItemKind::Const(
3295 self.lower_ty(ty, ImplTraitContext::disallowed()),
3298 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
3301 TraitItemKind::Method(ref sig, None) => {
3302 let names = self.lower_fn_args_to_names(&sig.decl);
3303 let (generics, sig) = self.lower_method_sig(
3310 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3312 TraitItemKind::Method(ref sig, Some(ref body)) => {
3313 let body_id = self.lower_body(Some(&sig.decl), |this| {
3314 let body = this.lower_block(body, false);
3315 this.expr_block(body, ThinVec::new())
3317 let (generics, sig) = self.lower_method_sig(
3324 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3326 TraitItemKind::Type(ref bounds, ref default) => (
3327 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3328 hir::TraitItemKind::Type(
3329 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3332 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3335 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3342 attrs: self.lower_attrs(&i.attrs),
3349 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3350 let (kind, has_default) = match i.node {
3351 TraitItemKind::Const(_, ref default) => {
3352 (hir::AssociatedItemKind::Const, default.is_some())
3354 TraitItemKind::Type(_, ref default) => {
3355 (hir::AssociatedItemKind::Type, default.is_some())
3357 TraitItemKind::Method(ref sig, ref default) => (
3358 hir::AssociatedItemKind::Method {
3359 has_self: sig.decl.has_self(),
3363 TraitItemKind::Macro(..) => unimplemented!(),
3366 id: hir::TraitItemId { node_id: i.id },
3369 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3374 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3375 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3376 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3378 let (generics, node) = match i.node {
3379 ImplItemKind::Const(ref ty, ref expr) => {
3380 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3382 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3383 hir::ImplItemKind::Const(
3384 self.lower_ty(ty, ImplTraitContext::disallowed()),
3389 ImplItemKind::Method(ref sig, ref body) => {
3390 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3391 let impl_trait_return_allow = !self.is_in_trait_impl;
3392 let (generics, sig) = self.lower_method_sig(
3396 impl_trait_return_allow,
3397 sig.header.asyncness.opt_return_id(),
3399 (generics, hir::ImplItemKind::Method(sig, body_id))
3401 ImplItemKind::Type(ref ty) => (
3402 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3403 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3405 ImplItemKind::Existential(ref bounds) => (
3406 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3407 hir::ImplItemKind::Existential(
3408 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3411 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3418 attrs: self.lower_attrs(&i.attrs),
3420 vis: self.lower_visibility(&i.vis, None),
3421 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3426 // [1] since `default impl` is not yet implemented, this is always true in impls
3429 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3431 id: hir::ImplItemId { node_id: i.id },
3434 vis: self.lower_visibility(&i.vis, Some(i.id)),
3435 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3436 kind: match i.node {
3437 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3438 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3439 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3440 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3441 has_self: sig.decl.has_self(),
3443 ImplItemKind::Macro(..) => unimplemented!(),
3447 // [1] since `default impl` is not yet implemented, this is always true in impls
3450 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3453 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3457 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3459 ItemKind::Use(ref use_tree) => {
3460 let mut vec = smallvec![hir::ItemId { id: i.id }];
3461 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3464 ItemKind::MacroDef(..) => SmallVec::new(),
3466 ItemKind::Impl(.., None, _, _) => smallvec![hir::ItemId { id: i.id }],
3467 ItemKind::Static(ref ty, ..) => {
3468 let mut ids = smallvec![hir::ItemId { id: i.id }];
3469 if self.sess.features_untracked().impl_trait_in_bindings {
3470 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3471 visitor.visit_ty(ty);
3475 ItemKind::Const(ref ty, ..) => {
3476 let mut ids = smallvec![hir::ItemId { id: i.id }];
3477 if self.sess.features_untracked().impl_trait_in_bindings {
3478 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3479 visitor.visit_ty(ty);
3483 _ => smallvec![hir::ItemId { id: i.id }],
3487 fn lower_item_id_use_tree(&mut self,
3490 vec: &mut SmallVec<[hir::ItemId; 1]>)
3493 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3494 vec.push(hir::ItemId { id });
3495 self.lower_item_id_use_tree(nested, id, vec);
3497 UseTreeKind::Glob => {}
3498 UseTreeKind::Simple(_, id1, id2) => {
3499 for (_, &id) in self.expect_full_def_from_use(base_id)
3501 .zip([id1, id2].iter())
3503 vec.push(hir::ItemId { id });
3509 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3510 let mut ident = i.ident;
3511 let mut vis = self.lower_visibility(&i.vis, None);
3512 let attrs = self.lower_attrs(&i.attrs);
3513 if let ItemKind::MacroDef(ref def) = i.node {
3514 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3515 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3516 let body = self.lower_token_stream(def.stream());
3517 let hir_id = self.lower_node_id(i.id).hir_id;
3518 self.exported_macros.push(hir::MacroDef {
3532 let node = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.node);
3534 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3547 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3548 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3549 let def_id = self.resolver.definitions().local_def_id(node_id);
3554 attrs: self.lower_attrs(&i.attrs),
3555 node: match i.node {
3556 ForeignItemKind::Fn(ref fdec, ref generics) => {
3557 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3560 AnonymousLifetimeMode::PassThrough,
3563 // Disallow impl Trait in foreign items
3564 this.lower_fn_decl(fdec, None, false, None),
3565 this.lower_fn_args_to_names(fdec),
3570 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3572 ForeignItemKind::Static(ref t, m) => {
3573 hir::ForeignItemKind::Static(
3574 self.lower_ty(t, ImplTraitContext::disallowed()), m)
3576 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3577 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3579 vis: self.lower_visibility(&i.vis, None),
3584 fn lower_method_sig(
3586 generics: &Generics,
3589 impl_trait_return_allow: bool,
3590 is_async: Option<NodeId>,
3591 ) -> (hir::Generics, hir::MethodSig) {
3592 let header = self.lower_fn_header(sig.header);
3593 let (generics, decl) = self.add_in_band_defs(
3596 AnonymousLifetimeMode::PassThrough,
3597 |this, idty| this.lower_fn_decl(
3599 Some((fn_def_id, idty)),
3600 impl_trait_return_allow,
3604 (generics, hir::MethodSig { header, decl })
3607 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3609 IsAuto::Yes => hir::IsAuto::Yes,
3610 IsAuto::No => hir::IsAuto::No,
3614 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3616 unsafety: self.lower_unsafety(h.unsafety),
3617 asyncness: self.lower_asyncness(h.asyncness),
3618 constness: self.lower_constness(h.constness),
3623 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3625 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3626 Unsafety::Normal => hir::Unsafety::Normal,
3630 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3632 Constness::Const => hir::Constness::Const,
3633 Constness::NotConst => hir::Constness::NotConst,
3637 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3639 IsAsync::Async { .. } => hir::IsAsync::Async,
3640 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3644 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3646 UnOp::Deref => hir::UnDeref,
3647 UnOp::Not => hir::UnNot,
3648 UnOp::Neg => hir::UnNeg,
3652 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3654 node: match b.node {
3655 BinOpKind::Add => hir::BinOpKind::Add,
3656 BinOpKind::Sub => hir::BinOpKind::Sub,
3657 BinOpKind::Mul => hir::BinOpKind::Mul,
3658 BinOpKind::Div => hir::BinOpKind::Div,
3659 BinOpKind::Rem => hir::BinOpKind::Rem,
3660 BinOpKind::And => hir::BinOpKind::And,
3661 BinOpKind::Or => hir::BinOpKind::Or,
3662 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3663 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3664 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3665 BinOpKind::Shl => hir::BinOpKind::Shl,
3666 BinOpKind::Shr => hir::BinOpKind::Shr,
3667 BinOpKind::Eq => hir::BinOpKind::Eq,
3668 BinOpKind::Lt => hir::BinOpKind::Lt,
3669 BinOpKind::Le => hir::BinOpKind::Le,
3670 BinOpKind::Ne => hir::BinOpKind::Ne,
3671 BinOpKind::Ge => hir::BinOpKind::Ge,
3672 BinOpKind::Gt => hir::BinOpKind::Gt,
3678 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3679 let node = match p.node {
3680 PatKind::Wild => hir::PatKind::Wild,
3681 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3682 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3683 // `None` can occur in body-less function signatures
3684 def @ None | def @ Some(Def::Local(_)) => {
3685 let canonical_id = match def {
3686 Some(Def::Local(id)) => id,
3689 let hir_id = self.lower_node_id(canonical_id).hir_id;
3690 hir::PatKind::Binding(
3691 self.lower_binding_mode(binding_mode),
3695 sub.as_ref().map(|x| self.lower_pat(x)),
3698 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3703 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3708 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3709 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3710 let qpath = self.lower_qpath(
3714 ParamMode::Optional,
3715 ImplTraitContext::disallowed(),
3717 hir::PatKind::TupleStruct(
3719 pats.iter().map(|x| self.lower_pat(x)).collect(),
3723 PatKind::Path(ref qself, ref path) => {
3724 let qpath = self.lower_qpath(
3728 ParamMode::Optional,
3729 ImplTraitContext::disallowed(),
3731 hir::PatKind::Path(qpath)
3733 PatKind::Struct(ref path, ref fields, etc) => {
3734 let qpath = self.lower_qpath(
3738 ParamMode::Optional,
3739 ImplTraitContext::disallowed(),
3745 let LoweredNodeId { node_id, hir_id } = self.next_id();
3749 node: hir::FieldPat {
3752 ident: f.node.ident,
3753 pat: self.lower_pat(&f.node.pat),
3754 is_shorthand: f.node.is_shorthand,
3759 hir::PatKind::Struct(qpath, fs, etc)
3761 PatKind::Tuple(ref elts, ddpos) => {
3762 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3764 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3765 PatKind::Ref(ref inner, mutbl) => {
3766 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3768 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3769 P(self.lower_expr(e1)),
3770 P(self.lower_expr(e2)),
3771 self.lower_range_end(end),
3773 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3774 before.iter().map(|x| self.lower_pat(x)).collect(),
3775 slice.as_ref().map(|x| self.lower_pat(x)),
3776 after.iter().map(|x| self.lower_pat(x)).collect(),
3778 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3779 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3782 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3791 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3793 RangeEnd::Included(_) => hir::RangeEnd::Included,
3794 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3798 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3799 self.with_new_scopes(|this| {
3800 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3804 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3809 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3810 let kind = match e.node {
3811 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3812 ExprKind::ObsoleteInPlace(..) => {
3813 self.sess.abort_if_errors();
3814 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3816 ExprKind::Array(ref exprs) => {
3817 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3819 ExprKind::Repeat(ref expr, ref count) => {
3820 let expr = P(self.lower_expr(expr));
3821 let count = self.lower_anon_const(count);
3822 hir::ExprKind::Repeat(expr, count)
3824 ExprKind::Tup(ref elts) => {
3825 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3827 ExprKind::Call(ref f, ref args) => {
3828 let f = P(self.lower_expr(f));
3829 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3831 ExprKind::MethodCall(ref seg, ref args) => {
3832 let hir_seg = self.lower_path_segment(
3835 ParamMode::Optional,
3837 ParenthesizedGenericArgs::Err,
3838 ImplTraitContext::disallowed(),
3841 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3842 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3844 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3845 let binop = self.lower_binop(binop);
3846 let lhs = P(self.lower_expr(lhs));
3847 let rhs = P(self.lower_expr(rhs));
3848 hir::ExprKind::Binary(binop, lhs, rhs)
3850 ExprKind::Unary(op, ref ohs) => {
3851 let op = self.lower_unop(op);
3852 let ohs = P(self.lower_expr(ohs));
3853 hir::ExprKind::Unary(op, ohs)
3855 ExprKind::Lit(ref l) => hir::ExprKind::Lit((*l).clone()),
3856 ExprKind::Cast(ref expr, ref ty) => {
3857 let expr = P(self.lower_expr(expr));
3858 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3860 ExprKind::Type(ref expr, ref ty) => {
3861 let expr = P(self.lower_expr(expr));
3862 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3864 ExprKind::AddrOf(m, ref ohs) => {
3865 let m = self.lower_mutability(m);
3866 let ohs = P(self.lower_expr(ohs));
3867 hir::ExprKind::AddrOf(m, ohs)
3869 // More complicated than you might expect because the else branch
3870 // might be `if let`.
3871 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3872 let else_opt = else_opt.as_ref().map(|els| {
3874 ExprKind::IfLet(..) => {
3875 // Wrap the `if let` expr in a block.
3876 let span = els.span;
3877 let els = P(self.lower_expr(els));
3878 let LoweredNodeId { node_id, hir_id } = self.next_id();
3879 let blk = P(hir::Block {
3884 rules: hir::DefaultBlock,
3886 targeted_by_break: false,
3888 P(self.expr_block(blk, ThinVec::new()))
3890 _ => P(self.lower_expr(els)),
3894 let then_blk = self.lower_block(blk, false);
3895 let then_expr = self.expr_block(then_blk, ThinVec::new());
3897 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3899 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3900 hir::ExprKind::While(
3901 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3902 this.lower_block(body, false),
3903 this.lower_label(opt_label),
3906 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3907 hir::ExprKind::Loop(
3908 this.lower_block(body, false),
3909 this.lower_label(opt_label),
3910 hir::LoopSource::Loop,
3913 ExprKind::TryBlock(ref body) => {
3914 self.with_catch_scope(body.id, |this| {
3916 this.allow_internal_unstable(CompilerDesugaringKind::TryBlock, body.span);
3917 let mut block = this.lower_block(body, true).into_inner();
3918 let tail = block.expr.take().map_or_else(
3920 let LoweredNodeId { node_id, hir_id } = this.next_id();
3921 let span = this.sess.source_map().end_point(unstable_span);
3925 node: hir::ExprKind::Tup(hir_vec![]),
3926 attrs: ThinVec::new(),
3930 |x: P<hir::Expr>| x.into_inner(),
3932 block.expr = Some(this.wrap_in_try_constructor(
3933 "from_ok", tail, unstable_span));
3934 hir::ExprKind::Block(P(block), None)
3937 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3938 P(self.lower_expr(expr)),
3939 arms.iter().map(|x| self.lower_arm(x)).collect(),
3940 hir::MatchSource::Normal,
3942 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3943 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3944 this.with_new_scopes(|this| {
3945 let block = this.lower_block(block, false);
3946 this.expr_block(block, ThinVec::new())
3951 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3953 if let IsAsync::Async { closure_id, .. } = asyncness {
3954 let outer_decl = FnDecl {
3955 inputs: decl.inputs.clone(),
3956 output: FunctionRetTy::Default(fn_decl_span),
3959 // We need to lower the declaration outside the new scope, because we
3960 // have to conserve the state of being inside a loop condition for the
3961 // closure argument types.
3962 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3964 self.with_new_scopes(|this| {
3965 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
3966 if capture_clause == CaptureBy::Ref &&
3967 !decl.inputs.is_empty()
3973 "`async` non-`move` closures with arguments \
3974 are not currently supported",
3976 .help("consider using `let` statements to manually capture \
3977 variables by reference before entering an \
3978 `async move` closure")
3982 // Transform `async |x: u8| -> X { ... }` into
3983 // `|x: u8| future_from_generator(|| -> X { ... })`.
3984 let body_id = this.lower_body(Some(&outer_decl), |this| {
3985 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3988 let async_body = this.make_async_expr(
3989 capture_clause, closure_id, async_ret_ty,
3991 this.with_new_scopes(|this| this.lower_expr(body))
3993 this.expr(fn_decl_span, async_body, ThinVec::new())
3995 hir::ExprKind::Closure(
3996 this.lower_capture_clause(capture_clause),
4004 // Lower outside new scope to preserve `is_in_loop_condition`.
4005 let fn_decl = self.lower_fn_decl(decl, None, false, None);
4007 self.with_new_scopes(|this| {
4008 let mut is_generator = false;
4009 let body_id = this.lower_body(Some(decl), |this| {
4010 let e = this.lower_expr(body);
4011 is_generator = this.is_generator;
4014 let generator_option = if is_generator {
4015 if !decl.inputs.is_empty() {
4020 "generators cannot have explicit arguments"
4022 this.sess.abort_if_errors();
4024 Some(match movability {
4025 Movability::Movable => hir::GeneratorMovability::Movable,
4026 Movability::Static => hir::GeneratorMovability::Static,
4029 if movability == Movability::Static {
4034 "closures cannot be static"
4039 hir::ExprKind::Closure(
4040 this.lower_capture_clause(capture_clause),
4049 ExprKind::Block(ref blk, opt_label) => {
4050 hir::ExprKind::Block(self.lower_block(blk,
4051 opt_label.is_some()),
4052 self.lower_label(opt_label))
4054 ExprKind::Assign(ref el, ref er) => {
4055 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
4057 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
4058 self.lower_binop(op),
4059 P(self.lower_expr(el)),
4060 P(self.lower_expr(er)),
4062 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
4063 ExprKind::Index(ref el, ref er) => {
4064 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
4066 // Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
4067 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
4068 let id = self.next_id();
4069 let e1 = self.lower_expr(e1);
4070 let e2 = self.lower_expr(e2);
4071 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
4072 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
4073 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
4074 let new_path = hir::QPath::TypeRelative(ty, new_seg);
4075 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
4076 hir::ExprKind::Call(new, hir_vec![e1, e2])
4078 ExprKind::Range(ref e1, ref e2, lims) => {
4079 use syntax::ast::RangeLimits::*;
4081 let path = match (e1, e2, lims) {
4082 (&None, &None, HalfOpen) => "RangeFull",
4083 (&Some(..), &None, HalfOpen) => "RangeFrom",
4084 (&None, &Some(..), HalfOpen) => "RangeTo",
4085 (&Some(..), &Some(..), HalfOpen) => "Range",
4086 (&None, &Some(..), Closed) => "RangeToInclusive",
4087 (&Some(..), &Some(..), Closed) => unreachable!(),
4088 (_, &None, Closed) => self.diagnostic()
4089 .span_fatal(e.span, "inclusive range with no end")
4093 let fields = e1.iter()
4094 .map(|e| ("start", e))
4095 .chain(e2.iter().map(|e| ("end", e)))
4097 let expr = P(self.lower_expr(&e));
4098 let ident = Ident::new(Symbol::intern(s), e.span);
4099 self.field(ident, expr, e.span)
4101 .collect::<P<[hir::Field]>>();
4103 let is_unit = fields.is_empty();
4104 let struct_path = ["ops", path];
4105 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
4106 let struct_path = hir::QPath::Resolved(None, P(struct_path));
4108 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4114 hir::ExprKind::Path(struct_path)
4116 hir::ExprKind::Struct(struct_path, fields, None)
4119 attrs: e.attrs.clone(),
4122 ExprKind::Path(ref qself, ref path) => {
4123 let qpath = self.lower_qpath(
4127 ParamMode::Optional,
4128 ImplTraitContext::disallowed(),
4130 hir::ExprKind::Path(qpath)
4132 ExprKind::Break(opt_label, ref opt_expr) => {
4133 let destination = if self.is_in_loop_condition && opt_label.is_none() {
4136 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4139 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4141 hir::ExprKind::Break(
4143 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
4146 ExprKind::Continue(opt_label) => {
4147 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
4150 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4153 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4156 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
4157 ExprKind::InlineAsm(ref asm) => {
4158 let hir_asm = hir::InlineAsm {
4159 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
4160 outputs: asm.outputs
4162 .map(|out| hir::InlineAsmOutput {
4163 constraint: out.constraint.clone(),
4165 is_indirect: out.is_indirect,
4166 span: out.expr.span,
4169 asm: asm.asm.clone(),
4170 asm_str_style: asm.asm_str_style,
4171 clobbers: asm.clobbers.clone().into(),
4172 volatile: asm.volatile,
4173 alignstack: asm.alignstack,
4174 dialect: asm.dialect,
4177 let outputs = asm.outputs
4179 .map(|out| self.lower_expr(&out.expr))
4181 let inputs = asm.inputs
4183 .map(|&(_, ref input)| self.lower_expr(input))
4185 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
4187 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4192 ParamMode::Optional,
4193 ImplTraitContext::disallowed(),
4195 fields.iter().map(|x| self.lower_field(x)).collect(),
4196 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4198 ExprKind::Paren(ref ex) => {
4199 let mut ex = self.lower_expr(ex);
4200 // Include parens in span, but only if it is a super-span.
4201 if e.span.contains(ex.span) {
4204 // Merge attributes into the inner expression.
4205 let mut attrs = e.attrs.clone();
4206 attrs.extend::<Vec<_>>(ex.attrs.into());
4211 ExprKind::Yield(ref opt_expr) => {
4212 self.is_generator = true;
4215 .map(|x| self.lower_expr(x))
4217 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
4219 hir::ExprKind::Yield(P(expr))
4222 ExprKind::Err => hir::ExprKind::Err,
4224 // Desugar `ExprIfLet`
4225 // from: `if let <pat> = <sub_expr> <body> [<else_opt>]`
4226 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4229 // match <sub_expr> {
4231 // _ => [<else_opt> | ()]
4234 let mut arms = vec![];
4236 // `<pat> => <body>`
4238 let body = self.lower_block(body, false);
4239 let body_expr = P(self.expr_block(body, ThinVec::new()));
4240 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4241 arms.push(self.arm(pats, body_expr));
4244 // _ => [<else_opt>|()]
4246 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4247 let wildcard_pattern = self.pat_wild(e.span);
4248 let body = if let Some(else_expr) = wildcard_arm {
4249 P(self.lower_expr(else_expr))
4251 self.expr_tuple(e.span, hir_vec![])
4253 arms.push(self.arm(hir_vec![wildcard_pattern], body));
4256 let contains_else_clause = else_opt.is_some();
4258 let sub_expr = P(self.lower_expr(sub_expr));
4260 hir::ExprKind::Match(
4263 hir::MatchSource::IfLetDesugar {
4264 contains_else_clause,
4269 // Desugar `ExprWhileLet`
4270 // from: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4271 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4274 // [opt_ident]: loop {
4275 // match <sub_expr> {
4281 // Note that the block AND the condition are evaluated in the loop scope.
4282 // This is done to allow `break` from inside the condition of the loop.
4283 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4285 this.lower_block(body, false),
4286 this.expr_break(e.span, ThinVec::new()),
4287 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4291 // `<pat> => <body>`
4293 let body_expr = P(self.expr_block(body, ThinVec::new()));
4294 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4295 self.arm(pats, body_expr)
4300 let pat_under = self.pat_wild(e.span);
4301 self.arm(hir_vec![pat_under], break_expr)
4304 // `match <sub_expr> { ... }`
4305 let arms = hir_vec![pat_arm, break_arm];
4306 let match_expr = self.expr(
4308 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4312 // `[opt_ident]: loop { ... }`
4313 let loop_block = P(self.block_expr(P(match_expr)));
4314 let loop_expr = hir::ExprKind::Loop(
4316 self.lower_label(opt_label),
4317 hir::LoopSource::WhileLet,
4319 // Add attributes to the outer returned expr node.
4323 // Desugar `ExprForLoop`
4324 // from: `[opt_ident]: for <pat> in <head> <body>`
4325 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4329 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4331 // [opt_ident]: loop {
4333 // match ::std::iter::Iterator::next(&mut iter) {
4334 // ::std::option::Option::Some(val) => __next = val,
4335 // ::std::option::Option::None => break
4337 // let <pat> = __next;
4338 // StmtKind::Expr(<body>);
4346 let head = self.lower_expr(head);
4347 let head_sp = head.span;
4348 let desugared_span = self.allow_internal_unstable(
4349 CompilerDesugaringKind::ForLoop,
4353 let iter = self.str_to_ident("iter");
4355 let next_ident = self.str_to_ident("__next");
4356 let next_pat = self.pat_ident_binding_mode(
4359 hir::BindingAnnotation::Mutable,
4362 // `::std::option::Option::Some(val) => next = val`
4364 let val_ident = self.str_to_ident("val");
4365 let val_pat = self.pat_ident(pat.span, val_ident);
4366 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4367 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4368 let assign = P(self.expr(
4370 hir::ExprKind::Assign(next_expr, val_expr),
4373 let some_pat = self.pat_some(pat.span, val_pat);
4374 self.arm(hir_vec![some_pat], assign)
4377 // `::std::option::Option::None => break`
4380 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4381 let pat = self.pat_none(e.span);
4382 self.arm(hir_vec![pat], break_expr)
4386 let iter_pat = self.pat_ident_binding_mode(
4389 hir::BindingAnnotation::Mutable
4392 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4394 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4395 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4396 let next_path = &["iter", "Iterator", "next"];
4397 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4398 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4399 let arms = hir_vec![pat_arm, break_arm];
4403 hir::ExprKind::Match(
4406 hir::MatchSource::ForLoopDesugar
4411 let LoweredNodeId { node_id, hir_id } = self.next_id();
4412 let match_stmt = hir::Stmt {
4415 node: hir::StmtKind::Expr(match_expr),
4419 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4422 let next_let = self.stmt_let_pat(
4426 hir::LocalSource::ForLoopDesugar,
4429 // `let <pat> = __next`
4430 let pat = self.lower_pat(pat);
4431 let pat_let = self.stmt_let_pat(
4435 hir::LocalSource::ForLoopDesugar,
4438 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4439 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4440 let LoweredNodeId { node_id, hir_id } = self.next_id();
4441 let body_stmt = hir::Stmt {
4444 node: hir::StmtKind::Expr(body_expr),
4448 let loop_block = P(self.block_all(
4450 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4454 // `[opt_ident]: loop { ... }`
4455 let loop_expr = hir::ExprKind::Loop(
4457 self.lower_label(opt_label),
4458 hir::LoopSource::ForLoop,
4460 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4461 let loop_expr = P(hir::Expr {
4466 attrs: ThinVec::new(),
4469 // `mut iter => { ... }`
4470 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4472 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4473 let into_iter_expr = {
4474 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4475 let into_iter = P(self.expr_std_path(
4476 head_sp, into_iter_path, None, ThinVec::new()));
4477 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4480 let match_expr = P(self.expr_match(
4484 hir::MatchSource::ForLoopDesugar,
4487 // `{ let _result = ...; _result }`
4488 // Underscore prevents an `unused_variables` lint if the head diverges.
4489 let result_ident = self.str_to_ident("_result");
4490 let (let_stmt, let_stmt_binding) =
4491 self.stmt_let(e.span, false, result_ident, match_expr);
4493 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4494 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4495 // Add the attributes to the outer returned expr node.
4496 return self.expr_block(block, e.attrs.clone());
4499 // Desugar `ExprKind::Try`
4501 ExprKind::Try(ref sub_expr) => {
4504 // match Try::into_result(<expr>) {
4505 // Ok(val) => #[allow(unreachable_code)] val,
4506 // Err(err) => #[allow(unreachable_code)]
4507 // // If there is an enclosing `catch {...}`
4508 // break 'catch_target Try::from_error(From::from(err)),
4510 // return Try::from_error(From::from(err)),
4514 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4516 // `Try::into_result(<expr>)`
4519 let sub_expr = self.lower_expr(sub_expr);
4521 let path = &["ops", "Try", "into_result"];
4522 let path = P(self.expr_std_path(
4523 unstable_span, path, None, ThinVec::new()));
4524 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4527 // `#[allow(unreachable_code)]`
4529 // `allow(unreachable_code)`
4531 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4532 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4533 let uc_nested = attr::mk_nested_word_item(uc_ident);
4534 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4536 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4538 let attrs = vec![attr];
4540 // `Ok(val) => #[allow(unreachable_code)] val,`
4542 let val_ident = self.str_to_ident("val");
4543 let val_pat = self.pat_ident(e.span, val_ident);
4544 let val_expr = P(self.expr_ident_with_attrs(
4548 ThinVec::from(attrs.clone()),
4550 let ok_pat = self.pat_ok(e.span, val_pat);
4552 self.arm(hir_vec![ok_pat], val_expr)
4555 // `Err(err) => #[allow(unreachable_code)]
4556 // return Try::from_error(From::from(err)),`
4558 let err_ident = self.str_to_ident("err");
4559 let err_local = self.pat_ident(e.span, err_ident);
4561 let path = &["convert", "From", "from"];
4562 let from = P(self.expr_std_path(
4563 e.span, path, None, ThinVec::new()));
4564 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4566 self.expr_call(e.span, from, hir_vec![err_expr])
4569 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4570 let thin_attrs = ThinVec::from(attrs);
4571 let catch_scope = self.catch_scopes.last().map(|x| *x);
4572 let ret_expr = if let Some(catch_node) = catch_scope {
4575 hir::ExprKind::Break(
4578 target_id: Ok(catch_node),
4580 Some(from_err_expr),
4585 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4588 let err_pat = self.pat_err(e.span, err_local);
4589 self.arm(hir_vec![err_pat], ret_expr)
4592 hir::ExprKind::Match(
4594 hir_vec![err_arm, ok_arm],
4595 hir::MatchSource::TryDesugar,
4599 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4602 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4609 attrs: e.attrs.clone(),
4613 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
4614 smallvec![match s.node {
4615 StmtKind::Local(ref l) => {
4616 let (l, item_ids) = self.lower_local(l);
4617 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
4620 let LoweredNodeId { node_id, hir_id } = self.next_id();
4625 node: hir::StmtKind::Item(P(item_id)),
4631 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(s.id);
4636 node: hir::StmtKind::Local(P(l)),
4642 StmtKind::Item(ref it) => {
4643 // Can only use the ID once.
4644 let mut id = Some(s.id);
4645 return self.lower_item_id(it)
4648 let LoweredNodeId { node_id, hir_id } = id.take()
4649 .map(|id| self.lower_node_id(id))
4650 .unwrap_or_else(|| self.next_id());
4655 node: hir::StmtKind::Item(P(item_id)),
4661 StmtKind::Expr(ref e) => {
4662 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(s.id);
4667 node: hir::StmtKind::Expr(P(self.lower_expr(e))),
4671 StmtKind::Semi(ref e) => {
4672 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(s.id);
4677 node: hir::StmtKind::Semi(P(self.lower_expr(e))),
4681 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4685 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4687 CaptureBy::Value => hir::CaptureByValue,
4688 CaptureBy::Ref => hir::CaptureByRef,
4692 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4693 /// the address space of that item instead of the item currently being
4694 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4695 /// lower a `Visibility` value although we haven't lowered the owning
4696 /// `ImplItem` in question yet.
4697 fn lower_visibility(
4700 explicit_owner: Option<NodeId>,
4701 ) -> hir::Visibility {
4702 let node = match v.node {
4703 VisibilityKind::Public => hir::VisibilityKind::Public,
4704 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4705 VisibilityKind::Restricted { ref path, id } => {
4706 debug!("lower_visibility: restricted path id = {:?}", id);
4707 let lowered_id = if let Some(owner) = explicit_owner {
4708 self.lower_node_id_with_owner(id, owner)
4710 self.lower_node_id(id)
4712 let def = self.expect_full_def(id);
4713 hir::VisibilityKind::Restricted {
4714 path: P(self.lower_path_extra(
4717 ParamMode::Explicit,
4720 id: lowered_id.node_id,
4721 hir_id: lowered_id.hir_id,
4724 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4726 respan(v.span, node)
4729 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4731 Defaultness::Default => hir::Defaultness::Default {
4732 has_value: has_value,
4734 Defaultness::Final => {
4736 hir::Defaultness::Final
4741 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4743 BlockCheckMode::Default => hir::DefaultBlock,
4744 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4748 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4750 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4751 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4752 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4753 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4757 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4759 CompilerGenerated => hir::CompilerGenerated,
4760 UserProvided => hir::UserProvided,
4764 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4766 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4767 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4771 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4773 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4774 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4778 // Helper methods for building HIR.
4780 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4789 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4790 let LoweredNodeId { node_id, hir_id } = self.next_id();
4798 is_shorthand: false,
4802 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4803 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4804 P(self.expr(span, expr_break, attrs))
4811 args: hir::HirVec<hir::Expr>,
4813 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4816 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4817 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4820 fn expr_ident_with_attrs(
4825 attrs: ThinVec<Attribute>,
4827 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4831 def: Def::Local(binding),
4832 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4836 self.expr(span, expr_path, attrs)
4839 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4840 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4846 components: &[&str],
4847 params: Option<P<hir::GenericArgs>>,
4848 attrs: ThinVec<Attribute>,
4850 let path = self.std_path(span, components, params, true);
4853 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4862 arms: hir::HirVec<hir::Arm>,
4863 source: hir::MatchSource,
4865 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4868 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4869 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4872 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4873 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4876 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4877 let LoweredNodeId { node_id, hir_id } = self.next_id();
4890 ex: Option<P<hir::Expr>>,
4892 source: hir::LocalSource,
4894 let LoweredNodeId { node_id, hir_id } = self.next_id();
4896 let local = hir::Local {
4903 attrs: ThinVec::new(),
4907 let LoweredNodeId { node_id, hir_id } = self.next_id();
4911 node: hir::StmtKind::Local(P(local)),
4922 ) -> (hir::Stmt, NodeId) {
4923 let pat = if mutbl {
4924 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4926 self.pat_ident(sp, ident)
4928 let pat_id = pat.id;
4930 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4935 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4936 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4942 stmts: hir::HirVec<hir::Stmt>,
4943 expr: Option<P<hir::Expr>>,
4945 let LoweredNodeId { node_id, hir_id } = self.next_id();
4952 rules: hir::DefaultBlock,
4954 targeted_by_break: false,
4958 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4959 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4962 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4963 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4966 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4967 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4970 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4971 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4977 components: &[&str],
4978 subpats: hir::HirVec<P<hir::Pat>>,
4980 let path = self.std_path(span, components, None, true);
4981 let qpath = hir::QPath::Resolved(None, P(path));
4982 let pt = if subpats.is_empty() {
4983 hir::PatKind::Path(qpath)
4985 hir::PatKind::TupleStruct(qpath, subpats, None)
4990 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4991 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4994 fn pat_ident_binding_mode(
4998 bm: hir::BindingAnnotation,
5000 let LoweredNodeId { node_id, hir_id } = self.next_id();
5005 node: hir::PatKind::Binding(bm, node_id, hir_id, ident.with_span_pos(span), None),
5010 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
5011 self.pat(span, hir::PatKind::Wild)
5014 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
5015 let LoweredNodeId { node_id, hir_id } = self.next_id();
5024 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
5025 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
5026 /// The path is also resolved according to `is_value`.
5030 components: &[&str],
5031 params: Option<P<hir::GenericArgs>>,
5034 let mut path = self.resolver
5035 .resolve_str_path(span, self.crate_root, components, is_value);
5036 path.segments.last_mut().unwrap().args = params;
5039 for seg in path.segments.iter_mut() {
5040 if let Some(id) = seg.id {
5041 seg.id = Some(self.lower_node_id(id).node_id);
5047 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
5049 let node = match qpath {
5050 hir::QPath::Resolved(None, path) => {
5051 // Turn trait object paths into `TyKind::TraitObject` instead.
5053 Def::Trait(_) | Def::TraitAlias(_) => {
5054 let principal = hir::PolyTraitRef {
5055 bound_generic_params: hir::HirVec::new(),
5056 trait_ref: hir::TraitRef {
5057 path: path.and_then(|path| path),
5059 hir_ref_id: id.hir_id,
5064 // The original ID is taken by the `PolyTraitRef`,
5065 // so the `Ty` itself needs a different one.
5066 id = self.next_id();
5067 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
5069 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
5072 _ => hir::TyKind::Path(qpath),
5082 /// Invoked to create the lifetime argument for a type `&T`
5083 /// with no explicit lifetime.
5084 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
5085 match self.anonymous_lifetime_mode {
5086 // Intercept when we are in an impl header and introduce an in-band lifetime.
5087 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
5089 AnonymousLifetimeMode::CreateParameter => {
5090 let fresh_name = self.collect_fresh_in_band_lifetime(span);
5091 let LoweredNodeId { node_id, hir_id } = self.next_id();
5096 name: hir::LifetimeName::Param(fresh_name),
5100 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5102 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5106 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
5107 /// return a "error lifetime".
5108 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
5109 let (id, msg, label) = match id {
5110 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
5113 self.next_id().node_id,
5114 "`&` without an explicit lifetime name cannot be used here",
5115 "explicit lifetime name needed here",
5119 let mut err = struct_span_err!(
5126 err.span_label(span, label);
5129 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5132 /// Invoked to create the lifetime argument(s) for a path like
5133 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
5134 /// sorts of cases are deprecated. This may therefore report a warning or an
5135 /// error, depending on the mode.
5136 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
5137 match self.anonymous_lifetime_mode {
5138 // N.B., We intentionally ignore the create-parameter mode here
5139 // and instead "pass through" to resolve-lifetimes, which will then
5140 // report an error. This is because we don't want to support
5141 // impl elision for deprecated forms like
5143 // impl Foo for std::cell::Ref<u32> // note lack of '_
5144 AnonymousLifetimeMode::CreateParameter => {}
5146 AnonymousLifetimeMode::ReportError => {
5148 .map(|_| self.new_error_lifetime(None, span))
5152 // This is the normal case.
5153 AnonymousLifetimeMode::PassThrough => {}
5157 .map(|_| self.new_implicit_lifetime(span))
5161 /// Invoked to create the lifetime argument(s) for an elided trait object
5162 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
5163 /// when the bound is written, even if it is written with `'_` like in
5164 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
5165 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
5166 match self.anonymous_lifetime_mode {
5167 // NB. We intentionally ignore the create-parameter mode here.
5168 // and instead "pass through" to resolve-lifetimes, which will apply
5169 // the object-lifetime-defaulting rules. Elided object lifetime defaults
5170 // do not act like other elided lifetimes. In other words, given this:
5172 // impl Foo for Box<dyn Debug>
5174 // we do not introduce a fresh `'_` to serve as the bound, but instead
5175 // ultimately translate to the equivalent of:
5177 // impl Foo for Box<dyn Debug + 'static>
5179 // `resolve_lifetime` has the code to make that happen.
5180 AnonymousLifetimeMode::CreateParameter => {}
5182 AnonymousLifetimeMode::ReportError => {
5183 // ReportError applies to explicit use of `'_`.
5186 // This is the normal case.
5187 AnonymousLifetimeMode::PassThrough => {}
5190 self.new_implicit_lifetime(span)
5193 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
5194 let LoweredNodeId { node_id, hir_id } = self.next_id();
5200 name: hir::LifetimeName::Implicit,
5204 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
5205 self.sess.buffer_lint_with_diagnostic(
5206 builtin::BARE_TRAIT_OBJECTS,
5209 "trait objects without an explicit `dyn` are deprecated",
5210 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
5214 fn wrap_in_try_constructor(
5216 method: &'static str,
5218 unstable_span: Span,
5220 let path = &["ops", "Try", method];
5221 let from_err = P(self.expr_std_path(unstable_span, path, None,
5223 P(self.expr_call(e.span, from_err, hir_vec![e]))
5227 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5228 // Sorting by span ensures that we get things in order within a
5229 // file, and also puts the files in a sensible order.
5230 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5231 body_ids.sort_by_key(|b| bodies[b].value.span);