1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Lowers the AST to the HIR.
13 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
14 //! much like a fold. Where lowering involves a bit more work things get more
15 //! interesting and there are some invariants you should know about. These mostly
16 //! concern spans and ids.
18 //! Spans are assigned to AST nodes during parsing and then are modified during
19 //! expansion to indicate the origin of a node and the process it went through
20 //! being expanded. Ids are assigned to AST nodes just before lowering.
22 //! For the simpler lowering steps, ids and spans should be preserved. Unlike
23 //! expansion we do not preserve the process of lowering in the spans, so spans
24 //! should not be modified here. When creating a new node (as opposed to
25 //! 'folding' an existing one), then you create a new id using `next_id()`.
27 //! You must ensure that ids are unique. That means that you should only use the
28 //! id from an AST node in a single HIR node (you can assume that AST node ids
29 //! are unique). Every new node must have a unique id. Avoid cloning HIR nodes.
30 //! If you do, you must then set the new node's id to a fresh one.
32 //! Spans are used for error messages and for tools to map semantics back to
33 //! source code. It is therefore not as important with spans as ids to be strict
34 //! about use (you can't break the compiler by screwing up a span). Obviously, a
35 //! HIR node can only have a single span. But multiple nodes can have the same
36 //! span and spans don't need to be kept in order, etc. Where code is preserved
37 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
38 //! new it is probably best to give a span for the whole AST node being lowered.
39 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
40 //! get confused if the spans from leaf AST nodes occur in multiple places
41 //! in the HIR, especially for multiple identifiers.
43 use dep_graph::DepGraph;
44 use hir::{self, ParamName};
46 use hir::map::{DefKey, DefPathData, Definitions};
47 use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX};
48 use hir::def::{Def, PathResolution, PerNS};
50 use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
51 ELIDED_LIFETIMES_IN_PATHS};
52 use middle::cstore::CrateStore;
53 use rustc_data_structures::fx::FxHashSet;
54 use rustc_data_structures::indexed_vec::IndexVec;
55 use rustc_data_structures::thin_vec::ThinVec;
57 use session::config::nightly_options;
58 use util::common::FN_OUTPUT_NAME;
59 use util::nodemap::{DefIdMap, NodeMap};
61 use std::collections::BTreeMap;
64 use smallvec::SmallVec;
69 use syntax::ext::hygiene::{Mark, SyntaxContext};
70 use syntax::feature_gate::{emit_feature_err, GateIssue};
71 use syntax::print::pprust;
73 use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned};
74 use syntax::std_inject;
75 use syntax::symbol::{keywords, Symbol};
76 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
77 use syntax::parse::token::Token;
78 use syntax::visit::{self, Visitor};
79 use syntax_pos::{Span, MultiSpan};
81 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
83 pub struct LoweringContext<'a> {
84 crate_root: Option<&'static str>,
86 // Use to assign ids to hir nodes that do not directly correspond to an ast node
89 cstore: &'a dyn CrateStore,
91 resolver: &'a mut dyn Resolver,
93 /// The items being lowered are collected here.
94 items: BTreeMap<NodeId, hir::Item>,
96 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
97 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
98 bodies: BTreeMap<hir::BodyId, hir::Body>,
99 exported_macros: Vec<hir::MacroDef>,
101 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
102 trait_auto_impl: BTreeMap<DefId, NodeId>,
106 catch_scopes: Vec<NodeId>,
107 loop_scopes: Vec<NodeId>,
108 is_in_loop_condition: bool,
109 is_in_trait_impl: bool,
111 /// What to do when we encounter either an "anonymous lifetime
112 /// reference". The term "anonymous" is meant to encompass both
113 /// `'_` lifetimes as well as fully elided cases where nothing is
114 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
115 anonymous_lifetime_mode: AnonymousLifetimeMode,
117 // Used to create lifetime definitions from in-band lifetime usages.
118 // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
119 // When a named lifetime is encountered in a function or impl header and
120 // has not been defined
121 // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
122 // to this list. The results of this list are then added to the list of
123 // lifetime definitions in the corresponding impl or function generics.
124 lifetimes_to_define: Vec<(Span, ParamName)>,
126 // Whether or not in-band lifetimes are being collected. This is used to
127 // indicate whether or not we're in a place where new lifetimes will result
128 // in in-band lifetime definitions, such a function or an impl header,
129 // including implicit lifetimes from `impl_header_lifetime_elision`.
130 is_collecting_in_band_lifetimes: bool,
132 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
133 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
134 // against this list to see if it is already in-scope, or if a definition
135 // needs to be created for it.
136 in_scope_lifetimes: Vec<Ident>,
138 type_def_lifetime_params: DefIdMap<usize>,
140 current_hir_id_owner: Vec<(DefIndex, u32)>,
141 item_local_id_counters: NodeMap<u32>,
142 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
146 /// Resolve a path generated by the lowerer when expanding `for`, `if let`, etc.
153 /// Obtain the resolution for a node id
154 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
156 /// Obtain the possible resolutions for the given `use` statement.
157 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
159 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
160 /// This should only return `None` during testing.
161 fn definitions(&mut self) -> &mut Definitions;
163 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
164 /// it based on `is_value`.
168 crate_root: Option<&str>,
175 enum ImplTraitContext<'a> {
176 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
177 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
178 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
180 /// Newly generated parameters should be inserted into the given `Vec`.
181 Universal(&'a mut Vec<hir::GenericParam>),
183 /// Treat `impl Trait` as shorthand for a new existential parameter.
184 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
185 /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
187 /// We optionally store a `DefId` for the parent item here so we can look up necessary
188 /// information later. It is `None` when no information about the context should be stored,
189 /// e.g. for consts and statics.
190 Existential(Option<DefId>),
192 /// `impl Trait` is not accepted in this position.
193 Disallowed(ImplTraitPosition),
196 /// Position in which `impl Trait` is disallowed. Used for error reporting.
197 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
198 enum ImplTraitPosition {
203 impl<'a> ImplTraitContext<'a> {
205 fn disallowed() -> Self {
206 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
209 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
210 use self::ImplTraitContext::*;
212 Universal(params) => Universal(params),
213 Existential(did) => Existential(*did),
214 Disallowed(pos) => Disallowed(*pos),
221 cstore: &dyn CrateStore,
222 dep_graph: &DepGraph,
224 resolver: &mut dyn Resolver,
226 // We're constructing the HIR here; we don't care what we will
227 // read, since we haven't even constructed the *input* to
229 dep_graph.assert_ignored();
232 crate_root: std_inject::injected_crate_name(),
236 items: BTreeMap::new(),
237 trait_items: BTreeMap::new(),
238 impl_items: BTreeMap::new(),
239 bodies: BTreeMap::new(),
240 trait_impls: BTreeMap::new(),
241 trait_auto_impl: BTreeMap::new(),
242 exported_macros: Vec::new(),
243 catch_scopes: Vec::new(),
244 loop_scopes: Vec::new(),
245 is_in_loop_condition: false,
246 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
247 type_def_lifetime_params: DefIdMap(),
248 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
249 item_local_id_counters: NodeMap(),
250 node_id_to_hir_id: IndexVec::new(),
252 is_in_trait_impl: false,
253 lifetimes_to_define: Vec::new(),
254 is_collecting_in_band_lifetimes: false,
255 in_scope_lifetimes: Vec::new(),
259 #[derive(Copy, Clone, PartialEq)]
261 /// Any path in a type context.
263 /// The `module::Type` in `module::Type::method` in an expression.
268 struct LoweredNodeId {
273 enum ParenthesizedGenericArgs {
279 /// What to do when we encounter an **anonymous** lifetime
280 /// reference. Anonymous lifetime references come in two flavors. You
281 /// have implicit, or fully elided, references to lifetimes, like the
282 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
283 /// or `Ref<'_, T>`. These often behave the same, but not always:
285 /// - certain usages of implicit references are deprecated, like
286 /// `Ref<T>`, and we sometimes just give hard errors in those cases
288 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
289 /// the same as `Box<dyn Foo + '_>`.
291 /// We describe the effects of the various modes in terms of three cases:
293 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
294 /// of a `&` (e.g., the missing lifetime in something like `&T`)
295 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
296 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
297 /// elided bounds follow special rules. Note that this only covers
298 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
299 /// '_>` is a case of "modern" elision.
300 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
301 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
302 /// non-deprecated equivalent.
304 /// Currently, the handling of lifetime elision is somewhat spread out
305 /// between HIR lowering and -- as described below -- the
306 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
307 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
308 /// everything into HIR lowering.
309 #[derive(Copy, Clone)]
310 enum AnonymousLifetimeMode {
311 /// For **Modern** cases, create a new anonymous region parameter
312 /// and reference that.
314 /// For **Dyn Bound** cases, pass responsibility to
315 /// `resolve_lifetime` code.
317 /// For **Deprecated** cases, report an error.
320 /// Give a hard error when either `&` or `'_` is written. Used to
321 /// rule out things like `where T: Foo<'_>`. Does not imply an
322 /// error on default object bounds (e.g., `Box<dyn Foo>`).
325 /// Pass responsibility to `resolve_lifetime` code for all cases.
329 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[hir::ItemId; 1]> }
331 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
332 fn visit_ty(&mut self, ty: &'a Ty) {
338 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
341 visit::walk_ty(self, ty);
344 fn visit_path_segment(
347 path_segment: &'v PathSegment,
349 if let Some(ref p) = path_segment.args {
350 if let GenericArgs::Parenthesized(_) = **p {
354 visit::walk_path_segment(self, path_span, path_segment)
358 impl<'a> LoweringContext<'a> {
359 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
360 /// Full-crate AST visitor that inserts into a fresh
361 /// `LoweringContext` any information that may be
362 /// needed from arbitrary locations in the crate.
363 /// E.g. The number of lifetime generic parameters
364 /// declared for every type and trait definition.
365 struct MiscCollector<'lcx, 'interner: 'lcx> {
366 lctx: &'lcx mut LoweringContext<'interner>,
369 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
370 fn visit_item(&mut self, item: &'lcx Item) {
371 self.lctx.allocate_hir_id_counter(item.id, item);
374 ItemKind::Struct(_, ref generics)
375 | ItemKind::Union(_, ref generics)
376 | ItemKind::Enum(_, ref generics)
377 | ItemKind::Ty(_, ref generics)
378 | ItemKind::Existential(_, ref generics)
379 | ItemKind::Trait(_, _, ref generics, ..) => {
380 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
384 .filter(|param| match param.kind {
385 ast::GenericParamKind::Lifetime { .. } => true,
389 self.lctx.type_def_lifetime_params.insert(def_id, count);
393 visit::walk_item(self, item);
396 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
397 self.lctx.allocate_hir_id_counter(item.id, item);
398 visit::walk_trait_item(self, item);
401 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
402 self.lctx.allocate_hir_id_counter(item.id, item);
403 visit::walk_impl_item(self, item);
407 struct ItemLowerer<'lcx, 'interner: 'lcx> {
408 lctx: &'lcx mut LoweringContext<'interner>,
411 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
412 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
414 F: FnOnce(&mut Self),
416 let old = self.lctx.is_in_trait_impl;
417 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
423 self.lctx.is_in_trait_impl = old;
427 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
428 fn visit_item(&mut self, item: &'lcx Item) {
429 let mut item_lowered = true;
430 self.lctx.with_hir_id_owner(item.id, |lctx| {
431 if let Some(hir_item) = lctx.lower_item(item) {
432 lctx.items.insert(item.id, hir_item);
434 item_lowered = false;
439 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
440 hir::ItemKind::Impl(_, _, _, ref generics, ..)
441 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
442 generics.params.clone()
447 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
448 let this = &mut ItemLowerer { lctx: this };
449 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
450 this.with_trait_impl_ref(opt_trait_ref, |this| {
451 visit::walk_item(this, item)
454 visit::walk_item(this, item);
460 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
461 self.lctx.with_hir_id_owner(item.id, |lctx| {
462 let id = hir::TraitItemId { node_id: item.id };
463 let hir_item = lctx.lower_trait_item(item);
464 lctx.trait_items.insert(id, hir_item);
467 visit::walk_trait_item(self, item);
470 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
471 self.lctx.with_hir_id_owner(item.id, |lctx| {
472 let id = hir::ImplItemId { node_id: item.id };
473 let hir_item = lctx.lower_impl_item(item);
474 lctx.impl_items.insert(id, hir_item);
476 visit::walk_impl_item(self, item);
480 self.lower_node_id(CRATE_NODE_ID);
481 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
483 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
484 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
486 let module = self.lower_mod(&c.module);
487 let attrs = self.lower_attrs(&c.attrs);
488 let body_ids = body_ids(&self.bodies);
492 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
498 exported_macros: hir::HirVec::from(self.exported_macros),
500 trait_items: self.trait_items,
501 impl_items: self.impl_items,
504 trait_impls: self.trait_impls,
505 trait_auto_impl: self.trait_auto_impl,
509 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
510 if self.item_local_id_counters.insert(owner, 0).is_some() {
512 "Tried to allocate item_local_id_counter for {:?} twice",
516 // Always allocate the first HirId for the owner itself
517 self.lower_node_id_with_owner(owner, owner)
520 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
522 F: FnOnce(&mut Self) -> hir::HirId,
524 if ast_node_id == DUMMY_NODE_ID {
525 return LoweredNodeId {
526 node_id: DUMMY_NODE_ID,
527 hir_id: hir::DUMMY_HIR_ID,
531 let min_size = ast_node_id.as_usize() + 1;
533 if min_size > self.node_id_to_hir_id.len() {
534 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
537 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
539 if existing_hir_id == hir::DUMMY_HIR_ID {
540 // Generate a new HirId
541 let hir_id = alloc_hir_id(self);
542 self.node_id_to_hir_id[ast_node_id] = hir_id;
544 node_id: ast_node_id,
549 node_id: ast_node_id,
550 hir_id: existing_hir_id,
555 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
557 F: FnOnce(&mut Self) -> T,
559 let counter = self.item_local_id_counters
560 .insert(owner, HIR_ID_COUNTER_LOCKED)
561 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
562 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
563 self.current_hir_id_owner.push((def_index, counter));
565 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
567 debug_assert!(def_index == new_def_index);
568 debug_assert!(new_counter >= counter);
570 let prev = self.item_local_id_counters
571 .insert(owner, new_counter)
573 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
577 /// This method allocates a new HirId for the given NodeId and stores it in
578 /// the LoweringContext's NodeId => HirId map.
579 /// Take care not to call this method if the resulting HirId is then not
580 /// actually used in the HIR, as that would trigger an assertion in the
581 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
582 /// properly. Calling the method twice with the same NodeId is fine though.
583 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
584 self.lower_node_id_generic(ast_node_id, |this| {
585 let &mut (def_index, ref mut local_id_counter) =
586 this.current_hir_id_owner.last_mut().unwrap();
587 let local_id = *local_id_counter;
588 *local_id_counter += 1;
591 local_id: hir::ItemLocalId(local_id),
596 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
597 self.lower_node_id_generic(ast_node_id, |this| {
598 let local_id_counter = this
599 .item_local_id_counters
601 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
602 let local_id = *local_id_counter;
604 // We want to be sure not to modify the counter in the map while it
605 // is also on the stack. Otherwise we'll get lost updates when writing
606 // back from the stack to the map.
607 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
609 *local_id_counter += 1;
613 .opt_def_index(owner)
614 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
615 that do not belong to the current owner");
619 local_id: hir::ItemLocalId(local_id),
624 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
625 let body = hir::Body {
626 arguments: decl.map_or(hir_vec![], |decl| {
627 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
629 is_generator: self.is_generator,
633 self.bodies.insert(id, body);
637 fn next_id(&mut self) -> LoweredNodeId {
638 self.lower_node_id(self.sess.next_node_id())
641 fn expect_full_def(&mut self, id: NodeId) -> Def {
642 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
643 if pr.unresolved_segments() != 0 {
644 bug!("path not fully resolved: {:?}", pr);
650 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Def> {
651 self.resolver.get_import(id).present_items().map(|pr| {
652 if pr.unresolved_segments() != 0 {
653 bug!("path not fully resolved: {:?}", pr);
659 fn diagnostic(&self) -> &errors::Handler {
660 self.sess.diagnostic()
663 fn str_to_ident(&self, s: &'static str) -> Ident {
664 Ident::with_empty_ctxt(Symbol::gensym(s))
667 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
668 let mark = Mark::fresh(Mark::root());
669 mark.set_expn_info(source_map::ExpnInfo {
671 def_site: Some(span),
672 format: source_map::CompilerDesugaring(reason),
673 allow_internal_unstable: true,
674 allow_internal_unsafe: false,
675 local_inner_macros: false,
676 edition: source_map::hygiene::default_edition(),
678 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
681 fn with_anonymous_lifetime_mode<R>(
683 anonymous_lifetime_mode: AnonymousLifetimeMode,
684 op: impl FnOnce(&mut Self) -> R,
686 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
687 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
688 let result = op(self);
689 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
693 /// Creates a new hir::GenericParam for every new lifetime and
694 /// type parameter encountered while evaluating `f`. Definitions
695 /// are created with the parent provided. If no `parent_id` is
696 /// provided, no definitions will be returned.
698 /// Presuming that in-band lifetimes are enabled, then
699 /// `self.anonymous_lifetime_mode` will be updated to match the
700 /// argument while `f` is running (and restored afterwards).
701 fn collect_in_band_defs<T, F>(
704 anonymous_lifetime_mode: AnonymousLifetimeMode,
706 ) -> (Vec<hir::GenericParam>, T)
708 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
710 assert!(!self.is_collecting_in_band_lifetimes);
711 assert!(self.lifetimes_to_define.is_empty());
712 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
714 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
715 self.is_collecting_in_band_lifetimes = true;
717 let (in_band_ty_params, res) = f(self);
719 self.is_collecting_in_band_lifetimes = false;
720 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
722 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
724 let params = lifetimes_to_define
726 .map(|(span, hir_name)| {
727 let def_node_id = self.next_id().node_id;
729 // Get the name we'll use to make the def-path. Note
730 // that collisions are ok here and this shouldn't
731 // really show up for end-user.
732 let (str_name, kind) = match hir_name {
733 ParamName::Plain(ident) => (
734 ident.as_interned_str(),
735 hir::LifetimeParamKind::InBand,
737 ParamName::Fresh(_) => (
738 keywords::UnderscoreLifetime.name().as_interned_str(),
739 hir::LifetimeParamKind::Elided,
741 ParamName::Error => (
742 keywords::UnderscoreLifetime.name().as_interned_str(),
743 hir::LifetimeParamKind::Error,
747 // Add a definition for the in-band lifetime def
748 self.resolver.definitions().create_def_with_parent(
751 DefPathData::LifetimeParam(str_name),
752 DefIndexAddressSpace::High,
763 pure_wrt_drop: false,
764 kind: hir::GenericParamKind::Lifetime { kind }
767 .chain(in_band_ty_params.into_iter())
773 /// When there is a reference to some lifetime `'a`, and in-band
774 /// lifetimes are enabled, then we want to push that lifetime into
775 /// the vector of names to define later. In that case, it will get
776 /// added to the appropriate generics.
777 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
778 if !self.is_collecting_in_band_lifetimes {
782 if !self.sess.features_untracked().in_band_lifetimes {
786 if self.in_scope_lifetimes.contains(&ident.modern()) {
790 let hir_name = ParamName::Plain(ident);
792 if self.lifetimes_to_define.iter()
793 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
797 self.lifetimes_to_define.push((ident.span, hir_name));
800 /// When we have either an elided or `'_` lifetime in an impl
801 /// header, we convert it to an in-band lifetime.
802 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
803 assert!(self.is_collecting_in_band_lifetimes);
804 let index = self.lifetimes_to_define.len();
805 let hir_name = ParamName::Fresh(index);
806 self.lifetimes_to_define.push((span, hir_name));
810 // Evaluates `f` with the lifetimes in `params` in-scope.
811 // This is used to track which lifetimes have already been defined, and
812 // which are new in-band lifetimes that need to have a definition created
814 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
816 F: FnOnce(&mut LoweringContext<'_>) -> T,
818 let old_len = self.in_scope_lifetimes.len();
819 let lt_def_names = params.iter().filter_map(|param| match param.kind {
820 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
823 self.in_scope_lifetimes.extend(lt_def_names);
827 self.in_scope_lifetimes.truncate(old_len);
831 // Same as the method above, but accepts `hir::GenericParam`s
832 // instead of `ast::GenericParam`s.
833 // This should only be used with generics that have already had their
834 // in-band lifetimes added. In practice, this means that this function is
835 // only used when lowering a child item of a trait or impl.
836 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
837 params: &HirVec<hir::GenericParam>,
840 F: FnOnce(&mut LoweringContext<'_>) -> T,
842 let old_len = self.in_scope_lifetimes.len();
843 let lt_def_names = params.iter().filter_map(|param| match param.kind {
844 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
847 self.in_scope_lifetimes.extend(lt_def_names);
851 self.in_scope_lifetimes.truncate(old_len);
855 /// Appends in-band lifetime defs and argument-position `impl
856 /// Trait` defs to the existing set of generics.
858 /// Presuming that in-band lifetimes are enabled, then
859 /// `self.anonymous_lifetime_mode` will be updated to match the
860 /// argument while `f` is running (and restored afterwards).
861 fn add_in_band_defs<F, T>(
865 anonymous_lifetime_mode: AnonymousLifetimeMode,
867 ) -> (hir::Generics, T)
869 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
871 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
874 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
875 let mut params = Vec::new();
876 let generics = this.lower_generics(
878 ImplTraitContext::Universal(&mut params),
880 let res = f(this, &mut params);
881 (params, (generics, res))
886 lowered_generics.params = lowered_generics
893 (lowered_generics, res)
896 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
898 F: FnOnce(&mut LoweringContext<'_>) -> T,
900 let len = self.catch_scopes.len();
901 self.catch_scopes.push(catch_id);
903 let result = f(self);
906 self.catch_scopes.len(),
907 "catch scopes should be added and removed in stack order"
910 self.catch_scopes.pop().unwrap();
917 capture_clause: CaptureBy,
918 closure_node_id: NodeId,
920 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
922 let prev_is_generator = mem::replace(&mut self.is_generator, true);
923 let body_expr = body(self);
924 let span = body_expr.span;
925 let output = match ret_ty {
926 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
927 None => FunctionRetTy::Default(span),
934 let body_id = self.record_body(body_expr, Some(&decl));
935 self.is_generator = prev_is_generator;
937 let capture_clause = self.lower_capture_clause(capture_clause);
938 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
939 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
940 let generator = hir::Expr {
942 hir_id: closure_hir_id,
943 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
944 Some(hir::GeneratorMovability::Static)),
946 attrs: ThinVec::new(),
949 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
950 let gen_future = self.expr_std_path(
951 unstable_span, &["future", "from_generator"], None, ThinVec::new());
952 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
955 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
957 F: FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
959 let prev = mem::replace(&mut self.is_generator, false);
960 let result = f(self);
961 let r = self.record_body(result, decl);
962 self.is_generator = prev;
966 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
968 F: FnOnce(&mut LoweringContext<'_>) -> T,
970 // We're no longer in the base loop's condition; we're in another loop.
971 let was_in_loop_condition = self.is_in_loop_condition;
972 self.is_in_loop_condition = false;
974 let len = self.loop_scopes.len();
975 self.loop_scopes.push(loop_id);
977 let result = f(self);
980 self.loop_scopes.len(),
981 "Loop scopes should be added and removed in stack order"
984 self.loop_scopes.pop().unwrap();
986 self.is_in_loop_condition = was_in_loop_condition;
991 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
993 F: FnOnce(&mut LoweringContext<'_>) -> T,
995 let was_in_loop_condition = self.is_in_loop_condition;
996 self.is_in_loop_condition = true;
998 let result = f(self);
1000 self.is_in_loop_condition = was_in_loop_condition;
1005 fn with_new_scopes<T, F>(&mut self, f: F) -> T
1007 F: FnOnce(&mut LoweringContext<'_>) -> T,
1009 let was_in_loop_condition = self.is_in_loop_condition;
1010 self.is_in_loop_condition = false;
1012 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
1013 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
1015 self.catch_scopes = catch_scopes;
1016 self.loop_scopes = loop_scopes;
1018 self.is_in_loop_condition = was_in_loop_condition;
1023 fn def_key(&mut self, id: DefId) -> DefKey {
1025 self.resolver.definitions().def_key(id.index)
1027 self.cstore.def_key(id)
1031 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1032 label.map(|label| hir::Label {
1037 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1038 let target_id = match destination {
1040 if let Def::Label(loop_id) = self.expect_full_def(id) {
1041 Ok(self.lower_node_id(loop_id).node_id)
1043 Err(hir::LoopIdError::UnresolvedLabel)
1050 .map(|id| Ok(self.lower_node_id(id).node_id))
1051 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1056 label: self.lower_label(destination.map(|(_, label)| label)),
1061 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1064 .map(|a| self.lower_attr(a))
1065 .collect::<Vec<_>>()
1069 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1070 // Note that we explicitly do not walk the path. Since we don't really
1071 // lower attributes (we use the AST version) there is nowhere to keep
1072 // the HirIds. We don't actually need HIR version of attributes anyway.
1076 path: attr.path.clone(),
1077 tokens: self.lower_token_stream(attr.tokens.clone()),
1078 is_sugared_doc: attr.is_sugared_doc,
1083 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1086 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1090 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1092 TokenTree::Token(span, token) => self.lower_token(token, span),
1093 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1096 delim: delimited.delim,
1097 tts: self.lower_token_stream(delimited.tts.into()).into(),
1103 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1105 Token::Interpolated(_) => {}
1106 other => return TokenTree::Token(span, other).into(),
1109 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1110 self.lower_token_stream(tts)
1113 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1115 attrs: self.lower_attrs(&arm.attrs),
1116 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1117 guard: match arm.guard {
1118 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1121 body: P(self.lower_expr(&arm.body)),
1125 fn lower_ty_binding(&mut self, b: &TypeBinding,
1126 itctx: ImplTraitContext<'_>) -> hir::TypeBinding {
1128 id: self.lower_node_id(b.id).node_id,
1130 ty: self.lower_ty(&b.ty, itctx),
1135 fn lower_generic_arg(&mut self,
1136 arg: &ast::GenericArg,
1137 itctx: ImplTraitContext<'_>)
1138 -> hir::GenericArg {
1140 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1141 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1145 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1146 P(self.lower_ty_direct(t, itctx))
1149 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1150 let kind = match t.node {
1151 TyKind::Infer => hir::TyKind::Infer,
1152 TyKind::Err => hir::TyKind::Err,
1153 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1154 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1155 TyKind::Rptr(ref region, ref mt) => {
1156 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1157 let lifetime = match *region {
1158 Some(ref lt) => self.lower_lifetime(lt),
1159 None => self.elided_ref_lifetime(span),
1161 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1163 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1166 this.with_anonymous_lifetime_mode(
1167 AnonymousLifetimeMode::PassThrough,
1169 hir::TyKind::BareFn(P(hir::BareFnTy {
1170 generic_params: this.lower_generic_params(
1173 ImplTraitContext::disallowed(),
1175 unsafety: this.lower_unsafety(f.unsafety),
1177 decl: this.lower_fn_decl(&f.decl, None, false, None),
1178 arg_names: this.lower_fn_args_to_names(&f.decl),
1184 TyKind::Never => hir::TyKind::Never,
1185 TyKind::Tup(ref tys) => {
1186 hir::TyKind::Tup(tys.iter().map(|ty| {
1187 self.lower_ty_direct(ty, itctx.reborrow())
1190 TyKind::Paren(ref ty) => {
1191 return self.lower_ty_direct(ty, itctx);
1193 TyKind::Path(ref qself, ref path) => {
1194 let id = self.lower_node_id(t.id);
1195 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1196 let ty = self.ty_path(id, t.span, qpath);
1197 if let hir::TyKind::TraitObject(..) = ty.node {
1198 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1202 TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1205 def: self.expect_full_def(t.id),
1206 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1210 TyKind::Array(ref ty, ref length) => {
1211 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1213 TyKind::Typeof(ref expr) => {
1214 hir::TyKind::Typeof(self.lower_anon_const(expr))
1216 TyKind::TraitObject(ref bounds, kind) => {
1217 let mut lifetime_bound = None;
1220 .filter_map(|bound| match *bound {
1221 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1222 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1224 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1225 GenericBound::Outlives(ref lifetime) => {
1226 if lifetime_bound.is_none() {
1227 lifetime_bound = Some(self.lower_lifetime(lifetime));
1233 let lifetime_bound =
1234 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1235 if kind != TraitObjectSyntax::Dyn {
1236 self.maybe_lint_bare_trait(t.span, t.id, false);
1238 hir::TyKind::TraitObject(bounds, lifetime_bound)
1240 TyKind::ImplTrait(def_node_id, ref bounds) => {
1243 ImplTraitContext::Existential(fn_def_id) => {
1244 self.lower_existential_impl_trait(
1245 span, fn_def_id, def_node_id,
1246 |this| this.lower_param_bounds(bounds, itctx),
1249 ImplTraitContext::Universal(in_band_ty_params) => {
1250 self.lower_node_id(def_node_id);
1251 // Add a definition for the in-band Param
1252 let def_index = self
1255 .opt_def_index(def_node_id)
1258 let hir_bounds = self.lower_param_bounds(
1260 ImplTraitContext::Universal(in_band_ty_params),
1262 // Set the name to `impl Bound1 + Bound2`
1263 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1264 in_band_ty_params.push(hir::GenericParam {
1266 name: ParamName::Plain(ident),
1267 pure_wrt_drop: false,
1271 kind: hir::GenericParamKind::Type {
1273 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1277 hir::TyKind::Path(hir::QPath::Resolved(
1281 def: Def::TyParam(DefId::local(def_index)),
1282 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1286 ImplTraitContext::Disallowed(pos) => {
1287 let allowed_in = if self.sess.features_untracked()
1288 .impl_trait_in_bindings {
1289 "bindings or function and inherent method return types"
1291 "function and inherent method return types"
1293 let mut err = struct_span_err!(
1297 "`impl Trait` not allowed outside of {}",
1300 if pos == ImplTraitPosition::Binding &&
1301 nightly_options::is_nightly_build() {
1303 "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1311 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1314 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1323 fn lower_existential_impl_trait(
1326 fn_def_id: Option<DefId>,
1327 exist_ty_node_id: NodeId,
1328 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1330 // Make sure we know that some funky desugaring has been going on here.
1331 // This is a first: there is code in other places like for loop
1332 // desugaring that explicitly states that we don't want to track that.
1333 // Not tracking it makes lints in rustc and clippy very fragile as
1334 // frequently opened issues show.
1335 let exist_ty_span = self.allow_internal_unstable(
1336 CompilerDesugaringKind::ExistentialReturnType,
1340 let exist_ty_def_index = self
1343 .opt_def_index(exist_ty_node_id)
1346 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1348 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1350 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1356 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1357 let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1358 generics: hir::Generics {
1359 params: lifetime_defs,
1360 where_clause: hir::WhereClause {
1361 id: lctx.next_id().node_id,
1362 predicates: Vec::new().into(),
1367 impl_trait_fn: fn_def_id,
1369 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1370 // Generate an `existential type Foo: Trait;` declaration
1371 trace!("creating existential type with id {:#?}", exist_ty_id);
1373 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1374 let exist_ty_item = hir::Item {
1375 id: exist_ty_id.node_id,
1376 hir_id: exist_ty_id.hir_id,
1377 name: keywords::Invalid.name(),
1378 attrs: Default::default(),
1379 node: exist_ty_item_kind,
1380 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1381 span: exist_ty_span,
1384 // Insert the item into the global list. This usually happens
1385 // automatically for all AST items. But this existential type item
1386 // does not actually exist in the AST.
1387 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1389 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1390 hir::TyKind::Def(hir::ItemId { id: exist_ty_id.node_id }, lifetimes)
1394 fn lifetimes_from_impl_trait_bounds(
1396 exist_ty_id: NodeId,
1397 parent_index: DefIndex,
1398 bounds: &hir::GenericBounds,
1399 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1400 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1401 // appear in the bounds, excluding lifetimes that are created within the bounds.
1402 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1403 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1404 context: &'r mut LoweringContext<'a>,
1406 exist_ty_id: NodeId,
1407 collect_elided_lifetimes: bool,
1408 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1409 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1410 output_lifetimes: Vec<hir::GenericArg>,
1411 output_lifetime_params: Vec<hir::GenericParam>,
1414 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1415 fn nested_visit_map<'this>(
1417 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1418 hir::intravisit::NestedVisitorMap::None
1421 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1422 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1423 if parameters.parenthesized {
1424 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1425 self.collect_elided_lifetimes = false;
1426 hir::intravisit::walk_generic_args(self, span, parameters);
1427 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1429 hir::intravisit::walk_generic_args(self, span, parameters);
1433 fn visit_ty(&mut self, t: &'v hir::Ty) {
1434 // Don't collect elided lifetimes used inside of `fn()` syntax
1435 if let hir::TyKind::BareFn(_) = t.node {
1436 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1437 self.collect_elided_lifetimes = false;
1439 // Record the "stack height" of `for<'a>` lifetime bindings
1440 // to be able to later fully undo their introduction.
1441 let old_len = self.currently_bound_lifetimes.len();
1442 hir::intravisit::walk_ty(self, t);
1443 self.currently_bound_lifetimes.truncate(old_len);
1445 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1447 hir::intravisit::walk_ty(self, t)
1451 fn visit_poly_trait_ref(
1453 trait_ref: &'v hir::PolyTraitRef,
1454 modifier: hir::TraitBoundModifier,
1456 // Record the "stack height" of `for<'a>` lifetime bindings
1457 // to be able to later fully undo their introduction.
1458 let old_len = self.currently_bound_lifetimes.len();
1459 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1460 self.currently_bound_lifetimes.truncate(old_len);
1463 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1464 // Record the introduction of 'a in `for<'a> ...`
1465 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1466 // Introduce lifetimes one at a time so that we can handle
1467 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1468 let lt_name = hir::LifetimeName::Param(param.name);
1469 self.currently_bound_lifetimes.push(lt_name);
1472 hir::intravisit::walk_generic_param(self, param);
1475 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1476 let name = match lifetime.name {
1477 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1478 if self.collect_elided_lifetimes {
1479 // Use `'_` for both implicit and underscore lifetimes in
1480 // `abstract type Foo<'_>: SomeTrait<'_>;`
1481 hir::LifetimeName::Underscore
1486 hir::LifetimeName::Param(_) => lifetime.name,
1487 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1490 if !self.currently_bound_lifetimes.contains(&name)
1491 && !self.already_defined_lifetimes.contains(&name) {
1492 self.already_defined_lifetimes.insert(name);
1494 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1495 id: self.context.next_id().node_id,
1496 span: lifetime.span,
1500 // We need to manually create the ids here, because the
1501 // definitions will go into the explicit `existential type`
1502 // declaration and thus need to have their owner set to that item
1503 let def_node_id = self.context.sess.next_node_id();
1504 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1505 self.context.resolver.definitions().create_def_with_parent(
1508 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1509 DefIndexAddressSpace::High,
1514 let (name, kind) = match name {
1515 hir::LifetimeName::Underscore => (
1516 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident()),
1517 hir::LifetimeParamKind::Elided,
1519 hir::LifetimeName::Param(param_name) => (
1521 hir::LifetimeParamKind::Explicit,
1523 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1526 self.output_lifetime_params.push(hir::GenericParam {
1529 span: lifetime.span,
1530 pure_wrt_drop: false,
1533 kind: hir::GenericParamKind::Lifetime { kind }
1539 let mut lifetime_collector = ImplTraitLifetimeCollector {
1541 parent: parent_index,
1543 collect_elided_lifetimes: true,
1544 currently_bound_lifetimes: Vec::new(),
1545 already_defined_lifetimes: FxHashSet::default(),
1546 output_lifetimes: Vec::new(),
1547 output_lifetime_params: Vec::new(),
1550 for bound in bounds {
1551 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1555 lifetime_collector.output_lifetimes.into(),
1556 lifetime_collector.output_lifetime_params.into(),
1560 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1565 .map(|x| self.lower_foreign_item(x))
1570 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1577 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1579 node: hir::VariantKind {
1580 name: v.node.ident.name,
1581 attrs: self.lower_attrs(&v.node.attrs),
1582 data: self.lower_variant_data(&v.node.data),
1583 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1592 qself: &Option<QSelf>,
1594 param_mode: ParamMode,
1595 mut itctx: ImplTraitContext<'_>,
1597 let qself_position = qself.as_ref().map(|q| q.position);
1598 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1600 let resolution = self.resolver
1602 .unwrap_or_else(|| PathResolution::new(Def::Err));
1604 let proj_start = p.segments.len() - resolution.unresolved_segments();
1605 let path = P(hir::Path {
1606 def: resolution.base_def(),
1607 segments: p.segments[..proj_start]
1610 .map(|(i, segment)| {
1611 let param_mode = match (qself_position, param_mode) {
1612 (Some(j), ParamMode::Optional) if i < j => {
1613 // This segment is part of the trait path in a
1614 // qualified path - one of `a`, `b` or `Trait`
1615 // in `<X as a::b::Trait>::T::U::method`.
1621 // Figure out if this is a type/trait segment,
1622 // which may need lifetime elision performed.
1623 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1624 krate: def_id.krate,
1625 index: this.def_key(def_id).parent.expect("missing parent"),
1627 let type_def_id = match resolution.base_def() {
1628 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1629 Some(parent_def_id(self, def_id))
1631 Def::Variant(def_id) if i + 1 == proj_start => {
1632 Some(parent_def_id(self, def_id))
1635 | Def::Union(def_id)
1637 | Def::TyAlias(def_id)
1638 | Def::Trait(def_id) if i + 1 == proj_start =>
1644 let parenthesized_generic_args = match resolution.base_def() {
1645 // `a::b::Trait(Args)`
1646 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1647 // `a::b::Trait(Args)::TraitItem`
1648 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1649 if i + 2 == proj_start =>
1651 ParenthesizedGenericArgs::Ok
1653 // Avoid duplicated errors
1654 Def::Err => ParenthesizedGenericArgs::Ok,
1660 | Def::Variant(..) if i + 1 == proj_start =>
1662 ParenthesizedGenericArgs::Err
1664 // A warning for now, for compatibility reasons
1665 _ => ParenthesizedGenericArgs::Warn,
1668 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1669 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1672 assert!(!def_id.is_local());
1674 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1675 let n = item_generics.own_counts().lifetimes;
1676 self.type_def_lifetime_params.insert(def_id, n);
1679 self.lower_path_segment(
1684 parenthesized_generic_args,
1693 // Simple case, either no projections, or only fully-qualified.
1694 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1695 if resolution.unresolved_segments() == 0 {
1696 return hir::QPath::Resolved(qself, path);
1699 // Create the innermost type that we're projecting from.
1700 let mut ty = if path.segments.is_empty() {
1701 // If the base path is empty that means there exists a
1702 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1703 qself.expect("missing QSelf for <T>::...")
1705 // Otherwise, the base path is an implicit `Self` type path,
1706 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1707 // `<I as Iterator>::Item::default`.
1708 let new_id = self.next_id();
1709 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1712 // Anything after the base path are associated "extensions",
1713 // out of which all but the last one are associated types,
1714 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1715 // * base path is `std::vec::Vec<T>`
1716 // * "extensions" are `IntoIter`, `Item` and `clone`
1717 // * type nodes are:
1718 // 1. `std::vec::Vec<T>` (created above)
1719 // 2. `<std::vec::Vec<T>>::IntoIter`
1720 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1721 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1722 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1723 let segment = P(self.lower_path_segment(
1728 ParenthesizedGenericArgs::Warn,
1732 let qpath = hir::QPath::TypeRelative(ty, segment);
1734 // It's finished, return the extension of the right node type.
1735 if i == p.segments.len() - 1 {
1739 // Wrap the associated extension in another type node.
1740 let new_id = self.next_id();
1741 ty = P(self.ty_path(new_id, p.span, qpath));
1744 // Should've returned in the for loop above.
1747 "lower_qpath: no final extension segment in {}..{}",
1753 fn lower_path_extra(
1757 param_mode: ParamMode,
1758 explicit_owner: Option<NodeId>,
1762 segments: p.segments
1765 self.lower_path_segment(
1770 ParenthesizedGenericArgs::Err,
1771 ImplTraitContext::disallowed(),
1780 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1781 let def = self.expect_full_def(id);
1782 self.lower_path_extra(def, p, param_mode, None)
1785 fn lower_path_segment(
1788 segment: &PathSegment,
1789 param_mode: ParamMode,
1790 expected_lifetimes: usize,
1791 parenthesized_generic_args: ParenthesizedGenericArgs,
1792 itctx: ImplTraitContext<'_>,
1793 explicit_owner: Option<NodeId>,
1794 ) -> hir::PathSegment {
1795 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1796 let msg = "parenthesized parameters may only be used with a trait";
1797 match **generic_args {
1798 GenericArgs::AngleBracketed(ref data) => {
1799 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1801 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1802 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1803 ParenthesizedGenericArgs::Warn => {
1804 self.sess.buffer_lint(
1805 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1810 (hir::GenericArgs::none(), true)
1812 ParenthesizedGenericArgs::Err => {
1813 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1814 .span_label(data.span, "only traits may use parentheses")
1816 (hir::GenericArgs::none(), true)
1821 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1824 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1825 GenericArg::Lifetime(_) => true,
1828 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1829 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1830 if !generic_args.parenthesized && !has_lifetimes {
1832 self.elided_path_lifetimes(path_span, expected_lifetimes)
1834 .map(|lt| GenericArg::Lifetime(lt))
1835 .chain(generic_args.args.into_iter())
1837 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1838 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1839 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1840 let no_bindings = generic_args.bindings.is_empty();
1841 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1842 // If there are no (non-implicit) generic args or associated-type
1843 // bindings, our suggestion includes the angle brackets
1844 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1846 // Otherwise—sorry, this is kind of gross—we need to infer the
1847 // place to splice in the `'_, ` from the generics that do exist
1848 let first_generic_span = first_generic_span
1849 .expect("already checked that type args or bindings exist");
1850 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1852 self.sess.buffer_lint_with_diagnostic(
1853 ELIDED_LIFETIMES_IN_PATHS,
1856 "hidden lifetime parameters in types are deprecated",
1857 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1858 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1864 let def = self.expect_full_def(segment.id);
1865 let id = if let Some(owner) = explicit_owner {
1866 self.lower_node_id_with_owner(segment.id, owner)
1868 self.lower_node_id(segment.id)
1871 hir::PathSegment::new(
1880 fn lower_angle_bracketed_parameter_data(
1882 data: &AngleBracketedArgs,
1883 param_mode: ParamMode,
1884 mut itctx: ImplTraitContext<'_>,
1885 ) -> (hir::GenericArgs, bool) {
1886 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1887 let has_types = args.iter().any(|arg| match arg {
1888 ast::GenericArg::Type(_) => true,
1892 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1893 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1894 parenthesized: false,
1896 !has_types && param_mode == ParamMode::Optional)
1899 fn lower_parenthesized_parameter_data(
1901 data: &ParenthesisedArgs,
1902 ) -> (hir::GenericArgs, bool) {
1903 // Switch to `PassThrough` mode for anonymous lifetimes: this
1904 // means that we permit things like `&Ref<T>`, where `Ref` has
1905 // a hidden lifetime parameter. This is needed for backwards
1906 // compatibility, even in contexts like an impl header where
1907 // we generally don't permit such things (see #51008).
1908 self.with_anonymous_lifetime_mode(
1909 AnonymousLifetimeMode::PassThrough,
1911 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1914 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
1916 let mk_tup = |this: &mut Self, tys, span| {
1917 let LoweredNodeId { node_id, hir_id } = this.next_id();
1918 hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1923 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1926 id: this.next_id().node_id,
1927 ident: Ident::from_str(FN_OUTPUT_NAME),
1930 .map(|ty| this.lower_ty(&ty, ImplTraitContext::disallowed()))
1931 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1932 span: output.as_ref().map_or(span, |ty| ty.span),
1935 parenthesized: true,
1943 fn lower_local(&mut self, l: &Local) -> (P<hir::Local>, SmallVec<[hir::ItemId; 1]>) {
1944 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1945 let mut ids = SmallVec::<[hir::ItemId; 1]>::new();
1946 if self.sess.features_untracked().impl_trait_in_bindings {
1947 if let Some(ref ty) = l.ty {
1948 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
1949 visitor.visit_ty(ty);
1952 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
1958 .map(|t| self.lower_ty(t,
1959 if self.sess.features_untracked().impl_trait_in_bindings {
1960 ImplTraitContext::Existential(Some(parent_def_id))
1962 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
1965 pat: self.lower_pat(&l.pat),
1966 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1968 attrs: l.attrs.clone(),
1969 source: hir::LocalSource::Normal,
1973 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1975 Mutability::Mutable => hir::MutMutable,
1976 Mutability::Immutable => hir::MutImmutable,
1980 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1981 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1985 pat: self.lower_pat(&arg.pat),
1989 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1992 .map(|arg| match arg.pat.node {
1993 PatKind::Ident(_, ident, _) => ident,
1994 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
1999 // Lowers a function declaration.
2001 // decl: the unlowered (ast) function declaration.
2002 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
2003 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2004 // make_ret_async is also `Some`.
2005 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
2006 // This guards against trait declarations and implementations where impl Trait is
2008 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2009 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
2010 // return type impl Trait item.
2014 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2015 impl_trait_return_allow: bool,
2016 make_ret_async: Option<NodeId>,
2017 ) -> P<hir::FnDecl> {
2018 let inputs = decl.inputs
2021 if let Some((_, ref mut ibty)) = in_band_ty_params {
2022 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2024 self.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2027 .collect::<HirVec<_>>();
2029 let output = if let Some(ret_id) = make_ret_async {
2030 self.lower_async_fn_ret_ty(
2033 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
2038 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2039 Some((def_id, _)) if impl_trait_return_allow => {
2040 hir::Return(self.lower_ty(ty,
2041 ImplTraitContext::Existential(Some(def_id))))
2044 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2047 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2054 variadic: decl.variadic,
2055 implicit_self: decl.inputs.get(0).map_or(
2056 hir::ImplicitSelfKind::None,
2058 let is_mutable_pat = match arg.pat.node {
2059 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2060 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2061 mt == Mutability::Mutable,
2066 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2067 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2068 // Given we are only considering `ImplicitSelf` types, we needn't consider
2069 // the case where we have a mutable pattern to a reference as that would
2070 // no longer be an `ImplicitSelf`.
2071 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2072 mt.mutbl == ast::Mutability::Mutable =>
2073 hir::ImplicitSelfKind::MutRef,
2074 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2075 hir::ImplicitSelfKind::ImmRef,
2076 _ => hir::ImplicitSelfKind::None,
2083 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
2085 // fn_span: the span of the async function declaration. Used for error reporting.
2086 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
2087 // output: unlowered output type (`T` in `-> T`)
2088 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
2089 fn lower_async_fn_ret_ty(
2092 output: &FunctionRetTy,
2094 return_impl_trait_id: NodeId,
2095 ) -> hir::FunctionRetTy {
2096 // Get lifetimes used in the input arguments to the function. Our output type must also
2097 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
2098 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
2099 // is a subset of the other. We really want some new lifetime that is a subset of all input
2100 // lifetimes, but that doesn't exist at the moment.
2102 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
2103 context: &'r mut LoweringContext<'a>,
2104 // Lifetimes bound by HRTB
2105 currently_bound_lifetimes: Vec<hir::LifetimeName>,
2106 // Whether to count elided lifetimes.
2107 // Disabled inside of `Fn` or `fn` syntax.
2108 collect_elided_lifetimes: bool,
2109 // The lifetime found.
2110 // Multiple different or elided lifetimes cannot appear in async fn for now.
2111 output_lifetime: Option<(hir::LifetimeName, Span)>,
2114 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
2115 fn nested_visit_map<'this>(
2117 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
2118 hir::intravisit::NestedVisitorMap::None
2121 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
2122 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2123 if parameters.parenthesized {
2124 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2125 self.collect_elided_lifetimes = false;
2126 hir::intravisit::walk_generic_args(self, span, parameters);
2127 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2129 hir::intravisit::walk_generic_args(self, span, parameters);
2133 fn visit_ty(&mut self, t: &'v hir::Ty) {
2134 // Don't collect elided lifetimes used inside of `fn()` syntax
2135 if let &hir::TyKind::BareFn(_) = &t.node {
2136 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2137 self.collect_elided_lifetimes = false;
2139 // Record the "stack height" of `for<'a>` lifetime bindings
2140 // to be able to later fully undo their introduction.
2141 let old_len = self.currently_bound_lifetimes.len();
2142 hir::intravisit::walk_ty(self, t);
2143 self.currently_bound_lifetimes.truncate(old_len);
2145 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2147 hir::intravisit::walk_ty(self, t);
2151 fn visit_poly_trait_ref(
2153 trait_ref: &'v hir::PolyTraitRef,
2154 modifier: hir::TraitBoundModifier,
2156 // Record the "stack height" of `for<'a>` lifetime bindings
2157 // to be able to later fully undo their introduction.
2158 let old_len = self.currently_bound_lifetimes.len();
2159 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2160 self.currently_bound_lifetimes.truncate(old_len);
2163 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2164 // Record the introduction of 'a in `for<'a> ...`
2165 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2166 // Introduce lifetimes one at a time so that we can handle
2167 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2168 let lt_name = hir::LifetimeName::Param(param.name);
2169 self.currently_bound_lifetimes.push(lt_name);
2172 hir::intravisit::walk_generic_param(self, param);
2175 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2176 let name = match lifetime.name {
2177 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2178 if self.collect_elided_lifetimes {
2179 // Use `'_` for both implicit and underscore lifetimes in
2180 // `abstract type Foo<'_>: SomeTrait<'_>;`
2181 hir::LifetimeName::Underscore
2186 hir::LifetimeName::Param(_) => lifetime.name,
2187 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
2190 if !self.currently_bound_lifetimes.contains(&name) {
2191 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2192 // We don't currently have a reliable way to desugar `async fn` with
2193 // multiple potentially unrelated input lifetimes into
2194 // `-> impl Trait + 'lt`, so we report an error in this case.
2195 if current_lt_name != name {
2198 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2200 "multiple different lifetimes used in arguments of `async fn`",
2202 .span_label(current_lt_span, "first lifetime here")
2203 .span_label(lifetime.span, "different lifetime here")
2204 .help("`async fn` can only accept borrowed values \
2205 with identical lifetimes")
2207 } else if current_lt_name.is_elided() && name.is_elided() {
2210 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2212 "multiple elided lifetimes used in arguments of `async fn`",
2214 .span_label(current_lt_span, "first lifetime here")
2215 .span_label(lifetime.span, "different lifetime here")
2216 .help("consider giving these arguments named lifetimes")
2220 self.output_lifetime = Some((name, lifetime.span));
2226 let bound_lifetime = {
2227 let mut lifetime_collector = AsyncFnLifetimeCollector {
2229 currently_bound_lifetimes: Vec::new(),
2230 collect_elided_lifetimes: true,
2231 output_lifetime: None,
2235 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2237 lifetime_collector.output_lifetime
2240 let span = match output {
2241 FunctionRetTy::Ty(ty) => ty.span,
2242 FunctionRetTy::Default(span) => *span,
2245 let impl_trait_ty = self.lower_existential_impl_trait(
2246 span, Some(fn_def_id), return_impl_trait_id, |this| {
2247 let output_ty = match output {
2248 FunctionRetTy::Ty(ty) => {
2249 this.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2251 FunctionRetTy::Default(span) => {
2252 let LoweredNodeId { node_id, hir_id } = this.next_id();
2256 node: hir::TyKind::Tup(hir_vec![]),
2263 let future_params = P(hir::GenericArgs {
2265 bindings: hir_vec![hir::TypeBinding {
2266 ident: Ident::from_str(FN_OUTPUT_NAME),
2268 id: this.next_id().node_id,
2271 parenthesized: false,
2275 this.std_path(span, &["future", "Future"], Some(future_params), false);
2277 let LoweredNodeId { node_id, hir_id } = this.next_id();
2278 let mut bounds = vec![
2279 hir::GenericBound::Trait(
2281 trait_ref: hir::TraitRef {
2286 bound_generic_params: hir_vec![],
2289 hir::TraitBoundModifier::None
2293 if let Some((name, span)) = bound_lifetime {
2294 bounds.push(hir::GenericBound::Outlives(
2295 hir::Lifetime { id: this.next_id().node_id, name, span }));
2298 hir::HirVec::from(bounds)
2301 let LoweredNodeId { node_id, hir_id } = self.next_id();
2302 let impl_trait_ty = P(hir::Ty {
2304 node: impl_trait_ty,
2309 hir::FunctionRetTy::Return(impl_trait_ty)
2312 fn lower_param_bound(
2315 itctx: ImplTraitContext<'_>,
2316 ) -> hir::GenericBound {
2318 GenericBound::Trait(ref ty, modifier) => {
2319 hir::GenericBound::Trait(
2320 self.lower_poly_trait_ref(ty, itctx),
2321 self.lower_trait_bound_modifier(modifier),
2324 GenericBound::Outlives(ref lifetime) => {
2325 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2330 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2331 let span = l.ident.span;
2333 ident if ident.name == keywords::StaticLifetime.name() =>
2334 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2335 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2336 match self.anonymous_lifetime_mode {
2337 AnonymousLifetimeMode::CreateParameter => {
2338 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2339 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2342 AnonymousLifetimeMode::PassThrough => {
2343 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2346 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2349 self.maybe_collect_in_band_lifetime(ident);
2350 let param_name = ParamName::Plain(ident);
2351 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2356 fn new_named_lifetime(
2360 name: hir::LifetimeName,
2361 ) -> hir::Lifetime {
2363 id: self.lower_node_id(id).node_id,
2369 fn lower_generic_params(
2371 params: &[GenericParam],
2372 add_bounds: &NodeMap<Vec<GenericBound>>,
2373 mut itctx: ImplTraitContext<'_>,
2374 ) -> hir::HirVec<hir::GenericParam> {
2375 params.iter().map(|param| {
2376 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2380 fn lower_generic_param(&mut self,
2381 param: &GenericParam,
2382 add_bounds: &NodeMap<Vec<GenericBound>>,
2383 mut itctx: ImplTraitContext<'_>)
2384 -> hir::GenericParam {
2385 let mut bounds = self.with_anonymous_lifetime_mode(
2386 AnonymousLifetimeMode::ReportError,
2387 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2391 GenericParamKind::Lifetime => {
2392 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2393 self.is_collecting_in_band_lifetimes = false;
2395 let lt = self.with_anonymous_lifetime_mode(
2396 AnonymousLifetimeMode::ReportError,
2397 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2399 let param_name = match lt.name {
2400 hir::LifetimeName::Param(param_name) => param_name,
2401 hir::LifetimeName::Implicit
2402 | hir::LifetimeName::Underscore
2403 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2404 hir::LifetimeName::Error => ParamName::Error,
2406 let param = hir::GenericParam {
2410 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2411 attrs: self.lower_attrs(¶m.attrs),
2413 kind: hir::GenericParamKind::Lifetime {
2414 kind: hir::LifetimeParamKind::Explicit,
2418 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2422 GenericParamKind::Type { ref default, .. } => {
2423 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2424 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2425 // Instead, use gensym("Self") to create a distinct name that looks the same.
2426 let ident = if param.ident.name == keywords::SelfType.name() {
2427 param.ident.gensym()
2432 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2433 if !add_bounds.is_empty() {
2434 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2435 bounds = bounds.into_iter()
2441 id: self.lower_node_id(param.id).node_id,
2442 name: hir::ParamName::Plain(ident),
2443 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2444 attrs: self.lower_attrs(¶m.attrs),
2447 kind: hir::GenericParamKind::Type {
2448 default: default.as_ref().map(|x| {
2449 self.lower_ty(x, ImplTraitContext::disallowed())
2451 synthetic: param.attrs.iter()
2452 .filter(|attr| attr.check_name("rustc_synthetic"))
2453 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2463 generics: &Generics,
2464 itctx: ImplTraitContext<'_>)
2467 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2468 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2469 // paths where report_error is called are also the only paths that advance to after
2470 // the match statement, so the error reporting could probably just be moved there.
2471 let mut add_bounds: NodeMap<Vec<_>> = NodeMap();
2472 for pred in &generics.where_clause.predicates {
2473 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2474 'next_bound: for bound in &bound_pred.bounds {
2475 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2476 let report_error = |this: &mut Self| {
2477 this.diagnostic().span_err(
2478 bound_pred.bounded_ty.span,
2479 "`?Trait` bounds are only permitted at the \
2480 point where a type parameter is declared",
2483 // Check if the where clause type is a plain type parameter.
2484 match bound_pred.bounded_ty.node {
2485 TyKind::Path(None, ref path)
2486 if path.segments.len() == 1
2487 && bound_pred.bound_generic_params.is_empty() =>
2489 if let Some(Def::TyParam(def_id)) = self.resolver
2490 .get_resolution(bound_pred.bounded_ty.id)
2491 .map(|d| d.base_def())
2493 if let Some(node_id) =
2494 self.resolver.definitions().as_local_node_id(def_id)
2496 for param in &generics.params {
2498 GenericParamKind::Type { .. } => {
2499 if node_id == param.id {
2500 add_bounds.entry(param.id)
2502 .push(bound.clone());
2503 continue 'next_bound;
2513 _ => report_error(self),
2521 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2522 where_clause: self.lower_where_clause(&generics.where_clause),
2523 span: generics.span,
2527 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2528 self.with_anonymous_lifetime_mode(
2529 AnonymousLifetimeMode::ReportError,
2532 id: this.lower_node_id(wc.id).node_id,
2533 predicates: wc.predicates
2535 .map(|predicate| this.lower_where_predicate(predicate))
2542 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2544 WherePredicate::BoundPredicate(WhereBoundPredicate {
2545 ref bound_generic_params,
2550 self.with_in_scope_lifetime_defs(
2551 &bound_generic_params,
2553 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2554 bound_generic_params: this.lower_generic_params(
2555 bound_generic_params,
2557 ImplTraitContext::disallowed(),
2559 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
2562 .filter_map(|bound| match *bound {
2563 // Ignore `?Trait` bounds.
2564 // Tthey were copied into type parameters already.
2565 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2566 _ => Some(this.lower_param_bound(
2568 ImplTraitContext::disallowed(),
2577 WherePredicate::RegionPredicate(WhereRegionPredicate {
2581 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2583 lifetime: self.lower_lifetime(lifetime),
2584 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2586 WherePredicate::EqPredicate(WhereEqPredicate {
2591 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2592 id: self.lower_node_id(id).node_id,
2593 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
2594 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
2600 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2602 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2606 .map(|f| self.lower_struct_field(f))
2608 self.lower_node_id(id).node_id,
2610 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2614 .map(|f| self.lower_struct_field(f))
2616 self.lower_node_id(id).node_id,
2618 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2622 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2623 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2624 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2625 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2627 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.ref_id);
2635 fn lower_poly_trait_ref(
2638 mut itctx: ImplTraitContext<'_>,
2639 ) -> hir::PolyTraitRef {
2640 let bound_generic_params =
2641 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx.reborrow());
2642 let trait_ref = self.with_parent_impl_lifetime_defs(
2643 &bound_generic_params,
2644 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2648 bound_generic_params,
2654 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2657 id: self.lower_node_id(f.id).node_id,
2658 ident: match f.ident {
2659 Some(ident) => ident,
2660 // FIXME(jseyfried) positional field hygiene
2661 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2663 vis: self.lower_visibility(&f.vis, None),
2664 ty: self.lower_ty(&f.ty, ImplTraitContext::disallowed()),
2665 attrs: self.lower_attrs(&f.attrs),
2669 fn lower_field(&mut self, f: &Field) -> hir::Field {
2671 id: self.next_id().node_id,
2673 expr: P(self.lower_expr(&f.expr)),
2675 is_shorthand: f.is_shorthand,
2679 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2681 ty: self.lower_ty(&mt.ty, itctx),
2682 mutbl: self.lower_mutability(mt.mutbl),
2686 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2687 -> hir::GenericBounds {
2688 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2691 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2692 let mut expr = None;
2694 let mut stmts = vec![];
2696 for (index, stmt) in b.stmts.iter().enumerate() {
2697 if index == b.stmts.len() - 1 {
2698 if let StmtKind::Expr(ref e) = stmt.node {
2699 expr = Some(P(self.lower_expr(e)));
2701 stmts.extend(self.lower_stmt(stmt));
2704 stmts.extend(self.lower_stmt(stmt));
2708 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2713 stmts: stmts.into(),
2715 rules: self.lower_block_check_mode(&b.rules),
2718 recovered: b.recovered,
2722 fn lower_async_body(
2728 self.lower_body(Some(decl), |this| {
2729 if let IsAsync::Async { closure_id, .. } = asyncness {
2730 let async_expr = this.make_async_expr(
2731 CaptureBy::Value, closure_id, None,
2733 let body = this.lower_block(body, false);
2734 this.expr_block(body, ThinVec::new())
2736 this.expr(body.span, async_expr, ThinVec::new())
2738 let body = this.lower_block(body, false);
2739 this.expr_block(body, ThinVec::new())
2748 attrs: &hir::HirVec<Attribute>,
2749 vis: &mut hir::Visibility,
2751 ) -> hir::ItemKind {
2753 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2754 ItemKind::Use(ref use_tree) => {
2755 // Start with an empty prefix
2758 span: use_tree.span,
2761 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2763 ItemKind::Static(ref t, m, ref e) => {
2764 let value = self.lower_body(None, |this| this.lower_expr(e));
2765 hir::ItemKind::Static(
2768 if self.sess.features_untracked().impl_trait_in_bindings {
2769 ImplTraitContext::Existential(None)
2771 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2774 self.lower_mutability(m),
2778 ItemKind::Const(ref t, ref e) => {
2779 let value = self.lower_body(None, |this| this.lower_expr(e));
2780 hir::ItemKind::Const(
2783 if self.sess.features_untracked().impl_trait_in_bindings {
2784 ImplTraitContext::Existential(None)
2786 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2792 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2793 let fn_def_id = self.resolver.definitions().local_def_id(id);
2794 self.with_new_scopes(|this| {
2795 // Note: we don't need to change the return type from `T` to
2796 // `impl Future<Output = T>` here because lower_body
2797 // only cares about the input argument patterns in the function
2798 // declaration (decl), not the return types.
2799 let body_id = this.lower_async_body(decl, header.asyncness, body);
2801 let (generics, fn_decl) = this.add_in_band_defs(
2804 AnonymousLifetimeMode::PassThrough,
2805 |this, idty| this.lower_fn_decl(
2807 Some((fn_def_id, idty)),
2809 header.asyncness.opt_return_id()
2815 this.lower_fn_header(header),
2821 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2822 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2823 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2824 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2825 self.lower_ty(t, ImplTraitContext::disallowed()),
2826 self.lower_generics(generics, ImplTraitContext::disallowed()),
2828 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2829 generics: self.lower_generics(generics, ImplTraitContext::disallowed()),
2830 bounds: self.lower_param_bounds(b, ImplTraitContext::disallowed()),
2831 impl_trait_fn: None,
2833 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2835 variants: enum_definition
2838 .map(|x| self.lower_variant(x))
2841 self.lower_generics(generics, ImplTraitContext::disallowed()),
2843 ItemKind::Struct(ref struct_def, ref generics) => {
2844 let struct_def = self.lower_variant_data(struct_def);
2845 hir::ItemKind::Struct(
2847 self.lower_generics(generics, ImplTraitContext::disallowed()),
2850 ItemKind::Union(ref vdata, ref generics) => {
2851 let vdata = self.lower_variant_data(vdata);
2852 hir::ItemKind::Union(
2854 self.lower_generics(generics, ImplTraitContext::disallowed()),
2866 let def_id = self.resolver.definitions().local_def_id(id);
2868 // Lower the "impl header" first. This ordering is important
2869 // for in-band lifetimes! Consider `'a` here:
2871 // impl Foo<'a> for u32 {
2872 // fn method(&'a self) { .. }
2875 // Because we start by lowering the `Foo<'a> for u32`
2876 // part, we will add `'a` to the list of generics on
2877 // the impl. When we then encounter it later in the
2878 // method, it will not be considered an in-band
2879 // lifetime to be added, but rather a reference to a
2881 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2884 AnonymousLifetimeMode::CreateParameter,
2886 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2887 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
2890 if let Some(ref trait_ref) = trait_ref {
2891 if let Def::Trait(def_id) = trait_ref.path.def {
2892 this.trait_impls.entry(def_id).or_default().push(id);
2896 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
2898 (trait_ref, lowered_ty)
2902 let new_impl_items = self.with_in_scope_lifetime_defs(
2903 &ast_generics.params,
2907 .map(|item| this.lower_impl_item_ref(item))
2912 hir::ItemKind::Impl(
2913 self.lower_unsafety(unsafety),
2914 self.lower_impl_polarity(polarity),
2915 self.lower_defaultness(defaultness, true /* [1] */),
2922 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2923 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
2926 .map(|item| self.lower_trait_item_ref(item))
2928 hir::ItemKind::Trait(
2929 self.lower_is_auto(is_auto),
2930 self.lower_unsafety(unsafety),
2931 self.lower_generics(generics, ImplTraitContext::disallowed()),
2936 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
2937 self.lower_generics(generics, ImplTraitContext::disallowed()),
2938 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2940 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2943 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2944 // not cause an assertion failure inside the `lower_defaultness` function
2952 vis: &mut hir::Visibility,
2954 attrs: &hir::HirVec<Attribute>,
2955 ) -> hir::ItemKind {
2956 let path = &tree.prefix;
2957 let segments = prefix
2960 .chain(path.segments.iter())
2965 UseTreeKind::Simple(rename, id1, id2) => {
2966 *name = tree.ident().name;
2968 // First apply the prefix to the path
2969 let mut path = Path {
2974 // Correctly resolve `self` imports
2975 if path.segments.len() > 1
2976 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2978 let _ = path.segments.pop();
2979 if rename.is_none() {
2980 *name = path.segments.last().unwrap().ident.name;
2984 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2985 let mut defs = self.expect_full_def_from_use(id);
2986 // we want to return *something* from this function, so hang onto the first item
2988 let ret_def = defs.next().unwrap_or(Def::Err);
2990 // Here, we are looping over namespaces, if they exist for the definition
2991 // being imported. We only handle type and value namespaces because we
2992 // won't be dealing with macros in the rest of the compiler.
2993 // Essentially a single `use` which imports two names is desugared into
2995 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2996 let vis = vis.clone();
2997 let name = name.clone();
2998 let mut path = path.clone();
2999 for seg in &mut path.segments {
3000 seg.id = self.sess.next_node_id();
3002 let span = path.span;
3003 self.resolver.definitions().create_def_with_parent(
3007 DefIndexAddressSpace::High,
3010 self.allocate_hir_id_counter(new_node_id, &path);
3012 self.with_hir_id_owner(new_node_id, |this| {
3013 let new_id = this.lower_node_id(new_node_id);
3015 this.lower_path_extra(def, &path, ParamMode::Explicit, None);
3016 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
3017 let vis_kind = match vis.node {
3018 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3019 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3020 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3021 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3022 let id = this.next_id();
3023 let mut path = path.clone();
3024 for seg in path.segments.iter_mut() {
3025 if seg.id.is_some() {
3026 seg.id = Some(this.next_id().node_id);
3029 hir::VisibilityKind::Restricted {
3036 let vis = respan(vis.span, vis_kind);
3042 hir_id: new_id.hir_id,
3044 attrs: attrs.clone(),
3054 P(self.lower_path_extra(ret_def, &path, ParamMode::Explicit, None));
3055 hir::ItemKind::Use(path, hir::UseKind::Single)
3057 UseTreeKind::Glob => {
3058 let path = P(self.lower_path(
3064 ParamMode::Explicit,
3066 hir::ItemKind::Use(path, hir::UseKind::Glob)
3068 UseTreeKind::Nested(ref trees) => {
3069 // Nested imports are desugared into simple imports.
3073 span: prefix.span.to(path.span),
3076 // Add all the nested PathListItems to the HIR.
3077 for &(ref use_tree, id) in trees {
3078 self.allocate_hir_id_counter(id, &use_tree);
3083 } = self.lower_node_id(id);
3085 let mut vis = vis.clone();
3086 let mut name = name.clone();
3087 let mut prefix = prefix.clone();
3089 // Give the segments new ids since they are being cloned.
3090 for seg in &mut prefix.segments {
3091 seg.id = self.sess.next_node_id();
3094 // Each `use` import is an item and thus are owners of the
3095 // names in the path. Up to this point the nested import is
3096 // the current owner, since we want each desugared import to
3097 // own its own names, we have to adjust the owner before
3098 // lowering the rest of the import.
3099 self.with_hir_id_owner(new_id, |this| {
3100 let item = this.lower_use_tree(use_tree,
3107 let vis_kind = match vis.node {
3108 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3109 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3110 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3111 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3112 let id = this.next_id();
3113 hir::VisibilityKind::Restricted {
3120 let vis = respan(vis.span, vis_kind);
3128 attrs: attrs.clone(),
3131 span: use_tree.span,
3137 // Privatize the degenerate import base, used only to check
3138 // the stability of `use a::{};`, to avoid it showing up as
3139 // a re-export by accident when `pub`, e.g. in documentation.
3140 let def = self.expect_full_def_from_use(id).next().unwrap_or(Def::Err);
3141 let path = P(self.lower_path_extra(def, &prefix, ParamMode::Explicit, None));
3142 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3143 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3148 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3149 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3150 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
3152 let (generics, node) = match i.node {
3153 TraitItemKind::Const(ref ty, ref default) => (
3154 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3155 hir::TraitItemKind::Const(
3156 self.lower_ty(ty, ImplTraitContext::disallowed()),
3159 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
3162 TraitItemKind::Method(ref sig, None) => {
3163 let names = self.lower_fn_args_to_names(&sig.decl);
3164 let (generics, sig) = self.lower_method_sig(
3171 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3173 TraitItemKind::Method(ref sig, Some(ref body)) => {
3174 let body_id = self.lower_body(Some(&sig.decl), |this| {
3175 let body = this.lower_block(body, false);
3176 this.expr_block(body, ThinVec::new())
3178 let (generics, sig) = self.lower_method_sig(
3185 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3187 TraitItemKind::Type(ref bounds, ref default) => (
3188 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3189 hir::TraitItemKind::Type(
3190 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3193 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3196 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3203 attrs: self.lower_attrs(&i.attrs),
3210 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3211 let (kind, has_default) = match i.node {
3212 TraitItemKind::Const(_, ref default) => {
3213 (hir::AssociatedItemKind::Const, default.is_some())
3215 TraitItemKind::Type(_, ref default) => {
3216 (hir::AssociatedItemKind::Type, default.is_some())
3218 TraitItemKind::Method(ref sig, ref default) => (
3219 hir::AssociatedItemKind::Method {
3220 has_self: sig.decl.has_self(),
3224 TraitItemKind::Macro(..) => unimplemented!(),
3227 id: hir::TraitItemId { node_id: i.id },
3230 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3235 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3236 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3237 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3239 let (generics, node) = match i.node {
3240 ImplItemKind::Const(ref ty, ref expr) => {
3241 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3243 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3244 hir::ImplItemKind::Const(
3245 self.lower_ty(ty, ImplTraitContext::disallowed()),
3250 ImplItemKind::Method(ref sig, ref body) => {
3251 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3252 let impl_trait_return_allow = !self.is_in_trait_impl;
3253 let (generics, sig) = self.lower_method_sig(
3257 impl_trait_return_allow,
3258 sig.header.asyncness.opt_return_id(),
3260 (generics, hir::ImplItemKind::Method(sig, body_id))
3262 ImplItemKind::Type(ref ty) => (
3263 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3264 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3266 ImplItemKind::Existential(ref bounds) => (
3267 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3268 hir::ImplItemKind::Existential(
3269 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3272 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3279 attrs: self.lower_attrs(&i.attrs),
3281 vis: self.lower_visibility(&i.vis, None),
3282 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3287 // [1] since `default impl` is not yet implemented, this is always true in impls
3290 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3292 id: hir::ImplItemId { node_id: i.id },
3295 vis: self.lower_visibility(&i.vis, Some(i.id)),
3296 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3297 kind: match i.node {
3298 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3299 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3300 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3301 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3302 has_self: sig.decl.has_self(),
3304 ImplItemKind::Macro(..) => unimplemented!(),
3308 // [1] since `default impl` is not yet implemented, this is always true in impls
3311 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3314 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3318 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3320 ItemKind::Use(ref use_tree) => {
3321 let mut vec = smallvec![hir::ItemId { id: i.id }];
3322 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3325 ItemKind::MacroDef(..) => SmallVec::new(),
3327 ItemKind::Impl(.., None, _, _) => smallvec![hir::ItemId { id: i.id }],
3328 ItemKind::Static(ref ty, ..) => {
3329 let mut ids = smallvec![hir::ItemId { id: i.id }];
3330 if self.sess.features_untracked().impl_trait_in_bindings {
3331 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3332 visitor.visit_ty(ty);
3336 ItemKind::Const(ref ty, ..) => {
3337 let mut ids = smallvec![hir::ItemId { id: i.id }];
3338 if self.sess.features_untracked().impl_trait_in_bindings {
3339 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3340 visitor.visit_ty(ty);
3344 _ => smallvec![hir::ItemId { id: i.id }],
3348 fn lower_item_id_use_tree(&mut self,
3351 vec: &mut SmallVec<[hir::ItemId; 1]>)
3354 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3355 vec.push(hir::ItemId { id });
3356 self.lower_item_id_use_tree(nested, id, vec);
3358 UseTreeKind::Glob => {}
3359 UseTreeKind::Simple(_, id1, id2) => {
3360 for (_, &id) in self.expect_full_def_from_use(base_id)
3362 .zip([id1, id2].iter())
3364 vec.push(hir::ItemId { id });
3370 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3371 let mut name = i.ident.name;
3372 let mut vis = self.lower_visibility(&i.vis, None);
3373 let attrs = self.lower_attrs(&i.attrs);
3374 if let ItemKind::MacroDef(ref def) = i.node {
3375 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3376 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3377 let body = self.lower_token_stream(def.stream());
3378 self.exported_macros.push(hir::MacroDef {
3391 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3393 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3406 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3407 let node_id = self.lower_node_id(i.id).node_id;
3408 let def_id = self.resolver.definitions().local_def_id(node_id);
3412 attrs: self.lower_attrs(&i.attrs),
3413 node: match i.node {
3414 ForeignItemKind::Fn(ref fdec, ref generics) => {
3415 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3418 AnonymousLifetimeMode::PassThrough,
3421 // Disallow impl Trait in foreign items
3422 this.lower_fn_decl(fdec, None, false, None),
3423 this.lower_fn_args_to_names(fdec),
3428 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3430 ForeignItemKind::Static(ref t, m) => {
3431 hir::ForeignItemKind::Static(
3432 self.lower_ty(t, ImplTraitContext::disallowed()), m)
3434 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3435 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3437 vis: self.lower_visibility(&i.vis, None),
3442 fn lower_method_sig(
3444 generics: &Generics,
3447 impl_trait_return_allow: bool,
3448 is_async: Option<NodeId>,
3449 ) -> (hir::Generics, hir::MethodSig) {
3450 let header = self.lower_fn_header(sig.header);
3451 let (generics, decl) = self.add_in_band_defs(
3454 AnonymousLifetimeMode::PassThrough,
3455 |this, idty| this.lower_fn_decl(
3457 Some((fn_def_id, idty)),
3458 impl_trait_return_allow,
3462 (generics, hir::MethodSig { header, decl })
3465 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3467 IsAuto::Yes => hir::IsAuto::Yes,
3468 IsAuto::No => hir::IsAuto::No,
3472 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3474 unsafety: self.lower_unsafety(h.unsafety),
3475 asyncness: self.lower_asyncness(h.asyncness),
3476 constness: self.lower_constness(h.constness),
3481 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3483 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3484 Unsafety::Normal => hir::Unsafety::Normal,
3488 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3490 Constness::Const => hir::Constness::Const,
3491 Constness::NotConst => hir::Constness::NotConst,
3495 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3497 IsAsync::Async { .. } => hir::IsAsync::Async,
3498 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3502 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3504 UnOp::Deref => hir::UnDeref,
3505 UnOp::Not => hir::UnNot,
3506 UnOp::Neg => hir::UnNeg,
3510 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3512 node: match b.node {
3513 BinOpKind::Add => hir::BinOpKind::Add,
3514 BinOpKind::Sub => hir::BinOpKind::Sub,
3515 BinOpKind::Mul => hir::BinOpKind::Mul,
3516 BinOpKind::Div => hir::BinOpKind::Div,
3517 BinOpKind::Rem => hir::BinOpKind::Rem,
3518 BinOpKind::And => hir::BinOpKind::And,
3519 BinOpKind::Or => hir::BinOpKind::Or,
3520 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3521 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3522 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3523 BinOpKind::Shl => hir::BinOpKind::Shl,
3524 BinOpKind::Shr => hir::BinOpKind::Shr,
3525 BinOpKind::Eq => hir::BinOpKind::Eq,
3526 BinOpKind::Lt => hir::BinOpKind::Lt,
3527 BinOpKind::Le => hir::BinOpKind::Le,
3528 BinOpKind::Ne => hir::BinOpKind::Ne,
3529 BinOpKind::Ge => hir::BinOpKind::Ge,
3530 BinOpKind::Gt => hir::BinOpKind::Gt,
3536 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3537 let node = match p.node {
3538 PatKind::Wild => hir::PatKind::Wild,
3539 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3540 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3541 // `None` can occur in body-less function signatures
3542 def @ None | def @ Some(Def::Local(_)) => {
3543 let canonical_id = match def {
3544 Some(Def::Local(id)) => id,
3547 hir::PatKind::Binding(
3548 self.lower_binding_mode(binding_mode),
3551 sub.as_ref().map(|x| self.lower_pat(x)),
3554 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3559 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3564 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3565 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3566 let qpath = self.lower_qpath(
3570 ParamMode::Optional,
3571 ImplTraitContext::disallowed(),
3573 self.check_self_struct_ctor_feature(&qpath);
3574 hir::PatKind::TupleStruct(
3576 pats.iter().map(|x| self.lower_pat(x)).collect(),
3580 PatKind::Path(ref qself, ref path) => {
3581 let qpath = self.lower_qpath(
3585 ParamMode::Optional,
3586 ImplTraitContext::disallowed(),
3588 self.check_self_struct_ctor_feature(&qpath);
3589 hir::PatKind::Path(qpath)
3591 PatKind::Struct(ref path, ref fields, etc) => {
3592 let qpath = self.lower_qpath(
3596 ParamMode::Optional,
3597 ImplTraitContext::disallowed(),
3604 node: hir::FieldPat {
3605 id: self.next_id().node_id,
3606 ident: f.node.ident,
3607 pat: self.lower_pat(&f.node.pat),
3608 is_shorthand: f.node.is_shorthand,
3612 hir::PatKind::Struct(qpath, fs, etc)
3614 PatKind::Tuple(ref elts, ddpos) => {
3615 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3617 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3618 PatKind::Ref(ref inner, mutbl) => {
3619 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3621 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3622 P(self.lower_expr(e1)),
3623 P(self.lower_expr(e2)),
3624 self.lower_range_end(end),
3626 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3627 before.iter().map(|x| self.lower_pat(x)).collect(),
3628 slice.as_ref().map(|x| self.lower_pat(x)),
3629 after.iter().map(|x| self.lower_pat(x)).collect(),
3631 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3632 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3635 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3644 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3646 RangeEnd::Included(_) => hir::RangeEnd::Included,
3647 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3651 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3652 self.with_new_scopes(|this| {
3653 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3657 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3662 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3663 let kind = match e.node {
3664 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3665 ExprKind::ObsoleteInPlace(..) => {
3666 self.sess.abort_if_errors();
3667 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3669 ExprKind::Array(ref exprs) => {
3670 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3672 ExprKind::Repeat(ref expr, ref count) => {
3673 let expr = P(self.lower_expr(expr));
3674 let count = self.lower_anon_const(count);
3675 hir::ExprKind::Repeat(expr, count)
3677 ExprKind::Tup(ref elts) => {
3678 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3680 ExprKind::Call(ref f, ref args) => {
3681 let f = P(self.lower_expr(f));
3682 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3684 ExprKind::MethodCall(ref seg, ref args) => {
3685 let hir_seg = self.lower_path_segment(
3688 ParamMode::Optional,
3690 ParenthesizedGenericArgs::Err,
3691 ImplTraitContext::disallowed(),
3694 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3695 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3697 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3698 let binop = self.lower_binop(binop);
3699 let lhs = P(self.lower_expr(lhs));
3700 let rhs = P(self.lower_expr(rhs));
3701 hir::ExprKind::Binary(binop, lhs, rhs)
3703 ExprKind::Unary(op, ref ohs) => {
3704 let op = self.lower_unop(op);
3705 let ohs = P(self.lower_expr(ohs));
3706 hir::ExprKind::Unary(op, ohs)
3708 ExprKind::Lit(ref l) => hir::ExprKind::Lit(P((**l).clone())),
3709 ExprKind::Cast(ref expr, ref ty) => {
3710 let expr = P(self.lower_expr(expr));
3711 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3713 ExprKind::Type(ref expr, ref ty) => {
3714 let expr = P(self.lower_expr(expr));
3715 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3717 ExprKind::AddrOf(m, ref ohs) => {
3718 let m = self.lower_mutability(m);
3719 let ohs = P(self.lower_expr(ohs));
3720 hir::ExprKind::AddrOf(m, ohs)
3722 // More complicated than you might expect because the else branch
3723 // might be `if let`.
3724 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3725 let else_opt = else_opt.as_ref().map(|els| {
3727 ExprKind::IfLet(..) => {
3728 // wrap the if-let expr in a block
3729 let span = els.span;
3730 let els = P(self.lower_expr(els));
3731 let LoweredNodeId { node_id, hir_id } = self.next_id();
3732 let blk = P(hir::Block {
3737 rules: hir::DefaultBlock,
3739 targeted_by_break: false,
3740 recovered: blk.recovered,
3742 P(self.expr_block(blk, ThinVec::new()))
3744 _ => P(self.lower_expr(els)),
3748 let then_blk = self.lower_block(blk, false);
3749 let then_expr = self.expr_block(then_blk, ThinVec::new());
3751 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3753 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3754 hir::ExprKind::While(
3755 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3756 this.lower_block(body, false),
3757 this.lower_label(opt_label),
3760 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3761 hir::ExprKind::Loop(
3762 this.lower_block(body, false),
3763 this.lower_label(opt_label),
3764 hir::LoopSource::Loop,
3767 ExprKind::TryBlock(ref body) => {
3768 self.with_catch_scope(body.id, |this| {
3770 this.allow_internal_unstable(CompilerDesugaringKind::TryBlock, body.span);
3771 let mut block = this.lower_block(body, true).into_inner();
3772 let tail = block.expr.take().map_or_else(
3774 let LoweredNodeId { node_id, hir_id } = this.next_id();
3775 let span = this.sess.source_map().end_point(unstable_span);
3779 node: hir::ExprKind::Tup(hir_vec![]),
3780 attrs: ThinVec::new(),
3784 |x: P<hir::Expr>| x.into_inner(),
3786 block.expr = Some(this.wrap_in_try_constructor(
3787 "from_ok", tail, unstable_span));
3788 hir::ExprKind::Block(P(block), None)
3791 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3792 P(self.lower_expr(expr)),
3793 arms.iter().map(|x| self.lower_arm(x)).collect(),
3794 hir::MatchSource::Normal,
3796 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3797 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3798 this.with_new_scopes(|this| {
3799 let block = this.lower_block(block, false);
3800 this.expr_block(block, ThinVec::new())
3805 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3807 if let IsAsync::Async { closure_id, .. } = asyncness {
3808 let outer_decl = FnDecl {
3809 inputs: decl.inputs.clone(),
3810 output: FunctionRetTy::Default(fn_decl_span),
3813 // We need to lower the declaration outside the new scope, because we
3814 // have to conserve the state of being inside a loop condition for the
3815 // closure argument types.
3816 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3818 self.with_new_scopes(|this| {
3819 // FIXME(cramertj) allow `async` non-`move` closures with
3820 if capture_clause == CaptureBy::Ref &&
3821 !decl.inputs.is_empty()
3827 "`async` non-`move` closures with arguments \
3828 are not currently supported",
3830 .help("consider using `let` statements to manually capture \
3831 variables by reference before entering an \
3832 `async move` closure")
3836 // Transform `async |x: u8| -> X { ... }` into
3837 // `|x: u8| future_from_generator(|| -> X { ... })`
3838 let body_id = this.lower_body(Some(&outer_decl), |this| {
3839 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3842 let async_body = this.make_async_expr(
3843 capture_clause, closure_id, async_ret_ty,
3845 this.with_new_scopes(|this| this.lower_expr(body))
3847 this.expr(fn_decl_span, async_body, ThinVec::new())
3849 hir::ExprKind::Closure(
3850 this.lower_capture_clause(capture_clause),
3858 // Lower outside new scope to preserve `is_in_loop_condition`.
3859 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3861 self.with_new_scopes(|this| {
3862 let mut is_generator = false;
3863 let body_id = this.lower_body(Some(decl), |this| {
3864 let e = this.lower_expr(body);
3865 is_generator = this.is_generator;
3868 let generator_option = if is_generator {
3869 if !decl.inputs.is_empty() {
3874 "generators cannot have explicit arguments"
3876 this.sess.abort_if_errors();
3878 Some(match movability {
3879 Movability::Movable => hir::GeneratorMovability::Movable,
3880 Movability::Static => hir::GeneratorMovability::Static,
3883 if movability == Movability::Static {
3888 "closures cannot be static"
3893 hir::ExprKind::Closure(
3894 this.lower_capture_clause(capture_clause),
3903 ExprKind::Block(ref blk, opt_label) => {
3904 hir::ExprKind::Block(self.lower_block(blk,
3905 opt_label.is_some()),
3906 self.lower_label(opt_label))
3908 ExprKind::Assign(ref el, ref er) => {
3909 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3911 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
3912 self.lower_binop(op),
3913 P(self.lower_expr(el)),
3914 P(self.lower_expr(er)),
3916 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
3917 ExprKind::Index(ref el, ref er) => {
3918 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
3920 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3921 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3922 let id = self.next_id();
3923 let e1 = self.lower_expr(e1);
3924 let e2 = self.lower_expr(e2);
3925 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
3926 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
3927 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3928 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3929 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
3930 hir::ExprKind::Call(new, hir_vec![e1, e2])
3932 ExprKind::Range(ref e1, ref e2, lims) => {
3933 use syntax::ast::RangeLimits::*;
3935 let path = match (e1, e2, lims) {
3936 (&None, &None, HalfOpen) => "RangeFull",
3937 (&Some(..), &None, HalfOpen) => "RangeFrom",
3938 (&None, &Some(..), HalfOpen) => "RangeTo",
3939 (&Some(..), &Some(..), HalfOpen) => "Range",
3940 (&None, &Some(..), Closed) => "RangeToInclusive",
3941 (&Some(..), &Some(..), Closed) => unreachable!(),
3942 (_, &None, Closed) => self.diagnostic()
3943 .span_fatal(e.span, "inclusive range with no end")
3947 let fields = e1.iter()
3948 .map(|e| ("start", e))
3949 .chain(e2.iter().map(|e| ("end", e)))
3951 let expr = P(self.lower_expr(&e));
3952 let ident = Ident::new(Symbol::intern(s), e.span);
3953 self.field(ident, expr, e.span)
3955 .collect::<P<[hir::Field]>>();
3957 let is_unit = fields.is_empty();
3958 let struct_path = ["ops", path];
3959 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
3960 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3962 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3968 hir::ExprKind::Path(struct_path)
3970 hir::ExprKind::Struct(struct_path, fields, None)
3973 attrs: e.attrs.clone(),
3976 ExprKind::Path(ref qself, ref path) => {
3977 let qpath = self.lower_qpath(
3981 ParamMode::Optional,
3982 ImplTraitContext::disallowed(),
3984 self.check_self_struct_ctor_feature(&qpath);
3985 hir::ExprKind::Path(qpath)
3987 ExprKind::Break(opt_label, ref opt_expr) => {
3988 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3991 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3994 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3996 hir::ExprKind::Break(
3998 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
4001 ExprKind::Continue(opt_label) => {
4002 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
4005 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4008 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4011 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
4012 ExprKind::InlineAsm(ref asm) => {
4013 let hir_asm = hir::InlineAsm {
4014 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
4015 outputs: asm.outputs
4017 .map(|out| hir::InlineAsmOutput {
4018 constraint: out.constraint.clone(),
4020 is_indirect: out.is_indirect,
4021 span: out.expr.span,
4024 asm: asm.asm.clone(),
4025 asm_str_style: asm.asm_str_style,
4026 clobbers: asm.clobbers.clone().into(),
4027 volatile: asm.volatile,
4028 alignstack: asm.alignstack,
4029 dialect: asm.dialect,
4032 let outputs = asm.outputs
4034 .map(|out| self.lower_expr(&out.expr))
4036 let inputs = asm.inputs
4038 .map(|&(_, ref input)| self.lower_expr(input))
4040 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
4042 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4047 ParamMode::Optional,
4048 ImplTraitContext::disallowed(),
4050 fields.iter().map(|x| self.lower_field(x)).collect(),
4051 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4053 ExprKind::Paren(ref ex) => {
4054 let mut ex = self.lower_expr(ex);
4055 // include parens in span, but only if it is a super-span.
4056 if e.span.contains(ex.span) {
4059 // merge attributes into the inner expression.
4060 let mut attrs = e.attrs.clone();
4061 attrs.extend::<Vec<_>>(ex.attrs.into());
4066 ExprKind::Yield(ref opt_expr) => {
4067 self.is_generator = true;
4070 .map(|x| self.lower_expr(x))
4072 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
4074 hir::ExprKind::Yield(P(expr))
4077 // Desugar ExprIfLet
4078 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
4079 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4082 // match <sub_expr> {
4084 // _ => [<else_opt> | ()]
4087 let mut arms = vec![];
4089 // `<pat> => <body>`
4091 let body = self.lower_block(body, false);
4092 let body_expr = P(self.expr_block(body, ThinVec::new()));
4093 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4094 arms.push(self.arm(pats, body_expr));
4097 // _ => [<else_opt>|()]
4099 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4100 let wildcard_pattern = self.pat_wild(e.span);
4101 let body = if let Some(else_expr) = wildcard_arm {
4102 P(self.lower_expr(else_expr))
4104 self.expr_tuple(e.span, hir_vec![])
4106 arms.push(self.arm(hir_vec![wildcard_pattern], body));
4109 let contains_else_clause = else_opt.is_some();
4111 let sub_expr = P(self.lower_expr(sub_expr));
4113 hir::ExprKind::Match(
4116 hir::MatchSource::IfLetDesugar {
4117 contains_else_clause,
4122 // Desugar ExprWhileLet
4123 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4124 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4127 // [opt_ident]: loop {
4128 // match <sub_expr> {
4134 // Note that the block AND the condition are evaluated in the loop scope.
4135 // This is done to allow `break` from inside the condition of the loop.
4136 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4138 this.lower_block(body, false),
4139 this.expr_break(e.span, ThinVec::new()),
4140 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4144 // `<pat> => <body>`
4146 let body_expr = P(self.expr_block(body, ThinVec::new()));
4147 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4148 self.arm(pats, body_expr)
4153 let pat_under = self.pat_wild(e.span);
4154 self.arm(hir_vec![pat_under], break_expr)
4157 // `match <sub_expr> { ... }`
4158 let arms = hir_vec![pat_arm, break_arm];
4159 let match_expr = self.expr(
4161 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4165 // `[opt_ident]: loop { ... }`
4166 let loop_block = P(self.block_expr(P(match_expr)));
4167 let loop_expr = hir::ExprKind::Loop(
4169 self.lower_label(opt_label),
4170 hir::LoopSource::WhileLet,
4172 // add attributes to the outer returned expr node
4176 // Desugar ExprForLoop
4177 // From: `[opt_ident]: for <pat> in <head> <body>`
4178 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4182 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4184 // [opt_ident]: loop {
4186 // match ::std::iter::Iterator::next(&mut iter) {
4187 // ::std::option::Option::Some(val) => __next = val,
4188 // ::std::option::Option::None => break
4190 // let <pat> = __next;
4191 // StmtKind::Expr(<body>);
4199 let head = self.lower_expr(head);
4200 let head_sp = head.span;
4201 let desugared_span = self.allow_internal_unstable(
4202 CompilerDesugaringKind::ForLoop,
4206 let iter = self.str_to_ident("iter");
4208 let next_ident = self.str_to_ident("__next");
4209 let next_pat = self.pat_ident_binding_mode(
4212 hir::BindingAnnotation::Mutable,
4215 // `::std::option::Option::Some(val) => next = val`
4217 let val_ident = self.str_to_ident("val");
4218 let val_pat = self.pat_ident(pat.span, val_ident);
4219 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4220 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4221 let assign = P(self.expr(
4223 hir::ExprKind::Assign(next_expr, val_expr),
4226 let some_pat = self.pat_some(pat.span, val_pat);
4227 self.arm(hir_vec![some_pat], assign)
4230 // `::std::option::Option::None => break`
4233 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4234 let pat = self.pat_none(e.span);
4235 self.arm(hir_vec![pat], break_expr)
4239 let iter_pat = self.pat_ident_binding_mode(
4242 hir::BindingAnnotation::Mutable
4245 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4247 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4248 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4249 let next_path = &["iter", "Iterator", "next"];
4250 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4251 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4252 let arms = hir_vec![pat_arm, break_arm];
4256 hir::ExprKind::Match(
4259 hir::MatchSource::ForLoopDesugar
4264 let match_stmt = respan(
4266 hir::StmtKind::Expr(match_expr, self.next_id().node_id)
4269 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4272 let next_let = self.stmt_let_pat(
4276 hir::LocalSource::ForLoopDesugar,
4279 // `let <pat> = __next`
4280 let pat = self.lower_pat(pat);
4281 let pat_let = self.stmt_let_pat(
4285 hir::LocalSource::ForLoopDesugar,
4288 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4289 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4290 let body_stmt = respan(
4292 hir::StmtKind::Expr(body_expr, self.next_id().node_id)
4295 let loop_block = P(self.block_all(
4297 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4301 // `[opt_ident]: loop { ... }`
4302 let loop_expr = hir::ExprKind::Loop(
4304 self.lower_label(opt_label),
4305 hir::LoopSource::ForLoop,
4307 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4308 let loop_expr = P(hir::Expr {
4313 attrs: ThinVec::new(),
4316 // `mut iter => { ... }`
4317 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4319 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4320 let into_iter_expr = {
4321 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4322 let into_iter = P(self.expr_std_path(
4323 head_sp, into_iter_path, None, ThinVec::new()));
4324 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4327 let match_expr = P(self.expr_match(
4331 hir::MatchSource::ForLoopDesugar,
4334 // `{ let _result = ...; _result }`
4335 // underscore prevents an unused_variables lint if the head diverges
4336 let result_ident = self.str_to_ident("_result");
4337 let (let_stmt, let_stmt_binding) =
4338 self.stmt_let(e.span, false, result_ident, match_expr);
4340 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4341 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4342 // add the attributes to the outer returned expr node
4343 return self.expr_block(block, e.attrs.clone());
4346 // Desugar ExprKind::Try
4348 ExprKind::Try(ref sub_expr) => {
4351 // match Try::into_result(<expr>) {
4352 // Ok(val) => #[allow(unreachable_code)] val,
4353 // Err(err) => #[allow(unreachable_code)]
4354 // // If there is an enclosing `catch {...}`
4355 // break 'catch_target Try::from_error(From::from(err)),
4357 // return Try::from_error(From::from(err)),
4361 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4363 // Try::into_result(<expr>)
4366 let sub_expr = self.lower_expr(sub_expr);
4368 let path = &["ops", "Try", "into_result"];
4369 let path = P(self.expr_std_path(
4370 unstable_span, path, None, ThinVec::new()));
4371 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4374 // #[allow(unreachable_code)]
4376 // allow(unreachable_code)
4378 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4379 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4380 let uc_nested = attr::mk_nested_word_item(uc_ident);
4381 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4383 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4385 let attrs = vec![attr];
4387 // Ok(val) => #[allow(unreachable_code)] val,
4389 let val_ident = self.str_to_ident("val");
4390 let val_pat = self.pat_ident(e.span, val_ident);
4391 let val_expr = P(self.expr_ident_with_attrs(
4395 ThinVec::from(attrs.clone()),
4397 let ok_pat = self.pat_ok(e.span, val_pat);
4399 self.arm(hir_vec![ok_pat], val_expr)
4402 // Err(err) => #[allow(unreachable_code)]
4403 // return Try::from_error(From::from(err)),
4405 let err_ident = self.str_to_ident("err");
4406 let err_local = self.pat_ident(e.span, err_ident);
4408 let path = &["convert", "From", "from"];
4409 let from = P(self.expr_std_path(
4410 e.span, path, None, ThinVec::new()));
4411 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4413 self.expr_call(e.span, from, hir_vec![err_expr])
4416 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4417 let thin_attrs = ThinVec::from(attrs);
4418 let catch_scope = self.catch_scopes.last().map(|x| *x);
4419 let ret_expr = if let Some(catch_node) = catch_scope {
4422 hir::ExprKind::Break(
4425 target_id: Ok(catch_node),
4427 Some(from_err_expr),
4432 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4435 let err_pat = self.pat_err(e.span, err_local);
4436 self.arm(hir_vec![err_pat], ret_expr)
4439 hir::ExprKind::Match(
4441 hir_vec![err_arm, ok_arm],
4442 hir::MatchSource::TryDesugar,
4446 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4449 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4456 attrs: e.attrs.clone(),
4460 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
4461 smallvec![match s.node {
4462 StmtKind::Local(ref l) => {
4463 let (l, item_ids) = self.lower_local(l);
4464 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
4466 .map(|item_id| Spanned {
4467 node: hir::StmtKind::Decl(
4469 node: hir::DeclKind::Item(item_id),
4472 self.next_id().node_id,
4478 node: hir::StmtKind::Decl(
4480 node: hir::DeclKind::Local(l),
4483 self.lower_node_id(s.id).node_id,
4489 StmtKind::Item(ref it) => {
4490 // Can only use the ID once.
4491 let mut id = Some(s.id);
4492 return self.lower_item_id(it)
4494 .map(|item_id| Spanned {
4495 node: hir::StmtKind::Decl(
4497 node: hir::DeclKind::Item(item_id),
4501 .map(|id| self.lower_node_id(id).node_id)
4502 .unwrap_or_else(|| self.next_id().node_id),
4508 StmtKind::Expr(ref e) => Spanned {
4509 node: hir::StmtKind::Expr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4512 StmtKind::Semi(ref e) => Spanned {
4513 node: hir::StmtKind::Semi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4516 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4520 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4522 CaptureBy::Value => hir::CaptureByValue,
4523 CaptureBy::Ref => hir::CaptureByRef,
4527 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4528 /// the address space of that item instead of the item currently being
4529 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4530 /// lower a `Visibility` value although we haven't lowered the owning
4531 /// `ImplItem` in question yet.
4532 fn lower_visibility(
4535 explicit_owner: Option<NodeId>,
4536 ) -> hir::Visibility {
4537 let node = match v.node {
4538 VisibilityKind::Public => hir::VisibilityKind::Public,
4539 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4540 VisibilityKind::Restricted { ref path, id } => {
4541 let lowered_id = if let Some(owner) = explicit_owner {
4542 self.lower_node_id_with_owner(id, owner)
4544 self.lower_node_id(id)
4546 let def = self.expect_full_def(id);
4547 hir::VisibilityKind::Restricted {
4548 path: P(self.lower_path_extra(
4551 ParamMode::Explicit,
4554 id: lowered_id.node_id,
4555 hir_id: lowered_id.hir_id,
4558 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4560 respan(v.span, node)
4563 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4565 Defaultness::Default => hir::Defaultness::Default {
4566 has_value: has_value,
4568 Defaultness::Final => {
4570 hir::Defaultness::Final
4575 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4577 BlockCheckMode::Default => hir::DefaultBlock,
4578 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4582 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4584 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4585 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4586 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4587 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4591 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4593 CompilerGenerated => hir::CompilerGenerated,
4594 UserProvided => hir::UserProvided,
4598 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4600 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4601 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4605 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4607 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4608 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4612 // Helper methods for building HIR.
4614 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4623 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4625 id: self.next_id().node_id,
4629 is_shorthand: false,
4633 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4634 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4635 P(self.expr(span, expr_break, attrs))
4642 args: hir::HirVec<hir::Expr>,
4644 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4647 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4648 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4651 fn expr_ident_with_attrs(
4656 attrs: ThinVec<Attribute>,
4658 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4662 def: Def::Local(binding),
4663 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4667 self.expr(span, expr_path, attrs)
4670 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4671 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4677 components: &[&str],
4678 params: Option<P<hir::GenericArgs>>,
4679 attrs: ThinVec<Attribute>,
4681 let path = self.std_path(span, components, params, true);
4684 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4693 arms: hir::HirVec<hir::Arm>,
4694 source: hir::MatchSource,
4696 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4699 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4700 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4703 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4704 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4707 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4708 let LoweredNodeId { node_id, hir_id } = self.next_id();
4721 ex: Option<P<hir::Expr>>,
4723 source: hir::LocalSource,
4725 let LoweredNodeId { node_id, hir_id } = self.next_id();
4727 let local = P(hir::Local {
4734 attrs: ThinVec::new(),
4737 let decl = respan(sp, hir::DeclKind::Local(local));
4738 respan(sp, hir::StmtKind::Decl(P(decl), self.next_id().node_id))
4747 ) -> (hir::Stmt, NodeId) {
4748 let pat = if mutbl {
4749 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4751 self.pat_ident(sp, ident)
4753 let pat_id = pat.id;
4755 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4760 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4761 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4767 stmts: hir::HirVec<hir::Stmt>,
4768 expr: Option<P<hir::Expr>>,
4770 let LoweredNodeId { node_id, hir_id } = self.next_id();
4777 rules: hir::DefaultBlock,
4779 targeted_by_break: false,
4784 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4785 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4788 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4789 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4792 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4793 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4796 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4797 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4803 components: &[&str],
4804 subpats: hir::HirVec<P<hir::Pat>>,
4806 let path = self.std_path(span, components, None, true);
4807 let qpath = hir::QPath::Resolved(None, P(path));
4808 let pt = if subpats.is_empty() {
4809 hir::PatKind::Path(qpath)
4811 hir::PatKind::TupleStruct(qpath, subpats, None)
4816 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4817 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4820 fn pat_ident_binding_mode(
4824 bm: hir::BindingAnnotation,
4826 let LoweredNodeId { node_id, hir_id } = self.next_id();
4831 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4836 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4837 self.pat(span, hir::PatKind::Wild)
4840 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4841 let LoweredNodeId { node_id, hir_id } = self.next_id();
4850 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4851 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4852 /// The path is also resolved according to `is_value`.
4856 components: &[&str],
4857 params: Option<P<hir::GenericArgs>>,
4860 let mut path = self.resolver
4861 .resolve_str_path(span, self.crate_root, components, is_value);
4862 path.segments.last_mut().unwrap().args = params;
4865 for seg in path.segments.iter_mut() {
4866 if let Some(id) = seg.id {
4867 seg.id = Some(self.lower_node_id(id).node_id);
4873 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4875 let node = match qpath {
4876 hir::QPath::Resolved(None, path) => {
4877 // Turn trait object paths into `TyKind::TraitObject` instead.
4878 if let Def::Trait(_) = path.def {
4879 let principal = hir::PolyTraitRef {
4880 bound_generic_params: hir::HirVec::new(),
4881 trait_ref: hir::TraitRef {
4882 path: path.and_then(|path| path),
4884 hir_ref_id: id.hir_id,
4889 // The original ID is taken by the `PolyTraitRef`,
4890 // so the `Ty` itself needs a different one.
4891 id = self.next_id();
4892 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4894 hir::TyKind::Path(hir::QPath::Resolved(None, path))
4897 _ => hir::TyKind::Path(qpath),
4907 /// Invoked to create the lifetime argument for a type `&T`
4908 /// with no explicit lifetime.
4909 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4910 match self.anonymous_lifetime_mode {
4911 // Intercept when we are in an impl header and introduce an in-band lifetime.
4912 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4914 AnonymousLifetimeMode::CreateParameter => {
4915 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4917 id: self.next_id().node_id,
4919 name: hir::LifetimeName::Param(fresh_name),
4923 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
4925 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4929 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
4930 /// return a "error lifetime".
4931 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
4932 let (id, msg, label) = match id {
4933 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
4936 self.next_id().node_id,
4937 "`&` without an explicit lifetime name cannot be used here",
4938 "explicit lifetime name needed here",
4942 let mut err = struct_span_err!(
4949 err.span_label(span, label);
4952 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
4955 /// Invoked to create the lifetime argument(s) for a path like
4956 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4957 /// sorts of cases are deprecated. This may therefore report a warning or an
4958 /// error, depending on the mode.
4959 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4960 match self.anonymous_lifetime_mode {
4961 // NB. We intentionally ignore the create-parameter mode here
4962 // and instead "pass through" to resolve-lifetimes, which will then
4963 // report an error. This is because we don't want to support
4964 // impl elision for deprecated forms like
4966 // impl Foo for std::cell::Ref<u32> // note lack of '_
4967 AnonymousLifetimeMode::CreateParameter => {}
4969 AnonymousLifetimeMode::ReportError => {
4971 .map(|_| self.new_error_lifetime(None, span))
4975 // This is the normal case.
4976 AnonymousLifetimeMode::PassThrough => {}
4980 .map(|_| self.new_implicit_lifetime(span))
4984 /// Invoked to create the lifetime argument(s) for an elided trait object
4985 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4986 /// when the bound is written, even if it is written with `'_` like in
4987 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4988 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4989 match self.anonymous_lifetime_mode {
4990 // NB. We intentionally ignore the create-parameter mode here.
4991 // and instead "pass through" to resolve-lifetimes, which will apply
4992 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4993 // do not act like other elided lifetimes. In other words, given this:
4995 // impl Foo for Box<dyn Debug>
4997 // we do not introduce a fresh `'_` to serve as the bound, but instead
4998 // ultimately translate to the equivalent of:
5000 // impl Foo for Box<dyn Debug + 'static>
5002 // `resolve_lifetime` has the code to make that happen.
5003 AnonymousLifetimeMode::CreateParameter => {}
5005 AnonymousLifetimeMode::ReportError => {
5006 // ReportError applies to explicit use of `'_`.
5009 // This is the normal case.
5010 AnonymousLifetimeMode::PassThrough => {}
5013 self.new_implicit_lifetime(span)
5016 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
5018 id: self.next_id().node_id,
5020 name: hir::LifetimeName::Implicit,
5024 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
5025 self.sess.buffer_lint_with_diagnostic(
5026 builtin::BARE_TRAIT_OBJECTS,
5029 "trait objects without an explicit `dyn` are deprecated",
5030 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
5034 fn wrap_in_try_constructor(
5036 method: &'static str,
5038 unstable_span: Span,
5040 let path = &["ops", "Try", method];
5041 let from_err = P(self.expr_std_path(unstable_span, path, None,
5043 P(self.expr_call(e.span, from_err, hir_vec![e]))
5046 fn check_self_struct_ctor_feature(&self, qp: &hir::QPath) {
5047 if let hir::QPath::Resolved(_, ref p) = qp {
5048 if p.segments.len() == 1 &&
5049 p.segments[0].ident.name == keywords::SelfType.name() &&
5050 !self.sess.features_untracked().self_struct_ctor {
5051 emit_feature_err(&self.sess.parse_sess, "self_struct_ctor",
5052 p.span, GateIssue::Language,
5053 "`Self` struct constructors are unstable");
5059 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5060 // Sorting by span ensures that we get things in order within a
5061 // file, and also puts the files in a sensible order.
5062 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5063 body_ids.sort_by_key(|b| bodies[b].value.span);