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 crate::dep_graph::DepGraph;
34 use crate::errors::Applicability;
35 use crate::hir::{self, ParamName};
36 use crate::hir::HirVec;
37 use crate::hir::map::{DefKey, DefPathData, Definitions};
38 use crate::hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX};
39 use crate::hir::def::{Def, PathResolution, PerNS};
40 use crate::hir::GenericArg;
41 use crate::lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
42 ELIDED_LIFETIMES_IN_PATHS};
43 use crate::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;
47 use crate::session::Session;
48 use crate::session::config::nightly_options;
49 use crate::util::common::FN_OUTPUT_NAME;
50 use crate::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)),
1160 ast::GenericArg::Const(ct) => {
1161 // FIXME(const_generics): const generics are not yet defined in the HIR.
1162 self.sess.struct_span_err(
1164 "const generics in any position are currently unsupported",
1166 self.sess.abort_if_errors();
1172 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1173 P(self.lower_ty_direct(t, itctx))
1176 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1177 let kind = match t.node {
1178 TyKind::Infer => hir::TyKind::Infer,
1179 TyKind::Err => hir::TyKind::Err,
1180 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1181 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1182 TyKind::Rptr(ref region, ref mt) => {
1183 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1184 let lifetime = match *region {
1185 Some(ref lt) => self.lower_lifetime(lt),
1186 None => self.elided_ref_lifetime(span),
1188 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1190 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1193 this.with_anonymous_lifetime_mode(
1194 AnonymousLifetimeMode::PassThrough,
1196 hir::TyKind::BareFn(P(hir::BareFnTy {
1197 generic_params: this.lower_generic_params(
1199 &NodeMap::default(),
1200 ImplTraitContext::disallowed(),
1202 unsafety: this.lower_unsafety(f.unsafety),
1204 decl: this.lower_fn_decl(&f.decl, None, false, None),
1205 arg_names: this.lower_fn_args_to_names(&f.decl),
1211 TyKind::Never => hir::TyKind::Never,
1212 TyKind::Tup(ref tys) => {
1213 hir::TyKind::Tup(tys.iter().map(|ty| {
1214 self.lower_ty_direct(ty, itctx.reborrow())
1217 TyKind::Paren(ref ty) => {
1218 return self.lower_ty_direct(ty, itctx);
1220 TyKind::Path(ref qself, ref path) => {
1221 let id = self.lower_node_id(t.id);
1222 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1223 let ty = self.ty_path(id, t.span, qpath);
1224 if let hir::TyKind::TraitObject(..) = ty.node {
1225 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1229 TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1232 def: self.expect_full_def(t.id),
1233 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfUpper.ident())],
1237 TyKind::Array(ref ty, ref length) => {
1238 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1240 TyKind::Typeof(ref expr) => {
1241 hir::TyKind::Typeof(self.lower_anon_const(expr))
1243 TyKind::TraitObject(ref bounds, kind) => {
1244 let mut lifetime_bound = None;
1247 .filter_map(|bound| match *bound {
1248 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1249 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1251 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1252 GenericBound::Outlives(ref lifetime) => {
1253 if lifetime_bound.is_none() {
1254 lifetime_bound = Some(self.lower_lifetime(lifetime));
1260 let lifetime_bound =
1261 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1262 if kind != TraitObjectSyntax::Dyn {
1263 self.maybe_lint_bare_trait(t.span, t.id, false);
1265 hir::TyKind::TraitObject(bounds, lifetime_bound)
1267 TyKind::ImplTrait(def_node_id, ref bounds) => {
1270 ImplTraitContext::Existential(fn_def_id) => {
1271 self.lower_existential_impl_trait(
1272 span, fn_def_id, def_node_id,
1273 |this| this.lower_param_bounds(bounds, itctx),
1276 ImplTraitContext::Universal(in_band_ty_params) => {
1277 let LoweredNodeId { node_id: _, hir_id } = self.lower_node_id(def_node_id);
1278 // Add a definition for the in-band `Param`.
1279 let def_index = self
1282 .opt_def_index(def_node_id)
1285 let hir_bounds = self.lower_param_bounds(
1287 ImplTraitContext::Universal(in_band_ty_params),
1289 // Set the name to `impl Bound1 + Bound2`.
1290 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1291 in_band_ty_params.push(hir::GenericParam {
1294 name: ParamName::Plain(ident),
1295 pure_wrt_drop: false,
1299 kind: hir::GenericParamKind::Type {
1301 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1305 hir::TyKind::Path(hir::QPath::Resolved(
1309 def: Def::TyParam(DefId::local(def_index)),
1310 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1314 ImplTraitContext::Disallowed(pos) => {
1315 let allowed_in = if self.sess.features_untracked()
1316 .impl_trait_in_bindings {
1317 "bindings or function and inherent method return types"
1319 "function and inherent method return types"
1321 let mut err = struct_span_err!(
1325 "`impl Trait` not allowed outside of {}",
1328 if pos == ImplTraitPosition::Binding &&
1329 nightly_options::is_nightly_build() {
1331 "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1339 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1342 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1351 fn lower_existential_impl_trait(
1354 fn_def_id: Option<DefId>,
1355 exist_ty_node_id: NodeId,
1356 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1358 // Make sure we know that some funky desugaring has been going on here.
1359 // This is a first: there is code in other places like for loop
1360 // desugaring that explicitly states that we don't want to track that.
1361 // Not tracking it makes lints in rustc and clippy very fragile as
1362 // frequently opened issues show.
1363 let exist_ty_span = self.allow_internal_unstable(
1364 CompilerDesugaringKind::ExistentialReturnType,
1368 let exist_ty_def_index = self
1371 .opt_def_index(exist_ty_node_id)
1374 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1376 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1378 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1384 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1385 let LoweredNodeId { node_id, hir_id } = lctx.next_id();
1386 let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1387 generics: hir::Generics {
1388 params: lifetime_defs,
1389 where_clause: hir::WhereClause {
1392 predicates: Vec::new().into(),
1397 impl_trait_fn: fn_def_id,
1399 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1400 // Generate an `existential type Foo: Trait;` declaration.
1401 trace!("creating existential type with id {:#?}", exist_ty_id);
1403 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1404 let exist_ty_item = hir::Item {
1405 id: exist_ty_id.node_id,
1406 hir_id: exist_ty_id.hir_id,
1407 ident: keywords::Invalid.ident(),
1408 attrs: Default::default(),
1409 node: exist_ty_item_kind,
1410 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1411 span: exist_ty_span,
1414 // Insert the item into the global list. This usually happens
1415 // automatically for all AST items. But this existential type item
1416 // does not actually exist in the AST.
1417 lctx.insert_item(exist_ty_id.node_id, exist_ty_item);
1419 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1420 hir::TyKind::Def(hir::ItemId { id: exist_ty_id.node_id }, lifetimes)
1424 fn lifetimes_from_impl_trait_bounds(
1426 exist_ty_id: NodeId,
1427 parent_index: DefIndex,
1428 bounds: &hir::GenericBounds,
1429 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1430 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1431 // appear in the bounds, excluding lifetimes that are created within the bounds.
1432 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1433 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1434 context: &'r mut LoweringContext<'a>,
1436 exist_ty_id: NodeId,
1437 collect_elided_lifetimes: bool,
1438 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1439 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1440 output_lifetimes: Vec<hir::GenericArg>,
1441 output_lifetime_params: Vec<hir::GenericParam>,
1444 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1445 fn nested_visit_map<'this>(
1447 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1448 hir::intravisit::NestedVisitorMap::None
1451 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1452 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1453 if parameters.parenthesized {
1454 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1455 self.collect_elided_lifetimes = false;
1456 hir::intravisit::walk_generic_args(self, span, parameters);
1457 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1459 hir::intravisit::walk_generic_args(self, span, parameters);
1463 fn visit_ty(&mut self, t: &'v hir::Ty) {
1464 // Don't collect elided lifetimes used inside of `fn()` syntax.
1465 if let hir::TyKind::BareFn(_) = t.node {
1466 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1467 self.collect_elided_lifetimes = false;
1469 // Record the "stack height" of `for<'a>` lifetime bindings
1470 // to be able to later fully undo their introduction.
1471 let old_len = self.currently_bound_lifetimes.len();
1472 hir::intravisit::walk_ty(self, t);
1473 self.currently_bound_lifetimes.truncate(old_len);
1475 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1477 hir::intravisit::walk_ty(self, t)
1481 fn visit_poly_trait_ref(
1483 trait_ref: &'v hir::PolyTraitRef,
1484 modifier: hir::TraitBoundModifier,
1486 // Record the "stack height" of `for<'a>` lifetime bindings
1487 // to be able to later fully undo their introduction.
1488 let old_len = self.currently_bound_lifetimes.len();
1489 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1490 self.currently_bound_lifetimes.truncate(old_len);
1493 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1494 // Record the introduction of 'a in `for<'a> ...`.
1495 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1496 // Introduce lifetimes one at a time so that we can handle
1497 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1498 let lt_name = hir::LifetimeName::Param(param.name);
1499 self.currently_bound_lifetimes.push(lt_name);
1502 hir::intravisit::walk_generic_param(self, param);
1505 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1506 let name = match lifetime.name {
1507 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1508 if self.collect_elided_lifetimes {
1509 // Use `'_` for both implicit and underscore lifetimes in
1510 // `abstract type Foo<'_>: SomeTrait<'_>;`.
1511 hir::LifetimeName::Underscore
1516 hir::LifetimeName::Param(_) => lifetime.name,
1517 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1520 if !self.currently_bound_lifetimes.contains(&name)
1521 && !self.already_defined_lifetimes.contains(&name) {
1522 self.already_defined_lifetimes.insert(name);
1524 let LoweredNodeId { node_id, hir_id } = self.context.next_id();
1525 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1528 span: lifetime.span,
1532 // We need to manually create the ids here, because the
1533 // definitions will go into the explicit `existential type`
1534 // declaration and thus need to have their owner set to that item
1535 let def_node_id = self.context.sess.next_node_id();
1536 let LoweredNodeId { node_id: _, hir_id } =
1537 self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1538 self.context.resolver.definitions().create_def_with_parent(
1541 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1542 DefIndexAddressSpace::High,
1547 let (name, kind) = match name {
1548 hir::LifetimeName::Underscore => (
1549 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident()),
1550 hir::LifetimeParamKind::Elided,
1552 hir::LifetimeName::Param(param_name) => (
1554 hir::LifetimeParamKind::Explicit,
1556 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1559 self.output_lifetime_params.push(hir::GenericParam {
1563 span: lifetime.span,
1564 pure_wrt_drop: false,
1567 kind: hir::GenericParamKind::Lifetime { kind }
1573 let mut lifetime_collector = ImplTraitLifetimeCollector {
1575 parent: parent_index,
1577 collect_elided_lifetimes: true,
1578 currently_bound_lifetimes: Vec::new(),
1579 already_defined_lifetimes: FxHashSet::default(),
1580 output_lifetimes: Vec::new(),
1581 output_lifetime_params: Vec::new(),
1584 for bound in bounds {
1585 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1589 lifetime_collector.output_lifetimes.into(),
1590 lifetime_collector.output_lifetime_params.into(),
1594 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1599 .map(|x| self.lower_foreign_item(x))
1604 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1611 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1613 node: hir::VariantKind {
1614 ident: v.node.ident,
1615 attrs: self.lower_attrs(&v.node.attrs),
1616 data: self.lower_variant_data(&v.node.data),
1617 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1626 qself: &Option<QSelf>,
1628 param_mode: ParamMode,
1629 mut itctx: ImplTraitContext<'_>,
1631 let qself_position = qself.as_ref().map(|q| q.position);
1632 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1634 let resolution = self.resolver
1636 .unwrap_or_else(|| PathResolution::new(Def::Err));
1638 let proj_start = p.segments.len() - resolution.unresolved_segments();
1639 let path = P(hir::Path {
1640 def: resolution.base_def(),
1641 segments: p.segments[..proj_start]
1644 .map(|(i, segment)| {
1645 let param_mode = match (qself_position, param_mode) {
1646 (Some(j), ParamMode::Optional) if i < j => {
1647 // This segment is part of the trait path in a
1648 // qualified path - one of `a`, `b` or `Trait`
1649 // in `<X as a::b::Trait>::T::U::method`.
1655 // Figure out if this is a type/trait segment,
1656 // which may need lifetime elision performed.
1657 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1658 krate: def_id.krate,
1659 index: this.def_key(def_id).parent.expect("missing parent"),
1661 let type_def_id = match resolution.base_def() {
1662 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1663 Some(parent_def_id(self, def_id))
1665 Def::Variant(def_id) if i + 1 == proj_start => {
1666 Some(parent_def_id(self, def_id))
1669 | Def::Union(def_id)
1671 | Def::TyAlias(def_id)
1672 | Def::Trait(def_id) if i + 1 == proj_start =>
1678 let parenthesized_generic_args = match resolution.base_def() {
1679 // `a::b::Trait(Args)`
1680 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1681 // `a::b::Trait(Args)::TraitItem`
1682 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1683 if i + 2 == proj_start =>
1685 ParenthesizedGenericArgs::Ok
1687 // Avoid duplicated errors.
1688 Def::Err => ParenthesizedGenericArgs::Ok,
1694 | Def::Variant(..) if i + 1 == proj_start =>
1696 ParenthesizedGenericArgs::Err
1698 // A warning for now, for compatibility reasons
1699 _ => ParenthesizedGenericArgs::Warn,
1702 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1703 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1706 assert!(!def_id.is_local());
1708 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1709 let n = item_generics.own_counts().lifetimes;
1710 self.type_def_lifetime_params.insert(def_id, n);
1713 self.lower_path_segment(
1718 parenthesized_generic_args,
1727 // Simple case, either no projections, or only fully-qualified.
1728 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
1729 if resolution.unresolved_segments() == 0 {
1730 return hir::QPath::Resolved(qself, path);
1733 // Create the innermost type that we're projecting from.
1734 let mut ty = if path.segments.is_empty() {
1735 // If the base path is empty that means there exists a
1736 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
1737 qself.expect("missing QSelf for <T>::...")
1739 // Otherwise, the base path is an implicit `Self` type path,
1740 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1741 // `<I as Iterator>::Item::default`.
1742 let new_id = self.next_id();
1743 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1746 // Anything after the base path are associated "extensions",
1747 // out of which all but the last one are associated types,
1748 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1749 // * base path is `std::vec::Vec<T>`
1750 // * "extensions" are `IntoIter`, `Item` and `clone`
1751 // * type nodes are:
1752 // 1. `std::vec::Vec<T>` (created above)
1753 // 2. `<std::vec::Vec<T>>::IntoIter`
1754 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1755 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1756 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1757 let segment = P(self.lower_path_segment(
1762 ParenthesizedGenericArgs::Warn,
1766 let qpath = hir::QPath::TypeRelative(ty, segment);
1768 // It's finished, return the extension of the right node type.
1769 if i == p.segments.len() - 1 {
1773 // Wrap the associated extension in another type node.
1774 let new_id = self.next_id();
1775 ty = P(self.ty_path(new_id, p.span, qpath));
1778 // We should've returned in the for loop above.
1781 "lower_qpath: no final extension segment in {}..{}",
1787 fn lower_path_extra(
1791 param_mode: ParamMode,
1792 explicit_owner: Option<NodeId>,
1796 segments: p.segments
1799 self.lower_path_segment(
1804 ParenthesizedGenericArgs::Err,
1805 ImplTraitContext::disallowed(),
1814 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1815 let def = self.expect_full_def(id);
1816 self.lower_path_extra(def, p, param_mode, None)
1819 fn lower_path_segment(
1822 segment: &PathSegment,
1823 param_mode: ParamMode,
1824 expected_lifetimes: usize,
1825 parenthesized_generic_args: ParenthesizedGenericArgs,
1826 itctx: ImplTraitContext<'_>,
1827 explicit_owner: Option<NodeId>,
1828 ) -> hir::PathSegment {
1829 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1830 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
1831 match **generic_args {
1832 GenericArgs::AngleBracketed(ref data) => {
1833 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1835 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1836 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1837 ParenthesizedGenericArgs::Warn => {
1838 self.sess.buffer_lint(
1839 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1844 (hir::GenericArgs::none(), true)
1846 ParenthesizedGenericArgs::Err => {
1847 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
1848 err.span_label(data.span, "only `Fn` traits may use parentheses");
1849 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
1850 // Do not suggest going from `Trait()` to `Trait<>`
1851 if data.inputs.len() > 0 {
1852 err.span_suggestion(
1854 "use angle brackets instead",
1855 format!("<{}>", &snippet[1..snippet.len() - 1]),
1856 Applicability::MaybeIncorrect,
1861 (self.lower_angle_bracketed_parameter_data(
1862 &data.as_angle_bracketed_args(),
1870 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1873 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1874 GenericArg::Lifetime(_) => true,
1877 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1878 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1879 if !generic_args.parenthesized && !has_lifetimes {
1881 self.elided_path_lifetimes(path_span, expected_lifetimes)
1883 .map(|lt| GenericArg::Lifetime(lt))
1884 .chain(generic_args.args.into_iter())
1886 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1887 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1888 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1889 let no_bindings = generic_args.bindings.is_empty();
1890 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1891 // If there are no (non-implicit) generic args or associated-type
1892 // bindings, our suggestion includes the angle brackets.
1893 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1895 // Otherwise—sorry, this is kind of gross—we need to infer the
1896 // place to splice in the `'_, ` from the generics that do exist.
1897 let first_generic_span = first_generic_span
1898 .expect("already checked that type args or bindings exist");
1899 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1901 self.sess.buffer_lint_with_diagnostic(
1902 ELIDED_LIFETIMES_IN_PATHS,
1905 "hidden lifetime parameters in types are deprecated",
1906 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1907 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1913 let def = self.expect_full_def(segment.id);
1914 let id = if let Some(owner) = explicit_owner {
1915 self.lower_node_id_with_owner(segment.id, owner)
1917 self.lower_node_id(segment.id)
1920 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
1921 segment.ident, segment.id, id,
1924 hir::PathSegment::new(
1934 fn lower_angle_bracketed_parameter_data(
1936 data: &AngleBracketedArgs,
1937 param_mode: ParamMode,
1938 mut itctx: ImplTraitContext<'_>,
1939 ) -> (hir::GenericArgs, bool) {
1940 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1941 let has_types = args.iter().any(|arg| match arg {
1942 ast::GenericArg::Type(_) => true,
1946 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1947 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1948 parenthesized: false,
1950 !has_types && param_mode == ParamMode::Optional)
1953 fn lower_parenthesized_parameter_data(
1955 data: &ParenthesizedArgs,
1956 ) -> (hir::GenericArgs, bool) {
1957 // Switch to `PassThrough` mode for anonymous lifetimes: this
1958 // means that we permit things like `&Ref<T>`, where `Ref` has
1959 // a hidden lifetime parameter. This is needed for backwards
1960 // compatibility, even in contexts like an impl header where
1961 // we generally don't permit such things (see #51008).
1962 self.with_anonymous_lifetime_mode(
1963 AnonymousLifetimeMode::PassThrough,
1965 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
1968 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
1970 let mk_tup = |this: &mut Self, tys, span| {
1971 let LoweredNodeId { node_id, hir_id } = this.next_id();
1972 hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1974 let LoweredNodeId { node_id, hir_id } = this.next_id();
1978 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1983 ident: Ident::from_str(FN_OUTPUT_NAME),
1986 .map(|ty| this.lower_ty(&ty, ImplTraitContext::disallowed()))
1987 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1988 span: output.as_ref().map_or(span, |ty| ty.span),
1991 parenthesized: true,
1999 fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[hir::ItemId; 1]>) {
2000 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
2001 let mut ids = SmallVec::<[hir::ItemId; 1]>::new();
2002 if self.sess.features_untracked().impl_trait_in_bindings {
2003 if let Some(ref ty) = l.ty {
2004 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2005 visitor.visit_ty(ty);
2008 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2014 .map(|t| self.lower_ty(t,
2015 if self.sess.features_untracked().impl_trait_in_bindings {
2016 ImplTraitContext::Existential(Some(parent_def_id))
2018 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2021 pat: self.lower_pat(&l.pat),
2022 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2024 attrs: l.attrs.clone(),
2025 source: hir::LocalSource::Normal,
2029 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
2031 Mutability::Mutable => hir::MutMutable,
2032 Mutability::Immutable => hir::MutImmutable,
2036 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
2037 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
2041 pat: self.lower_pat(&arg.pat),
2045 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2048 .map(|arg| match arg.pat.node {
2049 PatKind::Ident(_, ident, _) => ident,
2050 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
2055 // Lowers a function declaration.
2057 // decl: the unlowered (ast) function declaration.
2058 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
2059 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2060 // make_ret_async is also `Some`.
2061 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
2062 // This guards against trait declarations and implementations where impl Trait is
2064 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2065 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
2066 // return type impl Trait item.
2070 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2071 impl_trait_return_allow: bool,
2072 make_ret_async: Option<NodeId>,
2073 ) -> P<hir::FnDecl> {
2074 let inputs = decl.inputs
2077 if let Some((_, ref mut ibty)) = in_band_ty_params {
2078 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2080 self.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2083 .collect::<HirVec<_>>();
2085 let output = if let Some(ret_id) = make_ret_async {
2086 self.lower_async_fn_ret_ty(
2089 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
2094 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2095 Some((def_id, _)) if impl_trait_return_allow => {
2096 hir::Return(self.lower_ty(ty,
2097 ImplTraitContext::Existential(Some(def_id))))
2100 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2103 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2110 variadic: decl.variadic,
2111 implicit_self: decl.inputs.get(0).map_or(
2112 hir::ImplicitSelfKind::None,
2114 let is_mutable_pat = match arg.pat.node {
2115 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2116 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2117 mt == Mutability::Mutable,
2122 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2123 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2124 // Given we are only considering `ImplicitSelf` types, we needn't consider
2125 // the case where we have a mutable pattern to a reference as that would
2126 // no longer be an `ImplicitSelf`.
2127 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2128 mt.mutbl == ast::Mutability::Mutable =>
2129 hir::ImplicitSelfKind::MutRef,
2130 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2131 hir::ImplicitSelfKind::ImmRef,
2132 _ => hir::ImplicitSelfKind::None,
2139 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
2141 // fn_span: the span of the async function declaration. Used for error reporting.
2142 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
2143 // output: unlowered output type (`T` in `-> T`)
2144 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
2145 fn lower_async_fn_ret_ty(
2148 output: &FunctionRetTy,
2150 return_impl_trait_id: NodeId,
2151 ) -> hir::FunctionRetTy {
2152 // Get lifetimes used in the input arguments to the function. Our output type must also
2153 // have the same lifetime.
2154 // FIXME(cramertj): multiple different lifetimes are not allowed because
2155 // `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither is a subset
2156 // of the other. We really want some new lifetime that is a subset of all input lifetimes,
2157 // but that doesn't exist at the moment.
2159 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
2160 context: &'r mut LoweringContext<'a>,
2161 // Lifetimes bound by HRTB.
2162 currently_bound_lifetimes: Vec<hir::LifetimeName>,
2163 // Whether to count elided lifetimes.
2164 // Disabled inside of `Fn` or `fn` syntax.
2165 collect_elided_lifetimes: bool,
2166 // The lifetime found.
2167 // Multiple different or elided lifetimes cannot appear in async fn for now.
2168 output_lifetime: Option<(hir::LifetimeName, Span)>,
2171 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
2172 fn nested_visit_map<'this>(
2174 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
2175 hir::intravisit::NestedVisitorMap::None
2178 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
2179 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2180 if parameters.parenthesized {
2181 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2182 self.collect_elided_lifetimes = false;
2183 hir::intravisit::walk_generic_args(self, span, parameters);
2184 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2186 hir::intravisit::walk_generic_args(self, span, parameters);
2190 fn visit_ty(&mut self, t: &'v hir::Ty) {
2191 // Don't collect elided lifetimes used inside of `fn()` syntax.
2192 if let &hir::TyKind::BareFn(_) = &t.node {
2193 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2194 self.collect_elided_lifetimes = false;
2196 // Record the "stack height" of `for<'a>` lifetime bindings
2197 // to be able to later fully undo their introduction.
2198 let old_len = self.currently_bound_lifetimes.len();
2199 hir::intravisit::walk_ty(self, t);
2200 self.currently_bound_lifetimes.truncate(old_len);
2202 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2204 hir::intravisit::walk_ty(self, t);
2208 fn visit_poly_trait_ref(
2210 trait_ref: &'v hir::PolyTraitRef,
2211 modifier: hir::TraitBoundModifier,
2213 // Record the "stack height" of `for<'a>` lifetime bindings
2214 // to be able to later fully undo their introduction.
2215 let old_len = self.currently_bound_lifetimes.len();
2216 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2217 self.currently_bound_lifetimes.truncate(old_len);
2220 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2221 // Record the introduction of 'a in `for<'a> ...`
2222 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2223 // Introduce lifetimes one at a time so that we can handle
2224 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2225 let lt_name = hir::LifetimeName::Param(param.name);
2226 self.currently_bound_lifetimes.push(lt_name);
2229 hir::intravisit::walk_generic_param(self, param);
2232 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2233 let name = match lifetime.name {
2234 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2235 if self.collect_elided_lifetimes {
2236 // Use `'_` for both implicit and underscore lifetimes in
2237 // `abstract type Foo<'_>: SomeTrait<'_>;`
2238 hir::LifetimeName::Underscore
2243 hir::LifetimeName::Param(_) => lifetime.name,
2244 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
2247 if !self.currently_bound_lifetimes.contains(&name) {
2248 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2249 // We don't currently have a reliable way to desugar `async fn` with
2250 // multiple potentially unrelated input lifetimes into
2251 // `-> impl Trait + 'lt`, so we report an error in this case.
2252 if current_lt_name != name {
2255 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2257 "multiple different lifetimes used in arguments of `async fn`",
2259 .span_label(current_lt_span, "first lifetime here")
2260 .span_label(lifetime.span, "different lifetime here")
2261 .help("`async fn` can only accept borrowed values \
2262 with identical lifetimes")
2264 } else if current_lt_name.is_elided() && name.is_elided() {
2267 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2269 "multiple elided lifetimes used in arguments of `async fn`",
2271 .span_label(current_lt_span, "first lifetime here")
2272 .span_label(lifetime.span, "different lifetime here")
2273 .help("consider giving these arguments named lifetimes")
2277 self.output_lifetime = Some((name, lifetime.span));
2283 let bound_lifetime = {
2284 let mut lifetime_collector = AsyncFnLifetimeCollector {
2286 currently_bound_lifetimes: Vec::new(),
2287 collect_elided_lifetimes: true,
2288 output_lifetime: None,
2292 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2294 lifetime_collector.output_lifetime
2297 let span = match output {
2298 FunctionRetTy::Ty(ty) => ty.span,
2299 FunctionRetTy::Default(span) => *span,
2302 let impl_trait_ty = self.lower_existential_impl_trait(
2303 span, Some(fn_def_id), return_impl_trait_id, |this| {
2304 let output_ty = match output {
2305 FunctionRetTy::Ty(ty) => {
2306 this.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2308 FunctionRetTy::Default(span) => {
2309 let LoweredNodeId { node_id, hir_id } = this.next_id();
2313 node: hir::TyKind::Tup(hir_vec![]),
2320 let LoweredNodeId { node_id, hir_id } = this.next_id();
2321 let future_params = P(hir::GenericArgs {
2323 bindings: hir_vec![hir::TypeBinding {
2324 ident: Ident::from_str(FN_OUTPUT_NAME),
2330 parenthesized: false,
2334 this.std_path(span, &["future", "Future"], Some(future_params), false);
2336 let LoweredNodeId { node_id, hir_id } = this.next_id();
2337 let mut bounds = vec![
2338 hir::GenericBound::Trait(
2340 trait_ref: hir::TraitRef {
2345 bound_generic_params: hir_vec![],
2348 hir::TraitBoundModifier::None
2352 if let Some((name, span)) = bound_lifetime {
2353 let LoweredNodeId { node_id, hir_id } = this.next_id();
2354 bounds.push(hir::GenericBound::Outlives(
2355 hir::Lifetime { id: node_id, hir_id, name, span }));
2358 hir::HirVec::from(bounds)
2361 let LoweredNodeId { node_id, hir_id } = self.next_id();
2362 let impl_trait_ty = P(hir::Ty {
2364 node: impl_trait_ty,
2369 hir::FunctionRetTy::Return(impl_trait_ty)
2372 fn lower_param_bound(
2375 itctx: ImplTraitContext<'_>,
2376 ) -> hir::GenericBound {
2378 GenericBound::Trait(ref ty, modifier) => {
2379 hir::GenericBound::Trait(
2380 self.lower_poly_trait_ref(ty, itctx),
2381 self.lower_trait_bound_modifier(modifier),
2384 GenericBound::Outlives(ref lifetime) => {
2385 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2390 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2391 let span = l.ident.span;
2393 ident if ident.name == keywords::StaticLifetime.name() =>
2394 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2395 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2396 match self.anonymous_lifetime_mode {
2397 AnonymousLifetimeMode::CreateParameter => {
2398 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2399 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2402 AnonymousLifetimeMode::PassThrough => {
2403 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2406 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2409 self.maybe_collect_in_band_lifetime(ident);
2410 let param_name = ParamName::Plain(ident);
2411 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2416 fn new_named_lifetime(
2420 name: hir::LifetimeName,
2421 ) -> hir::Lifetime {
2422 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(id);
2432 fn lower_generic_params(
2434 params: &[GenericParam],
2435 add_bounds: &NodeMap<Vec<GenericBound>>,
2436 mut itctx: ImplTraitContext<'_>,
2437 ) -> hir::HirVec<hir::GenericParam> {
2438 params.iter().map(|param| {
2439 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2443 fn lower_generic_param(&mut self,
2444 param: &GenericParam,
2445 add_bounds: &NodeMap<Vec<GenericBound>>,
2446 mut itctx: ImplTraitContext<'_>)
2447 -> hir::GenericParam {
2448 let mut bounds = self.with_anonymous_lifetime_mode(
2449 AnonymousLifetimeMode::ReportError,
2450 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2453 let (name, kind) = match param.kind {
2454 GenericParamKind::Lifetime => {
2455 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2456 self.is_collecting_in_band_lifetimes = false;
2458 let lt = self.with_anonymous_lifetime_mode(
2459 AnonymousLifetimeMode::ReportError,
2460 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2462 let param_name = match lt.name {
2463 hir::LifetimeName::Param(param_name) => param_name,
2464 hir::LifetimeName::Implicit
2465 | hir::LifetimeName::Underscore
2466 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2467 hir::LifetimeName::Error => ParamName::Error,
2470 let kind = hir::GenericParamKind::Lifetime {
2471 kind: hir::LifetimeParamKind::Explicit
2474 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2478 GenericParamKind::Type { ref default, .. } => {
2479 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2480 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2481 // Instead, use `gensym("Self")` to create a distinct name that looks the same.
2482 let ident = if param.ident.name == keywords::SelfUpper.name() {
2483 param.ident.gensym()
2488 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2489 if !add_bounds.is_empty() {
2490 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2491 bounds = bounds.into_iter()
2496 let kind = hir::GenericParamKind::Type {
2497 default: default.as_ref().map(|x| {
2498 self.lower_ty(x, ImplTraitContext::disallowed())
2500 synthetic: param.attrs.iter()
2501 .filter(|attr| attr.check_name("rustc_synthetic"))
2502 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2506 (hir::ParamName::Plain(ident), kind)
2508 GenericParamKind::Const { .. } => {
2509 // FIXME(const_generics): const generics are not yet defined in the HIR.
2510 self.sess.struct_span_err(
2512 "const generics in any position are currently unsupported",
2514 self.sess.abort_if_errors();
2519 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(param.id);
2525 span: param.ident.span,
2526 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2527 attrs: self.lower_attrs(¶m.attrs),
2535 generics: &Generics,
2536 itctx: ImplTraitContext<'_>)
2539 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2540 // FIXME: this could probably be done with less rightward drift. Also looks like two control
2541 // paths where report_error is called are also the only paths that advance to after
2542 // the match statement, so the error reporting could probably just be moved there.
2543 let mut add_bounds: NodeMap<Vec<_>> = Default::default();
2544 for pred in &generics.where_clause.predicates {
2545 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2546 'next_bound: for bound in &bound_pred.bounds {
2547 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2548 let report_error = |this: &mut Self| {
2549 this.diagnostic().span_err(
2550 bound_pred.bounded_ty.span,
2551 "`?Trait` bounds are only permitted at the \
2552 point where a type parameter is declared",
2555 // Check if the where clause type is a plain type parameter.
2556 match bound_pred.bounded_ty.node {
2557 TyKind::Path(None, ref path)
2558 if path.segments.len() == 1
2559 && bound_pred.bound_generic_params.is_empty() =>
2561 if let Some(Def::TyParam(def_id)) = self.resolver
2562 .get_resolution(bound_pred.bounded_ty.id)
2563 .map(|d| d.base_def())
2565 if let Some(node_id) =
2566 self.resolver.definitions().as_local_node_id(def_id)
2568 for param in &generics.params {
2570 GenericParamKind::Type { .. } => {
2571 if node_id == param.id {
2572 add_bounds.entry(param.id)
2574 .push(bound.clone());
2575 continue 'next_bound;
2585 _ => report_error(self),
2593 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2594 where_clause: self.lower_where_clause(&generics.where_clause),
2595 span: generics.span,
2599 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2600 self.with_anonymous_lifetime_mode(
2601 AnonymousLifetimeMode::ReportError,
2603 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(wc.id);
2608 predicates: wc.predicates
2610 .map(|predicate| this.lower_where_predicate(predicate))
2617 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2619 WherePredicate::BoundPredicate(WhereBoundPredicate {
2620 ref bound_generic_params,
2625 self.with_in_scope_lifetime_defs(
2626 &bound_generic_params,
2628 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2629 bound_generic_params: this.lower_generic_params(
2630 bound_generic_params,
2631 &NodeMap::default(),
2632 ImplTraitContext::disallowed(),
2634 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
2637 .filter_map(|bound| match *bound {
2638 // Ignore `?Trait` bounds.
2639 // They were copied into type parameters already.
2640 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2641 _ => Some(this.lower_param_bound(
2643 ImplTraitContext::disallowed(),
2652 WherePredicate::RegionPredicate(WhereRegionPredicate {
2656 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2658 lifetime: self.lower_lifetime(lifetime),
2659 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2661 WherePredicate::EqPredicate(WhereEqPredicate {
2667 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(id);
2669 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2672 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
2673 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
2680 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2682 VariantData::Struct(ref fields, id) => {
2683 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(id);
2685 hir::VariantData::Struct(
2689 .map(|f| self.lower_struct_field(f))
2695 VariantData::Tuple(ref fields, id) => {
2696 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(id);
2698 hir::VariantData::Tuple(
2702 .map(|f| self.lower_struct_field(f))
2708 VariantData::Unit(id) => {
2709 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(id);
2711 hir::VariantData::Unit(node_id, hir_id)
2716 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2717 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2718 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2719 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2721 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.ref_id);
2729 fn lower_poly_trait_ref(
2732 mut itctx: ImplTraitContext<'_>,
2733 ) -> hir::PolyTraitRef {
2734 let bound_generic_params = self.lower_generic_params(
2735 &p.bound_generic_params,
2736 &NodeMap::default(),
2739 let trait_ref = self.with_parent_impl_lifetime_defs(
2740 &bound_generic_params,
2741 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2745 bound_generic_params,
2751 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2752 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(f.id);
2758 ident: match f.ident {
2759 Some(ident) => ident,
2760 // FIXME(jseyfried): positional field hygiene
2761 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2763 vis: self.lower_visibility(&f.vis, None),
2764 ty: self.lower_ty(&f.ty, ImplTraitContext::disallowed()),
2765 attrs: self.lower_attrs(&f.attrs),
2769 fn lower_field(&mut self, f: &Field) -> hir::Field {
2770 let LoweredNodeId { node_id, hir_id } = self.next_id();
2776 expr: P(self.lower_expr(&f.expr)),
2778 is_shorthand: f.is_shorthand,
2782 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2784 ty: self.lower_ty(&mt.ty, itctx),
2785 mutbl: self.lower_mutability(mt.mutbl),
2789 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2790 -> hir::GenericBounds {
2791 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2794 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2795 let mut expr = None;
2797 let mut stmts = vec![];
2799 for (index, stmt) in b.stmts.iter().enumerate() {
2800 if index == b.stmts.len() - 1 {
2801 if let StmtKind::Expr(ref e) = stmt.node {
2802 expr = Some(P(self.lower_expr(e)));
2804 stmts.extend(self.lower_stmt(stmt));
2807 stmts.extend(self.lower_stmt(stmt));
2811 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2816 stmts: stmts.into(),
2818 rules: self.lower_block_check_mode(&b.rules),
2824 fn lower_async_body(
2830 self.lower_body(Some(decl), |this| {
2831 if let IsAsync::Async { closure_id, .. } = asyncness {
2832 let async_expr = this.make_async_expr(
2833 CaptureBy::Value, closure_id, None,
2835 let body = this.lower_block(body, false);
2836 this.expr_block(body, ThinVec::new())
2838 this.expr(body.span, async_expr, ThinVec::new())
2840 let body = this.lower_block(body, false);
2841 this.expr_block(body, ThinVec::new())
2850 attrs: &hir::HirVec<Attribute>,
2851 vis: &mut hir::Visibility,
2853 ) -> hir::ItemKind {
2855 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2856 ItemKind::Use(ref use_tree) => {
2857 // Start with an empty prefix
2860 span: use_tree.span,
2863 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
2865 ItemKind::Static(ref t, m, ref e) => {
2866 let value = self.lower_body(None, |this| this.lower_expr(e));
2867 hir::ItemKind::Static(
2870 if self.sess.features_untracked().impl_trait_in_bindings {
2871 ImplTraitContext::Existential(None)
2873 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2876 self.lower_mutability(m),
2880 ItemKind::Const(ref t, ref e) => {
2881 let value = self.lower_body(None, |this| this.lower_expr(e));
2882 hir::ItemKind::Const(
2885 if self.sess.features_untracked().impl_trait_in_bindings {
2886 ImplTraitContext::Existential(None)
2888 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2894 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2895 let fn_def_id = self.resolver.definitions().local_def_id(id);
2896 self.with_new_scopes(|this| {
2897 // Note: we don't need to change the return type from `T` to
2898 // `impl Future<Output = T>` here because lower_body
2899 // only cares about the input argument patterns in the function
2900 // declaration (decl), not the return types.
2901 let body_id = this.lower_async_body(decl, header.asyncness, body);
2903 let (generics, fn_decl) = this.add_in_band_defs(
2906 AnonymousLifetimeMode::PassThrough,
2907 |this, idty| this.lower_fn_decl(
2909 Some((fn_def_id, idty)),
2911 header.asyncness.opt_return_id()
2917 this.lower_fn_header(header),
2923 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2924 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2925 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2926 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2927 self.lower_ty(t, ImplTraitContext::disallowed()),
2928 self.lower_generics(generics, ImplTraitContext::disallowed()),
2930 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2931 generics: self.lower_generics(generics, ImplTraitContext::disallowed()),
2932 bounds: self.lower_param_bounds(b, ImplTraitContext::disallowed()),
2933 impl_trait_fn: None,
2935 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2937 variants: enum_definition
2940 .map(|x| self.lower_variant(x))
2943 self.lower_generics(generics, ImplTraitContext::disallowed()),
2945 ItemKind::Struct(ref struct_def, ref generics) => {
2946 let struct_def = self.lower_variant_data(struct_def);
2947 hir::ItemKind::Struct(
2949 self.lower_generics(generics, ImplTraitContext::disallowed()),
2952 ItemKind::Union(ref vdata, ref generics) => {
2953 let vdata = self.lower_variant_data(vdata);
2954 hir::ItemKind::Union(
2956 self.lower_generics(generics, ImplTraitContext::disallowed()),
2968 let def_id = self.resolver.definitions().local_def_id(id);
2970 // Lower the "impl header" first. This ordering is important
2971 // for in-band lifetimes! Consider `'a` here:
2973 // impl Foo<'a> for u32 {
2974 // fn method(&'a self) { .. }
2977 // Because we start by lowering the `Foo<'a> for u32`
2978 // part, we will add `'a` to the list of generics on
2979 // the impl. When we then encounter it later in the
2980 // method, it will not be considered an in-band
2981 // lifetime to be added, but rather a reference to a
2983 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2986 AnonymousLifetimeMode::CreateParameter,
2988 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2989 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
2992 if let Some(ref trait_ref) = trait_ref {
2993 if let Def::Trait(def_id) = trait_ref.path.def {
2994 this.trait_impls.entry(def_id).or_default().push(id);
2998 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
3000 (trait_ref, lowered_ty)
3004 let new_impl_items = self.with_in_scope_lifetime_defs(
3005 &ast_generics.params,
3009 .map(|item| this.lower_impl_item_ref(item))
3014 hir::ItemKind::Impl(
3015 self.lower_unsafety(unsafety),
3016 self.lower_impl_polarity(polarity),
3017 self.lower_defaultness(defaultness, true /* [1] */),
3024 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
3025 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
3028 .map(|item| self.lower_trait_item_ref(item))
3030 hir::ItemKind::Trait(
3031 self.lower_is_auto(is_auto),
3032 self.lower_unsafety(unsafety),
3033 self.lower_generics(generics, ImplTraitContext::disallowed()),
3038 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
3039 self.lower_generics(generics, ImplTraitContext::disallowed()),
3040 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3042 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
3045 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
3046 // not cause an assertion failure inside the `lower_defaultness` function.
3054 vis: &mut hir::Visibility,
3056 attrs: &hir::HirVec<Attribute>,
3057 ) -> hir::ItemKind {
3058 debug!("lower_use_tree(tree={:?})", tree);
3059 debug!("lower_use_tree: vis = {:?}", vis);
3061 let path = &tree.prefix;
3062 let segments = prefix
3065 .chain(path.segments.iter())
3070 UseTreeKind::Simple(rename, id1, id2) => {
3071 *ident = tree.ident();
3073 // First, apply the prefix to the path.
3074 let mut path = Path {
3079 // Correctly resolve `self` imports.
3080 if path.segments.len() > 1
3081 && path.segments.last().unwrap().ident.name == keywords::SelfLower.name()
3083 let _ = path.segments.pop();
3084 if rename.is_none() {
3085 *ident = path.segments.last().unwrap().ident;
3089 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
3090 let mut defs = self.expect_full_def_from_use(id);
3091 // We want to return *something* from this function, so hold onto the first item
3093 let ret_def = defs.next().unwrap_or(Def::Err);
3095 // Here, we are looping over namespaces, if they exist for the definition
3096 // being imported. We only handle type and value namespaces because we
3097 // won't be dealing with macros in the rest of the compiler.
3098 // Essentially a single `use` which imports two names is desugared into
3100 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
3101 let vis = vis.clone();
3102 let ident = ident.clone();
3103 let mut path = path.clone();
3104 for seg in &mut path.segments {
3105 seg.id = self.sess.next_node_id();
3107 let span = path.span;
3108 self.resolver.definitions().create_def_with_parent(
3112 DefIndexAddressSpace::High,
3115 self.allocate_hir_id_counter(new_node_id, &path);
3117 self.with_hir_id_owner(new_node_id, |this| {
3118 let new_id = this.lower_node_id(new_node_id);
3120 this.lower_path_extra(def, &path, ParamMode::Explicit, None);
3121 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
3122 let vis_kind = match vis.node {
3123 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3124 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3125 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3126 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3127 let id = this.next_id();
3128 let path = this.renumber_segment_ids(path);
3129 hir::VisibilityKind::Restricted {
3136 let vis = respan(vis.span, vis_kind);
3142 hir_id: new_id.hir_id,
3144 attrs: attrs.clone(),
3154 P(self.lower_path_extra(ret_def, &path, ParamMode::Explicit, None));
3155 hir::ItemKind::Use(path, hir::UseKind::Single)
3157 UseTreeKind::Glob => {
3158 let path = P(self.lower_path(
3164 ParamMode::Explicit,
3166 hir::ItemKind::Use(path, hir::UseKind::Glob)
3168 UseTreeKind::Nested(ref trees) => {
3169 // Nested imports are desugared into simple imports.
3170 // So, if we start with
3173 // pub(x) use foo::{a, b};
3176 // we will create three items:
3179 // pub(x) use foo::a;
3180 // pub(x) use foo::b;
3181 // pub(x) use foo::{}; // <-- this is called the `ListStem`
3184 // The first two are produced by recursively invoking
3185 // `lower_use_tree` (and indeed there may be things
3186 // like `use foo::{a::{b, c}}` and so forth). They
3187 // wind up being directly added to
3188 // `self.items`. However, the structure of this
3189 // function also requires us to return one item, and
3190 // for that we return the `{}` import (called the
3195 span: prefix.span.to(path.span),
3198 // Add all the nested `PathListItem`s to the HIR.
3199 for &(ref use_tree, id) in trees {
3200 self.allocate_hir_id_counter(id, &use_tree);
3205 } = self.lower_node_id(id);
3207 let mut vis = vis.clone();
3208 let mut ident = ident.clone();
3209 let mut prefix = prefix.clone();
3211 // Give the segments new node-ids since they are being cloned.
3212 for seg in &mut prefix.segments {
3213 seg.id = self.sess.next_node_id();
3216 // Each `use` import is an item and thus are owners of the
3217 // names in the path. Up to this point the nested import is
3218 // the current owner, since we want each desugared import to
3219 // own its own names, we have to adjust the owner before
3220 // lowering the rest of the import.
3221 self.with_hir_id_owner(new_id, |this| {
3222 let item = this.lower_use_tree(use_tree,
3229 let vis_kind = match vis.node {
3230 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3231 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3232 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3233 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3234 let id = this.next_id();
3235 let path = this.renumber_segment_ids(path);
3236 hir::VisibilityKind::Restricted {
3243 let vis = respan(vis.span, vis_kind);
3251 attrs: attrs.clone(),
3254 span: use_tree.span,
3260 // Subtle and a bit hacky: we lower the privacy level
3261 // of the list stem to "private" most of the time, but
3262 // not for "restricted" paths. The key thing is that
3263 // we don't want it to stay as `pub` (with no caveats)
3264 // because that affects rustdoc and also the lints
3265 // about `pub` items. But we can't *always* make it
3266 // private -- particularly not for restricted paths --
3267 // because it contains node-ids that would then be
3268 // unused, failing the check that HirIds are "densely
3271 hir::VisibilityKind::Public |
3272 hir::VisibilityKind::Crate(_) |
3273 hir::VisibilityKind::Inherited => {
3274 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3276 hir::VisibilityKind::Restricted { .. } => {
3277 // Do nothing here, as described in the comment on the match.
3281 let def = self.expect_full_def_from_use(id).next().unwrap_or(Def::Err);
3282 let path = P(self.lower_path_extra(def, &prefix, ParamMode::Explicit, None));
3283 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3288 /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
3289 /// many times in the HIR tree; for each occurrence, we need to assign distinct
3290 /// node-ids. (See e.g., #56128.)
3291 fn renumber_segment_ids(&mut self, path: &P<hir::Path>) -> P<hir::Path> {
3292 debug!("renumber_segment_ids(path = {:?})", path);
3293 let mut path = path.clone();
3294 for seg in path.segments.iter_mut() {
3295 if seg.id.is_some() {
3296 seg.id = Some(self.next_id().node_id);
3302 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3303 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3304 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
3306 let (generics, node) = match i.node {
3307 TraitItemKind::Const(ref ty, ref default) => (
3308 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3309 hir::TraitItemKind::Const(
3310 self.lower_ty(ty, ImplTraitContext::disallowed()),
3313 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
3316 TraitItemKind::Method(ref sig, None) => {
3317 let names = self.lower_fn_args_to_names(&sig.decl);
3318 let (generics, sig) = self.lower_method_sig(
3325 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3327 TraitItemKind::Method(ref sig, Some(ref body)) => {
3328 let body_id = self.lower_body(Some(&sig.decl), |this| {
3329 let body = this.lower_block(body, false);
3330 this.expr_block(body, ThinVec::new())
3332 let (generics, sig) = self.lower_method_sig(
3339 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3341 TraitItemKind::Type(ref bounds, ref default) => (
3342 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3343 hir::TraitItemKind::Type(
3344 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3347 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3350 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3357 attrs: self.lower_attrs(&i.attrs),
3364 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3365 let (kind, has_default) = match i.node {
3366 TraitItemKind::Const(_, ref default) => {
3367 (hir::AssociatedItemKind::Const, default.is_some())
3369 TraitItemKind::Type(_, ref default) => {
3370 (hir::AssociatedItemKind::Type, default.is_some())
3372 TraitItemKind::Method(ref sig, ref default) => (
3373 hir::AssociatedItemKind::Method {
3374 has_self: sig.decl.has_self(),
3378 TraitItemKind::Macro(..) => unimplemented!(),
3381 id: hir::TraitItemId { node_id: i.id },
3384 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3389 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3390 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3391 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3393 let (generics, node) = match i.node {
3394 ImplItemKind::Const(ref ty, ref expr) => {
3395 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3397 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3398 hir::ImplItemKind::Const(
3399 self.lower_ty(ty, ImplTraitContext::disallowed()),
3404 ImplItemKind::Method(ref sig, ref body) => {
3405 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3406 let impl_trait_return_allow = !self.is_in_trait_impl;
3407 let (generics, sig) = self.lower_method_sig(
3411 impl_trait_return_allow,
3412 sig.header.asyncness.opt_return_id(),
3414 (generics, hir::ImplItemKind::Method(sig, body_id))
3416 ImplItemKind::Type(ref ty) => (
3417 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3418 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3420 ImplItemKind::Existential(ref bounds) => (
3421 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3422 hir::ImplItemKind::Existential(
3423 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3426 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3433 attrs: self.lower_attrs(&i.attrs),
3435 vis: self.lower_visibility(&i.vis, None),
3436 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3441 // [1] since `default impl` is not yet implemented, this is always true in impls
3444 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3446 id: hir::ImplItemId { node_id: i.id },
3449 vis: self.lower_visibility(&i.vis, Some(i.id)),
3450 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3451 kind: match i.node {
3452 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3453 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3454 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3455 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3456 has_self: sig.decl.has_self(),
3458 ImplItemKind::Macro(..) => unimplemented!(),
3462 // [1] since `default impl` is not yet implemented, this is always true in impls
3465 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3468 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3472 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3474 ItemKind::Use(ref use_tree) => {
3475 let mut vec = smallvec![hir::ItemId { id: i.id }];
3476 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3479 ItemKind::MacroDef(..) => SmallVec::new(),
3481 ItemKind::Impl(.., None, _, _) => smallvec![hir::ItemId { id: i.id }],
3482 ItemKind::Static(ref ty, ..) => {
3483 let mut ids = smallvec![hir::ItemId { id: i.id }];
3484 if self.sess.features_untracked().impl_trait_in_bindings {
3485 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3486 visitor.visit_ty(ty);
3490 ItemKind::Const(ref ty, ..) => {
3491 let mut ids = smallvec![hir::ItemId { id: i.id }];
3492 if self.sess.features_untracked().impl_trait_in_bindings {
3493 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3494 visitor.visit_ty(ty);
3498 _ => smallvec![hir::ItemId { id: i.id }],
3502 fn lower_item_id_use_tree(&mut self,
3505 vec: &mut SmallVec<[hir::ItemId; 1]>)
3508 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3509 vec.push(hir::ItemId { id });
3510 self.lower_item_id_use_tree(nested, id, vec);
3512 UseTreeKind::Glob => {}
3513 UseTreeKind::Simple(_, id1, id2) => {
3514 for (_, &id) in self.expect_full_def_from_use(base_id)
3516 .zip([id1, id2].iter())
3518 vec.push(hir::ItemId { id });
3524 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3525 let mut ident = i.ident;
3526 let mut vis = self.lower_visibility(&i.vis, None);
3527 let attrs = self.lower_attrs(&i.attrs);
3528 if let ItemKind::MacroDef(ref def) = i.node {
3529 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3530 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3531 let body = self.lower_token_stream(def.stream());
3532 let hir_id = self.lower_node_id(i.id).hir_id;
3533 self.exported_macros.push(hir::MacroDef {
3547 let node = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.node);
3549 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3562 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3563 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3564 let def_id = self.resolver.definitions().local_def_id(node_id);
3569 attrs: self.lower_attrs(&i.attrs),
3570 node: match i.node {
3571 ForeignItemKind::Fn(ref fdec, ref generics) => {
3572 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3575 AnonymousLifetimeMode::PassThrough,
3578 // Disallow impl Trait in foreign items
3579 this.lower_fn_decl(fdec, None, false, None),
3580 this.lower_fn_args_to_names(fdec),
3585 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3587 ForeignItemKind::Static(ref t, m) => {
3588 hir::ForeignItemKind::Static(
3589 self.lower_ty(t, ImplTraitContext::disallowed()), m)
3591 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3592 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3594 vis: self.lower_visibility(&i.vis, None),
3599 fn lower_method_sig(
3601 generics: &Generics,
3604 impl_trait_return_allow: bool,
3605 is_async: Option<NodeId>,
3606 ) -> (hir::Generics, hir::MethodSig) {
3607 let header = self.lower_fn_header(sig.header);
3608 let (generics, decl) = self.add_in_band_defs(
3611 AnonymousLifetimeMode::PassThrough,
3612 |this, idty| this.lower_fn_decl(
3614 Some((fn_def_id, idty)),
3615 impl_trait_return_allow,
3619 (generics, hir::MethodSig { header, decl })
3622 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3624 IsAuto::Yes => hir::IsAuto::Yes,
3625 IsAuto::No => hir::IsAuto::No,
3629 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3631 unsafety: self.lower_unsafety(h.unsafety),
3632 asyncness: self.lower_asyncness(h.asyncness),
3633 constness: self.lower_constness(h.constness),
3638 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3640 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3641 Unsafety::Normal => hir::Unsafety::Normal,
3645 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3647 Constness::Const => hir::Constness::Const,
3648 Constness::NotConst => hir::Constness::NotConst,
3652 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3654 IsAsync::Async { .. } => hir::IsAsync::Async,
3655 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3659 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3661 UnOp::Deref => hir::UnDeref,
3662 UnOp::Not => hir::UnNot,
3663 UnOp::Neg => hir::UnNeg,
3667 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3669 node: match b.node {
3670 BinOpKind::Add => hir::BinOpKind::Add,
3671 BinOpKind::Sub => hir::BinOpKind::Sub,
3672 BinOpKind::Mul => hir::BinOpKind::Mul,
3673 BinOpKind::Div => hir::BinOpKind::Div,
3674 BinOpKind::Rem => hir::BinOpKind::Rem,
3675 BinOpKind::And => hir::BinOpKind::And,
3676 BinOpKind::Or => hir::BinOpKind::Or,
3677 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3678 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3679 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3680 BinOpKind::Shl => hir::BinOpKind::Shl,
3681 BinOpKind::Shr => hir::BinOpKind::Shr,
3682 BinOpKind::Eq => hir::BinOpKind::Eq,
3683 BinOpKind::Lt => hir::BinOpKind::Lt,
3684 BinOpKind::Le => hir::BinOpKind::Le,
3685 BinOpKind::Ne => hir::BinOpKind::Ne,
3686 BinOpKind::Ge => hir::BinOpKind::Ge,
3687 BinOpKind::Gt => hir::BinOpKind::Gt,
3693 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3694 let node = match p.node {
3695 PatKind::Wild => hir::PatKind::Wild,
3696 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3697 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3698 // `None` can occur in body-less function signatures
3699 def @ None | def @ Some(Def::Local(_)) => {
3700 let canonical_id = match def {
3701 Some(Def::Local(id)) => id,
3704 let hir_id = self.lower_node_id(canonical_id).hir_id;
3705 hir::PatKind::Binding(
3706 self.lower_binding_mode(binding_mode),
3710 sub.as_ref().map(|x| self.lower_pat(x)),
3713 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3718 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3723 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3724 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3725 let qpath = self.lower_qpath(
3729 ParamMode::Optional,
3730 ImplTraitContext::disallowed(),
3732 hir::PatKind::TupleStruct(
3734 pats.iter().map(|x| self.lower_pat(x)).collect(),
3738 PatKind::Path(ref qself, ref path) => {
3739 let qpath = self.lower_qpath(
3743 ParamMode::Optional,
3744 ImplTraitContext::disallowed(),
3746 hir::PatKind::Path(qpath)
3748 PatKind::Struct(ref path, ref fields, etc) => {
3749 let qpath = self.lower_qpath(
3753 ParamMode::Optional,
3754 ImplTraitContext::disallowed(),
3760 let LoweredNodeId { node_id, hir_id } = self.next_id();
3764 node: hir::FieldPat {
3767 ident: f.node.ident,
3768 pat: self.lower_pat(&f.node.pat),
3769 is_shorthand: f.node.is_shorthand,
3774 hir::PatKind::Struct(qpath, fs, etc)
3776 PatKind::Tuple(ref elts, ddpos) => {
3777 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3779 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3780 PatKind::Ref(ref inner, mutbl) => {
3781 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3783 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3784 P(self.lower_expr(e1)),
3785 P(self.lower_expr(e2)),
3786 self.lower_range_end(end),
3788 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3789 before.iter().map(|x| self.lower_pat(x)).collect(),
3790 slice.as_ref().map(|x| self.lower_pat(x)),
3791 after.iter().map(|x| self.lower_pat(x)).collect(),
3793 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3794 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3797 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3806 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3808 RangeEnd::Included(_) => hir::RangeEnd::Included,
3809 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3813 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3814 self.with_new_scopes(|this| {
3815 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3819 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3824 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3825 let kind = match e.node {
3826 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3827 ExprKind::ObsoleteInPlace(..) => {
3828 self.sess.abort_if_errors();
3829 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3831 ExprKind::Array(ref exprs) => {
3832 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3834 ExprKind::Repeat(ref expr, ref count) => {
3835 let expr = P(self.lower_expr(expr));
3836 let count = self.lower_anon_const(count);
3837 hir::ExprKind::Repeat(expr, count)
3839 ExprKind::Tup(ref elts) => {
3840 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3842 ExprKind::Call(ref f, ref args) => {
3843 let f = P(self.lower_expr(f));
3844 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3846 ExprKind::MethodCall(ref seg, ref args) => {
3847 let hir_seg = self.lower_path_segment(
3850 ParamMode::Optional,
3852 ParenthesizedGenericArgs::Err,
3853 ImplTraitContext::disallowed(),
3856 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3857 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3859 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3860 let binop = self.lower_binop(binop);
3861 let lhs = P(self.lower_expr(lhs));
3862 let rhs = P(self.lower_expr(rhs));
3863 hir::ExprKind::Binary(binop, lhs, rhs)
3865 ExprKind::Unary(op, ref ohs) => {
3866 let op = self.lower_unop(op);
3867 let ohs = P(self.lower_expr(ohs));
3868 hir::ExprKind::Unary(op, ohs)
3870 ExprKind::Lit(ref l) => hir::ExprKind::Lit((*l).clone()),
3871 ExprKind::Cast(ref expr, ref ty) => {
3872 let expr = P(self.lower_expr(expr));
3873 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3875 ExprKind::Type(ref expr, ref ty) => {
3876 let expr = P(self.lower_expr(expr));
3877 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3879 ExprKind::AddrOf(m, ref ohs) => {
3880 let m = self.lower_mutability(m);
3881 let ohs = P(self.lower_expr(ohs));
3882 hir::ExprKind::AddrOf(m, ohs)
3884 // More complicated than you might expect because the else branch
3885 // might be `if let`.
3886 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3887 let else_opt = else_opt.as_ref().map(|els| {
3889 ExprKind::IfLet(..) => {
3890 // Wrap the `if let` expr in a block.
3891 let span = els.span;
3892 let els = P(self.lower_expr(els));
3893 let LoweredNodeId { node_id, hir_id } = self.next_id();
3894 let blk = P(hir::Block {
3899 rules: hir::DefaultBlock,
3901 targeted_by_break: false,
3903 P(self.expr_block(blk, ThinVec::new()))
3905 _ => P(self.lower_expr(els)),
3909 let then_blk = self.lower_block(blk, false);
3910 let then_expr = self.expr_block(then_blk, ThinVec::new());
3912 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3914 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3915 hir::ExprKind::While(
3916 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3917 this.lower_block(body, false),
3918 this.lower_label(opt_label),
3921 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3922 hir::ExprKind::Loop(
3923 this.lower_block(body, false),
3924 this.lower_label(opt_label),
3925 hir::LoopSource::Loop,
3928 ExprKind::TryBlock(ref body) => {
3929 self.with_catch_scope(body.id, |this| {
3931 this.allow_internal_unstable(CompilerDesugaringKind::TryBlock, body.span);
3932 let mut block = this.lower_block(body, true).into_inner();
3933 let tail = block.expr.take().map_or_else(
3935 let LoweredNodeId { node_id, hir_id } = this.next_id();
3936 let span = this.sess.source_map().end_point(unstable_span);
3940 node: hir::ExprKind::Tup(hir_vec![]),
3941 attrs: ThinVec::new(),
3945 |x: P<hir::Expr>| x.into_inner(),
3947 block.expr = Some(this.wrap_in_try_constructor(
3948 "from_ok", tail, unstable_span));
3949 hir::ExprKind::Block(P(block), None)
3952 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3953 P(self.lower_expr(expr)),
3954 arms.iter().map(|x| self.lower_arm(x)).collect(),
3955 hir::MatchSource::Normal,
3957 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3958 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3959 this.with_new_scopes(|this| {
3960 let block = this.lower_block(block, false);
3961 this.expr_block(block, ThinVec::new())
3966 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3968 if let IsAsync::Async { closure_id, .. } = asyncness {
3969 let outer_decl = FnDecl {
3970 inputs: decl.inputs.clone(),
3971 output: FunctionRetTy::Default(fn_decl_span),
3974 // We need to lower the declaration outside the new scope, because we
3975 // have to conserve the state of being inside a loop condition for the
3976 // closure argument types.
3977 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3979 self.with_new_scopes(|this| {
3980 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
3981 if capture_clause == CaptureBy::Ref &&
3982 !decl.inputs.is_empty()
3988 "`async` non-`move` closures with arguments \
3989 are not currently supported",
3991 .help("consider using `let` statements to manually capture \
3992 variables by reference before entering an \
3993 `async move` closure")
3997 // Transform `async |x: u8| -> X { ... }` into
3998 // `|x: u8| future_from_generator(|| -> X { ... })`.
3999 let body_id = this.lower_body(Some(&outer_decl), |this| {
4000 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
4003 let async_body = this.make_async_expr(
4004 capture_clause, closure_id, async_ret_ty,
4006 this.with_new_scopes(|this| this.lower_expr(body))
4008 this.expr(fn_decl_span, async_body, ThinVec::new())
4010 hir::ExprKind::Closure(
4011 this.lower_capture_clause(capture_clause),
4019 // Lower outside new scope to preserve `is_in_loop_condition`.
4020 let fn_decl = self.lower_fn_decl(decl, None, false, None);
4022 self.with_new_scopes(|this| {
4023 let mut is_generator = false;
4024 let body_id = this.lower_body(Some(decl), |this| {
4025 let e = this.lower_expr(body);
4026 is_generator = this.is_generator;
4029 let generator_option = if is_generator {
4030 if !decl.inputs.is_empty() {
4035 "generators cannot have explicit arguments"
4037 this.sess.abort_if_errors();
4039 Some(match movability {
4040 Movability::Movable => hir::GeneratorMovability::Movable,
4041 Movability::Static => hir::GeneratorMovability::Static,
4044 if movability == Movability::Static {
4049 "closures cannot be static"
4054 hir::ExprKind::Closure(
4055 this.lower_capture_clause(capture_clause),
4064 ExprKind::Block(ref blk, opt_label) => {
4065 hir::ExprKind::Block(self.lower_block(blk,
4066 opt_label.is_some()),
4067 self.lower_label(opt_label))
4069 ExprKind::Assign(ref el, ref er) => {
4070 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
4072 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
4073 self.lower_binop(op),
4074 P(self.lower_expr(el)),
4075 P(self.lower_expr(er)),
4077 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
4078 ExprKind::Index(ref el, ref er) => {
4079 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
4081 // Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
4082 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
4083 let id = self.next_id();
4084 let e1 = self.lower_expr(e1);
4085 let e2 = self.lower_expr(e2);
4086 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
4087 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
4088 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
4089 let new_path = hir::QPath::TypeRelative(ty, new_seg);
4090 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
4091 hir::ExprKind::Call(new, hir_vec![e1, e2])
4093 ExprKind::Range(ref e1, ref e2, lims) => {
4094 use syntax::ast::RangeLimits::*;
4096 let path = match (e1, e2, lims) {
4097 (&None, &None, HalfOpen) => "RangeFull",
4098 (&Some(..), &None, HalfOpen) => "RangeFrom",
4099 (&None, &Some(..), HalfOpen) => "RangeTo",
4100 (&Some(..), &Some(..), HalfOpen) => "Range",
4101 (&None, &Some(..), Closed) => "RangeToInclusive",
4102 (&Some(..), &Some(..), Closed) => unreachable!(),
4103 (_, &None, Closed) => self.diagnostic()
4104 .span_fatal(e.span, "inclusive range with no end")
4108 let fields = e1.iter()
4109 .map(|e| ("start", e))
4110 .chain(e2.iter().map(|e| ("end", e)))
4112 let expr = P(self.lower_expr(&e));
4113 let ident = Ident::new(Symbol::intern(s), e.span);
4114 self.field(ident, expr, e.span)
4116 .collect::<P<[hir::Field]>>();
4118 let is_unit = fields.is_empty();
4119 let struct_path = ["ops", path];
4120 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
4121 let struct_path = hir::QPath::Resolved(None, P(struct_path));
4123 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4129 hir::ExprKind::Path(struct_path)
4131 hir::ExprKind::Struct(struct_path, fields, None)
4134 attrs: e.attrs.clone(),
4137 ExprKind::Path(ref qself, ref path) => {
4138 let qpath = self.lower_qpath(
4142 ParamMode::Optional,
4143 ImplTraitContext::disallowed(),
4145 hir::ExprKind::Path(qpath)
4147 ExprKind::Break(opt_label, ref opt_expr) => {
4148 let destination = if self.is_in_loop_condition && opt_label.is_none() {
4151 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4154 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4156 hir::ExprKind::Break(
4158 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
4161 ExprKind::Continue(opt_label) => {
4162 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
4165 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4168 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4171 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
4172 ExprKind::InlineAsm(ref asm) => {
4173 let hir_asm = hir::InlineAsm {
4174 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
4175 outputs: asm.outputs
4177 .map(|out| hir::InlineAsmOutput {
4178 constraint: out.constraint.clone(),
4180 is_indirect: out.is_indirect,
4181 span: out.expr.span,
4184 asm: asm.asm.clone(),
4185 asm_str_style: asm.asm_str_style,
4186 clobbers: asm.clobbers.clone().into(),
4187 volatile: asm.volatile,
4188 alignstack: asm.alignstack,
4189 dialect: asm.dialect,
4192 let outputs = asm.outputs
4194 .map(|out| self.lower_expr(&out.expr))
4196 let inputs = asm.inputs
4198 .map(|&(_, ref input)| self.lower_expr(input))
4200 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
4202 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4207 ParamMode::Optional,
4208 ImplTraitContext::disallowed(),
4210 fields.iter().map(|x| self.lower_field(x)).collect(),
4211 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4213 ExprKind::Paren(ref ex) => {
4214 let mut ex = self.lower_expr(ex);
4215 // Include parens in span, but only if it is a super-span.
4216 if e.span.contains(ex.span) {
4219 // Merge attributes into the inner expression.
4220 let mut attrs = e.attrs.clone();
4221 attrs.extend::<Vec<_>>(ex.attrs.into());
4226 ExprKind::Yield(ref opt_expr) => {
4227 self.is_generator = true;
4230 .map(|x| self.lower_expr(x))
4232 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
4234 hir::ExprKind::Yield(P(expr))
4237 ExprKind::Err => hir::ExprKind::Err,
4239 // Desugar `ExprIfLet`
4240 // from: `if let <pat> = <sub_expr> <body> [<else_opt>]`
4241 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4244 // match <sub_expr> {
4246 // _ => [<else_opt> | ()]
4249 let mut arms = vec![];
4251 // `<pat> => <body>`
4253 let body = self.lower_block(body, false);
4254 let body_expr = P(self.expr_block(body, ThinVec::new()));
4255 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4256 arms.push(self.arm(pats, body_expr));
4259 // _ => [<else_opt>|()]
4261 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4262 let wildcard_pattern = self.pat_wild(e.span);
4263 let body = if let Some(else_expr) = wildcard_arm {
4264 P(self.lower_expr(else_expr))
4266 self.expr_tuple(e.span, hir_vec![])
4268 arms.push(self.arm(hir_vec![wildcard_pattern], body));
4271 let contains_else_clause = else_opt.is_some();
4273 let sub_expr = P(self.lower_expr(sub_expr));
4275 hir::ExprKind::Match(
4278 hir::MatchSource::IfLetDesugar {
4279 contains_else_clause,
4284 // Desugar `ExprWhileLet`
4285 // from: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4286 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4289 // [opt_ident]: loop {
4290 // match <sub_expr> {
4296 // Note that the block AND the condition are evaluated in the loop scope.
4297 // This is done to allow `break` from inside the condition of the loop.
4298 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4300 this.lower_block(body, false),
4301 this.expr_break(e.span, ThinVec::new()),
4302 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4306 // `<pat> => <body>`
4308 let body_expr = P(self.expr_block(body, ThinVec::new()));
4309 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4310 self.arm(pats, body_expr)
4315 let pat_under = self.pat_wild(e.span);
4316 self.arm(hir_vec![pat_under], break_expr)
4319 // `match <sub_expr> { ... }`
4320 let arms = hir_vec![pat_arm, break_arm];
4321 let match_expr = self.expr(
4323 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4327 // `[opt_ident]: loop { ... }`
4328 let loop_block = P(self.block_expr(P(match_expr)));
4329 let loop_expr = hir::ExprKind::Loop(
4331 self.lower_label(opt_label),
4332 hir::LoopSource::WhileLet,
4334 // Add attributes to the outer returned expr node.
4338 // Desugar `ExprForLoop`
4339 // from: `[opt_ident]: for <pat> in <head> <body>`
4340 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4344 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4346 // [opt_ident]: loop {
4348 // match ::std::iter::Iterator::next(&mut iter) {
4349 // ::std::option::Option::Some(val) => __next = val,
4350 // ::std::option::Option::None => break
4352 // let <pat> = __next;
4353 // StmtKind::Expr(<body>);
4361 let head = self.lower_expr(head);
4362 let head_sp = head.span;
4363 let desugared_span = self.allow_internal_unstable(
4364 CompilerDesugaringKind::ForLoop,
4368 let iter = self.str_to_ident("iter");
4370 let next_ident = self.str_to_ident("__next");
4371 let next_pat = self.pat_ident_binding_mode(
4374 hir::BindingAnnotation::Mutable,
4377 // `::std::option::Option::Some(val) => next = val`
4379 let val_ident = self.str_to_ident("val");
4380 let val_pat = self.pat_ident(pat.span, val_ident);
4381 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4382 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4383 let assign = P(self.expr(
4385 hir::ExprKind::Assign(next_expr, val_expr),
4388 let some_pat = self.pat_some(pat.span, val_pat);
4389 self.arm(hir_vec![some_pat], assign)
4392 // `::std::option::Option::None => break`
4395 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4396 let pat = self.pat_none(e.span);
4397 self.arm(hir_vec![pat], break_expr)
4401 let iter_pat = self.pat_ident_binding_mode(
4404 hir::BindingAnnotation::Mutable
4407 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4409 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4410 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4411 let next_path = &["iter", "Iterator", "next"];
4412 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4413 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4414 let arms = hir_vec![pat_arm, break_arm];
4418 hir::ExprKind::Match(
4421 hir::MatchSource::ForLoopDesugar
4426 let LoweredNodeId { node_id, hir_id } = self.next_id();
4427 let match_stmt = hir::Stmt {
4430 node: hir::StmtKind::Expr(match_expr),
4434 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4437 let next_let = self.stmt_let_pat(
4441 hir::LocalSource::ForLoopDesugar,
4444 // `let <pat> = __next`
4445 let pat = self.lower_pat(pat);
4446 let pat_let = self.stmt_let_pat(
4450 hir::LocalSource::ForLoopDesugar,
4453 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4454 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4455 let LoweredNodeId { node_id, hir_id } = self.next_id();
4456 let body_stmt = hir::Stmt {
4459 node: hir::StmtKind::Expr(body_expr),
4463 let loop_block = P(self.block_all(
4465 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4469 // `[opt_ident]: loop { ... }`
4470 let loop_expr = hir::ExprKind::Loop(
4472 self.lower_label(opt_label),
4473 hir::LoopSource::ForLoop,
4475 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4476 let loop_expr = P(hir::Expr {
4481 attrs: ThinVec::new(),
4484 // `mut iter => { ... }`
4485 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4487 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4488 let into_iter_expr = {
4489 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4490 let into_iter = P(self.expr_std_path(
4491 head_sp, into_iter_path, None, ThinVec::new()));
4492 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4495 let match_expr = P(self.expr_match(
4499 hir::MatchSource::ForLoopDesugar,
4502 // `{ let _result = ...; _result }`
4503 // Underscore prevents an `unused_variables` lint if the head diverges.
4504 let result_ident = self.str_to_ident("_result");
4505 let (let_stmt, let_stmt_binding) =
4506 self.stmt_let(e.span, false, result_ident, match_expr);
4508 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4509 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4510 // Add the attributes to the outer returned expr node.
4511 return self.expr_block(block, e.attrs.clone());
4514 // Desugar `ExprKind::Try`
4516 ExprKind::Try(ref sub_expr) => {
4519 // match Try::into_result(<expr>) {
4520 // Ok(val) => #[allow(unreachable_code)] val,
4521 // Err(err) => #[allow(unreachable_code)]
4522 // // If there is an enclosing `catch {...}`
4523 // break 'catch_target Try::from_error(From::from(err)),
4525 // return Try::from_error(From::from(err)),
4529 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4531 // `Try::into_result(<expr>)`
4534 let sub_expr = self.lower_expr(sub_expr);
4536 let path = &["ops", "Try", "into_result"];
4537 let path = P(self.expr_std_path(
4538 unstable_span, path, None, ThinVec::new()));
4539 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4542 // `#[allow(unreachable_code)]`
4544 // `allow(unreachable_code)`
4546 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4547 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4548 let uc_nested = attr::mk_nested_word_item(uc_ident);
4549 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4551 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4553 let attrs = vec![attr];
4555 // `Ok(val) => #[allow(unreachable_code)] val,`
4557 let val_ident = self.str_to_ident("val");
4558 let val_pat = self.pat_ident(e.span, val_ident);
4559 let val_expr = P(self.expr_ident_with_attrs(
4563 ThinVec::from(attrs.clone()),
4565 let ok_pat = self.pat_ok(e.span, val_pat);
4567 self.arm(hir_vec![ok_pat], val_expr)
4570 // `Err(err) => #[allow(unreachable_code)]
4571 // return Try::from_error(From::from(err)),`
4573 let err_ident = self.str_to_ident("err");
4574 let err_local = self.pat_ident(e.span, err_ident);
4576 let path = &["convert", "From", "from"];
4577 let from = P(self.expr_std_path(
4578 e.span, path, None, ThinVec::new()));
4579 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4581 self.expr_call(e.span, from, hir_vec![err_expr])
4584 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4585 let thin_attrs = ThinVec::from(attrs);
4586 let catch_scope = self.catch_scopes.last().map(|x| *x);
4587 let ret_expr = if let Some(catch_node) = catch_scope {
4590 hir::ExprKind::Break(
4593 target_id: Ok(catch_node),
4595 Some(from_err_expr),
4600 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4603 let err_pat = self.pat_err(e.span, err_local);
4604 self.arm(hir_vec![err_pat], ret_expr)
4607 hir::ExprKind::Match(
4609 hir_vec![err_arm, ok_arm],
4610 hir::MatchSource::TryDesugar,
4614 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4617 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4624 attrs: e.attrs.clone(),
4628 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
4629 smallvec![match s.node {
4630 StmtKind::Local(ref l) => {
4631 let (l, item_ids) = self.lower_local(l);
4632 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
4635 let LoweredNodeId { node_id, hir_id } = self.next_id();
4640 node: hir::StmtKind::Item(P(item_id)),
4646 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(s.id);
4651 node: hir::StmtKind::Local(P(l)),
4657 StmtKind::Item(ref it) => {
4658 // Can only use the ID once.
4659 let mut id = Some(s.id);
4660 return self.lower_item_id(it)
4663 let LoweredNodeId { node_id, hir_id } = id.take()
4664 .map(|id| self.lower_node_id(id))
4665 .unwrap_or_else(|| self.next_id());
4670 node: hir::StmtKind::Item(P(item_id)),
4676 StmtKind::Expr(ref e) => {
4677 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(s.id);
4682 node: hir::StmtKind::Expr(P(self.lower_expr(e))),
4686 StmtKind::Semi(ref e) => {
4687 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(s.id);
4692 node: hir::StmtKind::Semi(P(self.lower_expr(e))),
4696 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4700 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4702 CaptureBy::Value => hir::CaptureByValue,
4703 CaptureBy::Ref => hir::CaptureByRef,
4707 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4708 /// the address space of that item instead of the item currently being
4709 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4710 /// lower a `Visibility` value although we haven't lowered the owning
4711 /// `ImplItem` in question yet.
4712 fn lower_visibility(
4715 explicit_owner: Option<NodeId>,
4716 ) -> hir::Visibility {
4717 let node = match v.node {
4718 VisibilityKind::Public => hir::VisibilityKind::Public,
4719 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4720 VisibilityKind::Restricted { ref path, id } => {
4721 debug!("lower_visibility: restricted path id = {:?}", id);
4722 let lowered_id = if let Some(owner) = explicit_owner {
4723 self.lower_node_id_with_owner(id, owner)
4725 self.lower_node_id(id)
4727 let def = self.expect_full_def(id);
4728 hir::VisibilityKind::Restricted {
4729 path: P(self.lower_path_extra(
4732 ParamMode::Explicit,
4735 id: lowered_id.node_id,
4736 hir_id: lowered_id.hir_id,
4739 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4741 respan(v.span, node)
4744 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4746 Defaultness::Default => hir::Defaultness::Default {
4747 has_value: has_value,
4749 Defaultness::Final => {
4751 hir::Defaultness::Final
4756 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4758 BlockCheckMode::Default => hir::DefaultBlock,
4759 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4763 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4765 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4766 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4767 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4768 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4772 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4774 CompilerGenerated => hir::CompilerGenerated,
4775 UserProvided => hir::UserProvided,
4779 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4781 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4782 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4786 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4788 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4789 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4793 // Helper methods for building HIR.
4795 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4804 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4805 let LoweredNodeId { node_id, hir_id } = self.next_id();
4813 is_shorthand: false,
4817 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4818 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4819 P(self.expr(span, expr_break, attrs))
4826 args: hir::HirVec<hir::Expr>,
4828 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4831 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4832 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4835 fn expr_ident_with_attrs(
4840 attrs: ThinVec<Attribute>,
4842 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4846 def: Def::Local(binding),
4847 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4851 self.expr(span, expr_path, attrs)
4854 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4855 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4861 components: &[&str],
4862 params: Option<P<hir::GenericArgs>>,
4863 attrs: ThinVec<Attribute>,
4865 let path = self.std_path(span, components, params, true);
4868 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4877 arms: hir::HirVec<hir::Arm>,
4878 source: hir::MatchSource,
4880 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4883 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4884 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4887 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4888 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4891 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4892 let LoweredNodeId { node_id, hir_id } = self.next_id();
4905 ex: Option<P<hir::Expr>>,
4907 source: hir::LocalSource,
4909 let LoweredNodeId { node_id, hir_id } = self.next_id();
4911 let local = hir::Local {
4918 attrs: ThinVec::new(),
4922 let LoweredNodeId { node_id, hir_id } = self.next_id();
4926 node: hir::StmtKind::Local(P(local)),
4937 ) -> (hir::Stmt, NodeId) {
4938 let pat = if mutbl {
4939 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4941 self.pat_ident(sp, ident)
4943 let pat_id = pat.id;
4945 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4950 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4951 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4957 stmts: hir::HirVec<hir::Stmt>,
4958 expr: Option<P<hir::Expr>>,
4960 let LoweredNodeId { node_id, hir_id } = self.next_id();
4967 rules: hir::DefaultBlock,
4969 targeted_by_break: false,
4973 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4974 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4977 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4978 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4981 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4982 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4985 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4986 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4992 components: &[&str],
4993 subpats: hir::HirVec<P<hir::Pat>>,
4995 let path = self.std_path(span, components, None, true);
4996 let qpath = hir::QPath::Resolved(None, P(path));
4997 let pt = if subpats.is_empty() {
4998 hir::PatKind::Path(qpath)
5000 hir::PatKind::TupleStruct(qpath, subpats, None)
5005 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
5006 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
5009 fn pat_ident_binding_mode(
5013 bm: hir::BindingAnnotation,
5015 let LoweredNodeId { node_id, hir_id } = self.next_id();
5020 node: hir::PatKind::Binding(bm, node_id, hir_id, ident.with_span_pos(span), None),
5025 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
5026 self.pat(span, hir::PatKind::Wild)
5029 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
5030 let LoweredNodeId { node_id, hir_id } = self.next_id();
5039 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
5040 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
5041 /// The path is also resolved according to `is_value`.
5045 components: &[&str],
5046 params: Option<P<hir::GenericArgs>>,
5049 let mut path = self.resolver
5050 .resolve_str_path(span, self.crate_root, components, is_value);
5051 path.segments.last_mut().unwrap().args = params;
5054 for seg in path.segments.iter_mut() {
5055 if let Some(id) = seg.id {
5056 seg.id = Some(self.lower_node_id(id).node_id);
5062 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
5064 let node = match qpath {
5065 hir::QPath::Resolved(None, path) => {
5066 // Turn trait object paths into `TyKind::TraitObject` instead.
5068 Def::Trait(_) | Def::TraitAlias(_) => {
5069 let principal = hir::PolyTraitRef {
5070 bound_generic_params: hir::HirVec::new(),
5071 trait_ref: hir::TraitRef {
5072 path: path.and_then(|path| path),
5074 hir_ref_id: id.hir_id,
5079 // The original ID is taken by the `PolyTraitRef`,
5080 // so the `Ty` itself needs a different one.
5081 id = self.next_id();
5082 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
5084 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
5087 _ => hir::TyKind::Path(qpath),
5097 /// Invoked to create the lifetime argument for a type `&T`
5098 /// with no explicit lifetime.
5099 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
5100 match self.anonymous_lifetime_mode {
5101 // Intercept when we are in an impl header and introduce an in-band lifetime.
5102 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
5104 AnonymousLifetimeMode::CreateParameter => {
5105 let fresh_name = self.collect_fresh_in_band_lifetime(span);
5106 let LoweredNodeId { node_id, hir_id } = self.next_id();
5111 name: hir::LifetimeName::Param(fresh_name),
5115 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5117 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5121 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
5122 /// return a "error lifetime".
5123 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
5124 let (id, msg, label) = match id {
5125 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
5128 self.next_id().node_id,
5129 "`&` without an explicit lifetime name cannot be used here",
5130 "explicit lifetime name needed here",
5134 let mut err = struct_span_err!(
5141 err.span_label(span, label);
5144 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5147 /// Invoked to create the lifetime argument(s) for a path like
5148 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
5149 /// sorts of cases are deprecated. This may therefore report a warning or an
5150 /// error, depending on the mode.
5151 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
5152 match self.anonymous_lifetime_mode {
5153 // N.B., We intentionally ignore the create-parameter mode here
5154 // and instead "pass through" to resolve-lifetimes, which will then
5155 // report an error. This is because we don't want to support
5156 // impl elision for deprecated forms like
5158 // impl Foo for std::cell::Ref<u32> // note lack of '_
5159 AnonymousLifetimeMode::CreateParameter => {}
5161 AnonymousLifetimeMode::ReportError => {
5163 .map(|_| self.new_error_lifetime(None, span))
5167 // This is the normal case.
5168 AnonymousLifetimeMode::PassThrough => {}
5172 .map(|_| self.new_implicit_lifetime(span))
5176 /// Invoked to create the lifetime argument(s) for an elided trait object
5177 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
5178 /// when the bound is written, even if it is written with `'_` like in
5179 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
5180 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
5181 match self.anonymous_lifetime_mode {
5182 // NB. We intentionally ignore the create-parameter mode here.
5183 // and instead "pass through" to resolve-lifetimes, which will apply
5184 // the object-lifetime-defaulting rules. Elided object lifetime defaults
5185 // do not act like other elided lifetimes. In other words, given this:
5187 // impl Foo for Box<dyn Debug>
5189 // we do not introduce a fresh `'_` to serve as the bound, but instead
5190 // ultimately translate to the equivalent of:
5192 // impl Foo for Box<dyn Debug + 'static>
5194 // `resolve_lifetime` has the code to make that happen.
5195 AnonymousLifetimeMode::CreateParameter => {}
5197 AnonymousLifetimeMode::ReportError => {
5198 // ReportError applies to explicit use of `'_`.
5201 // This is the normal case.
5202 AnonymousLifetimeMode::PassThrough => {}
5205 self.new_implicit_lifetime(span)
5208 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
5209 let LoweredNodeId { node_id, hir_id } = self.next_id();
5215 name: hir::LifetimeName::Implicit,
5219 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
5220 self.sess.buffer_lint_with_diagnostic(
5221 builtin::BARE_TRAIT_OBJECTS,
5224 "trait objects without an explicit `dyn` are deprecated",
5225 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
5229 fn wrap_in_try_constructor(
5231 method: &'static str,
5233 unstable_span: Span,
5235 let path = &["ops", "Try", method];
5236 let from_err = P(self.expr_std_path(unstable_span, path, None,
5238 P(self.expr_call(e.span, from_err, hir_vec![e]))
5242 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5243 // Sorting by span ensures that we get things in order within a
5244 // file, and also puts the files in a sensible order.
5245 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5246 body_ids.sort_by_key(|b| bodies[b].value.span);