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 hir path generated by the lowerer when expanding `for`, `if let`, etc.
147 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
149 /// Obtain the resolution for a node id
150 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
152 /// Obtain the possible resolutions for the given `use` statement.
153 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
155 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
156 /// This should only return `None` during testing.
157 fn definitions(&mut self) -> &mut Definitions;
159 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
160 /// it based on `is_value`.
164 crate_root: Option<&str>,
166 params: Option<P<hir::GenericArgs>>,
172 enum ImplTraitContext<'a> {
173 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
174 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
175 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
177 /// Newly generated parameters should be inserted into the given `Vec`.
178 Universal(&'a mut Vec<hir::GenericParam>),
180 /// Treat `impl Trait` as shorthand for a new existential parameter.
181 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
182 /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
184 /// We optionally store a `DefId` for the parent item here so we can look up necessary
185 /// information later. It is `None` when no information about the context should be stored,
186 /// e.g. for consts and statics.
187 Existential(Option<DefId>),
189 /// `impl Trait` is not accepted in this position.
190 Disallowed(ImplTraitPosition),
193 /// Position in which `impl Trait` is disallowed. Used for error reporting.
194 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
195 enum ImplTraitPosition {
200 impl<'a> ImplTraitContext<'a> {
202 fn disallowed() -> Self {
203 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
206 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
207 use self::ImplTraitContext::*;
209 Universal(params) => Universal(params),
210 Existential(did) => Existential(*did),
211 Disallowed(pos) => Disallowed(*pos),
218 cstore: &dyn CrateStore,
219 dep_graph: &DepGraph,
221 resolver: &mut dyn Resolver,
223 // We're constructing the HIR here; we don't care what we will
224 // read, since we haven't even constructed the *input* to
226 dep_graph.assert_ignored();
229 crate_root: std_inject::injected_crate_name(),
233 items: BTreeMap::new(),
234 trait_items: BTreeMap::new(),
235 impl_items: BTreeMap::new(),
236 bodies: BTreeMap::new(),
237 trait_impls: BTreeMap::new(),
238 trait_auto_impl: BTreeMap::new(),
239 exported_macros: Vec::new(),
240 catch_scopes: Vec::new(),
241 loop_scopes: Vec::new(),
242 is_in_loop_condition: false,
243 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
244 type_def_lifetime_params: DefIdMap(),
245 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
246 item_local_id_counters: NodeMap(),
247 node_id_to_hir_id: IndexVec::new(),
249 is_in_trait_impl: false,
250 lifetimes_to_define: Vec::new(),
251 is_collecting_in_band_lifetimes: false,
252 in_scope_lifetimes: Vec::new(),
256 #[derive(Copy, Clone, PartialEq)]
258 /// Any path in a type context.
260 /// The `module::Type` in `module::Type::method` in an expression.
265 struct LoweredNodeId {
270 enum ParenthesizedGenericArgs {
276 /// What to do when we encounter an **anonymous** lifetime
277 /// reference. Anonymous lifetime references come in two flavors. You
278 /// have implicit, or fully elided, references to lifetimes, like the
279 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
280 /// or `Ref<'_, T>`. These often behave the same, but not always:
282 /// - certain usages of implicit references are deprecated, like
283 /// `Ref<T>`, and we sometimes just give hard errors in those cases
285 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
286 /// the same as `Box<dyn Foo + '_>`.
288 /// We describe the effects of the various modes in terms of three cases:
290 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
291 /// of a `&` (e.g., the missing lifetime in something like `&T`)
292 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
293 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
294 /// elided bounds follow special rules. Note that this only covers
295 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
296 /// '_>` is a case of "modern" elision.
297 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
298 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
299 /// non-deprecated equivalent.
301 /// Currently, the handling of lifetime elision is somewhat spread out
302 /// between HIR lowering and -- as described below -- the
303 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
304 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
305 /// everything into HIR lowering.
306 #[derive(Copy, Clone)]
307 enum AnonymousLifetimeMode {
308 /// For **Modern** cases, create a new anonymous region parameter
309 /// and reference that.
311 /// For **Dyn Bound** cases, pass responsibility to
312 /// `resolve_lifetime` code.
314 /// For **Deprecated** cases, report an error.
317 /// Give a hard error when either `&` or `'_` is written. Used to
318 /// rule out things like `where T: Foo<'_>`. Does not imply an
319 /// error on default object bounds (e.g., `Box<dyn Foo>`).
322 /// Pass responsibility to `resolve_lifetime` code for all cases.
326 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[hir::ItemId; 1]> }
328 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
329 fn visit_ty(&mut self, ty: &'a Ty) {
335 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
338 visit::walk_ty(self, ty);
341 fn visit_path_segment(
344 path_segment: &'v PathSegment,
346 if let Some(ref p) = path_segment.args {
347 if let GenericArgs::Parenthesized(_) = **p {
351 visit::walk_path_segment(self, path_span, path_segment)
355 impl<'a> LoweringContext<'a> {
356 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
357 /// Full-crate AST visitor that inserts into a fresh
358 /// `LoweringContext` any information that may be
359 /// needed from arbitrary locations in the crate.
360 /// E.g. The number of lifetime generic parameters
361 /// declared for every type and trait definition.
362 struct MiscCollector<'lcx, 'interner: 'lcx> {
363 lctx: &'lcx mut LoweringContext<'interner>,
366 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
367 fn visit_item(&mut self, item: &'lcx Item) {
368 self.lctx.allocate_hir_id_counter(item.id, item);
371 ItemKind::Struct(_, ref generics)
372 | ItemKind::Union(_, ref generics)
373 | ItemKind::Enum(_, ref generics)
374 | ItemKind::Ty(_, ref generics)
375 | ItemKind::Existential(_, ref generics)
376 | ItemKind::Trait(_, _, ref generics, ..) => {
377 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
381 .filter(|param| match param.kind {
382 ast::GenericParamKind::Lifetime { .. } => true,
386 self.lctx.type_def_lifetime_params.insert(def_id, count);
390 visit::walk_item(self, item);
393 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
394 self.lctx.allocate_hir_id_counter(item.id, item);
395 visit::walk_trait_item(self, item);
398 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
399 self.lctx.allocate_hir_id_counter(item.id, item);
400 visit::walk_impl_item(self, item);
404 struct ItemLowerer<'lcx, 'interner: 'lcx> {
405 lctx: &'lcx mut LoweringContext<'interner>,
408 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
409 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
411 F: FnOnce(&mut Self),
413 let old = self.lctx.is_in_trait_impl;
414 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
420 self.lctx.is_in_trait_impl = old;
424 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
425 fn visit_item(&mut self, item: &'lcx Item) {
426 let mut item_lowered = true;
427 self.lctx.with_hir_id_owner(item.id, |lctx| {
428 if let Some(hir_item) = lctx.lower_item(item) {
429 lctx.items.insert(item.id, hir_item);
431 item_lowered = false;
436 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
437 hir::ItemKind::Impl(_, _, _, ref generics, ..)
438 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
439 generics.params.clone()
444 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
445 let this = &mut ItemLowerer { lctx: this };
446 if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
447 this.with_trait_impl_ref(opt_trait_ref, |this| {
448 visit::walk_item(this, item)
451 visit::walk_item(this, item);
457 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
458 self.lctx.with_hir_id_owner(item.id, |lctx| {
459 let id = hir::TraitItemId { node_id: item.id };
460 let hir_item = lctx.lower_trait_item(item);
461 lctx.trait_items.insert(id, hir_item);
464 visit::walk_trait_item(self, item);
467 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
468 self.lctx.with_hir_id_owner(item.id, |lctx| {
469 let id = hir::ImplItemId { node_id: item.id };
470 let hir_item = lctx.lower_impl_item(item);
471 lctx.impl_items.insert(id, hir_item);
473 visit::walk_impl_item(self, item);
477 self.lower_node_id(CRATE_NODE_ID);
478 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
480 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
481 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
483 let module = self.lower_mod(&c.module);
484 let attrs = self.lower_attrs(&c.attrs);
485 let body_ids = body_ids(&self.bodies);
489 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
495 exported_macros: hir::HirVec::from(self.exported_macros),
497 trait_items: self.trait_items,
498 impl_items: self.impl_items,
501 trait_impls: self.trait_impls,
502 trait_auto_impl: self.trait_auto_impl,
506 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
507 if self.item_local_id_counters.insert(owner, 0).is_some() {
509 "Tried to allocate item_local_id_counter for {:?} twice",
513 // Always allocate the first HirId for the owner itself
514 self.lower_node_id_with_owner(owner, owner)
517 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
519 F: FnOnce(&mut Self) -> hir::HirId,
521 if ast_node_id == DUMMY_NODE_ID {
522 return LoweredNodeId {
523 node_id: DUMMY_NODE_ID,
524 hir_id: hir::DUMMY_HIR_ID,
528 let min_size = ast_node_id.as_usize() + 1;
530 if min_size > self.node_id_to_hir_id.len() {
531 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
534 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
536 if existing_hir_id == hir::DUMMY_HIR_ID {
537 // Generate a new HirId
538 let hir_id = alloc_hir_id(self);
539 self.node_id_to_hir_id[ast_node_id] = hir_id;
541 node_id: ast_node_id,
546 node_id: ast_node_id,
547 hir_id: existing_hir_id,
552 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
554 F: FnOnce(&mut Self) -> T,
556 let counter = self.item_local_id_counters
557 .insert(owner, HIR_ID_COUNTER_LOCKED)
558 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
559 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
560 self.current_hir_id_owner.push((def_index, counter));
562 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
564 debug_assert!(def_index == new_def_index);
565 debug_assert!(new_counter >= counter);
567 let prev = self.item_local_id_counters
568 .insert(owner, new_counter)
570 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
574 /// This method allocates a new HirId for the given NodeId and stores it in
575 /// the LoweringContext's NodeId => HirId map.
576 /// Take care not to call this method if the resulting HirId is then not
577 /// actually used in the HIR, as that would trigger an assertion in the
578 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
579 /// properly. Calling the method twice with the same NodeId is fine though.
580 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
581 self.lower_node_id_generic(ast_node_id, |this| {
582 let &mut (def_index, ref mut local_id_counter) =
583 this.current_hir_id_owner.last_mut().unwrap();
584 let local_id = *local_id_counter;
585 *local_id_counter += 1;
588 local_id: hir::ItemLocalId(local_id),
593 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
594 self.lower_node_id_generic(ast_node_id, |this| {
595 let local_id_counter = this
596 .item_local_id_counters
598 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
599 let local_id = *local_id_counter;
601 // We want to be sure not to modify the counter in the map while it
602 // is also on the stack. Otherwise we'll get lost updates when writing
603 // back from the stack to the map.
604 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
606 *local_id_counter += 1;
610 .opt_def_index(owner)
611 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
612 that do not belong to the current owner");
616 local_id: hir::ItemLocalId(local_id),
621 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
622 let body = hir::Body {
623 arguments: decl.map_or(hir_vec![], |decl| {
624 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
626 is_generator: self.is_generator,
630 self.bodies.insert(id, body);
634 fn next_id(&mut self) -> LoweredNodeId {
635 self.lower_node_id(self.sess.next_node_id())
638 fn expect_full_def(&mut self, id: NodeId) -> Def {
639 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
640 if pr.unresolved_segments() != 0 {
641 bug!("path not fully resolved: {:?}", pr);
647 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Def> {
648 self.resolver.get_import(id).present_items().map(|pr| {
649 if pr.unresolved_segments() != 0 {
650 bug!("path not fully resolved: {:?}", pr);
656 fn diagnostic(&self) -> &errors::Handler {
657 self.sess.diagnostic()
660 fn str_to_ident(&self, s: &'static str) -> Ident {
661 Ident::with_empty_ctxt(Symbol::gensym(s))
664 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
665 let mark = Mark::fresh(Mark::root());
666 mark.set_expn_info(source_map::ExpnInfo {
668 def_site: Some(span),
669 format: source_map::CompilerDesugaring(reason),
670 allow_internal_unstable: true,
671 allow_internal_unsafe: false,
672 local_inner_macros: false,
673 edition: source_map::hygiene::default_edition(),
675 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
678 fn with_anonymous_lifetime_mode<R>(
680 anonymous_lifetime_mode: AnonymousLifetimeMode,
681 op: impl FnOnce(&mut Self) -> R,
683 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
684 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
685 let result = op(self);
686 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
690 /// Creates a new hir::GenericParam for every new lifetime and
691 /// type parameter encountered while evaluating `f`. Definitions
692 /// are created with the parent provided. If no `parent_id` is
693 /// provided, no definitions will be returned.
695 /// Presuming that in-band lifetimes are enabled, then
696 /// `self.anonymous_lifetime_mode` will be updated to match the
697 /// argument while `f` is running (and restored afterwards).
698 fn collect_in_band_defs<T, F>(
701 anonymous_lifetime_mode: AnonymousLifetimeMode,
703 ) -> (Vec<hir::GenericParam>, T)
705 F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
707 assert!(!self.is_collecting_in_band_lifetimes);
708 assert!(self.lifetimes_to_define.is_empty());
709 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
711 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
712 self.is_collecting_in_band_lifetimes = true;
714 let (in_band_ty_params, res) = f(self);
716 self.is_collecting_in_band_lifetimes = false;
717 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
719 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
721 let params = lifetimes_to_define
723 .map(|(span, hir_name)| {
724 let def_node_id = self.next_id().node_id;
726 // Get the name we'll use to make the def-path. Note
727 // that collisions are ok here and this shouldn't
728 // really show up for end-user.
729 let (str_name, kind) = match hir_name {
730 ParamName::Plain(ident) => (
731 ident.as_interned_str(),
732 hir::LifetimeParamKind::InBand,
734 ParamName::Fresh(_) => (
735 keywords::UnderscoreLifetime.name().as_interned_str(),
736 hir::LifetimeParamKind::Elided,
738 ParamName::Error => (
739 keywords::UnderscoreLifetime.name().as_interned_str(),
740 hir::LifetimeParamKind::Error,
744 // Add a definition for the in-band lifetime def
745 self.resolver.definitions().create_def_with_parent(
748 DefPathData::LifetimeParam(str_name),
749 DefIndexAddressSpace::High,
760 pure_wrt_drop: false,
761 kind: hir::GenericParamKind::Lifetime { kind }
764 .chain(in_band_ty_params.into_iter())
770 /// When there is a reference to some lifetime `'a`, and in-band
771 /// lifetimes are enabled, then we want to push that lifetime into
772 /// the vector of names to define later. In that case, it will get
773 /// added to the appropriate generics.
774 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
775 if !self.is_collecting_in_band_lifetimes {
779 if !self.sess.features_untracked().in_band_lifetimes {
783 if self.in_scope_lifetimes.contains(&ident.modern()) {
787 let hir_name = ParamName::Plain(ident);
789 if self.lifetimes_to_define.iter()
790 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
794 self.lifetimes_to_define.push((ident.span, hir_name));
797 /// When we have either an elided or `'_` lifetime in an impl
798 /// header, we convert it to an in-band lifetime.
799 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
800 assert!(self.is_collecting_in_band_lifetimes);
801 let index = self.lifetimes_to_define.len();
802 let hir_name = ParamName::Fresh(index);
803 self.lifetimes_to_define.push((span, hir_name));
807 // Evaluates `f` with the lifetimes in `params` in-scope.
808 // This is used to track which lifetimes have already been defined, and
809 // which are new in-band lifetimes that need to have a definition created
811 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
813 F: FnOnce(&mut LoweringContext<'_>) -> T,
815 let old_len = self.in_scope_lifetimes.len();
816 let lt_def_names = params.iter().filter_map(|param| match param.kind {
817 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
820 self.in_scope_lifetimes.extend(lt_def_names);
824 self.in_scope_lifetimes.truncate(old_len);
828 // Same as the method above, but accepts `hir::GenericParam`s
829 // instead of `ast::GenericParam`s.
830 // This should only be used with generics that have already had their
831 // in-band lifetimes added. In practice, this means that this function is
832 // only used when lowering a child item of a trait or impl.
833 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
834 params: &HirVec<hir::GenericParam>,
837 F: FnOnce(&mut LoweringContext<'_>) -> T,
839 let old_len = self.in_scope_lifetimes.len();
840 let lt_def_names = params.iter().filter_map(|param| match param.kind {
841 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
844 self.in_scope_lifetimes.extend(lt_def_names);
848 self.in_scope_lifetimes.truncate(old_len);
852 /// Appends in-band lifetime defs and argument-position `impl
853 /// Trait` defs to the existing set of generics.
855 /// Presuming that in-band lifetimes are enabled, then
856 /// `self.anonymous_lifetime_mode` will be updated to match the
857 /// argument while `f` is running (and restored afterwards).
858 fn add_in_band_defs<F, T>(
862 anonymous_lifetime_mode: AnonymousLifetimeMode,
864 ) -> (hir::Generics, T)
866 F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
868 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
871 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
872 let mut params = Vec::new();
873 let generics = this.lower_generics(
875 ImplTraitContext::Universal(&mut params),
877 let res = f(this, &mut params);
878 (params, (generics, res))
883 lowered_generics.params = lowered_generics
890 (lowered_generics, res)
893 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
895 F: FnOnce(&mut LoweringContext<'_>) -> T,
897 let len = self.catch_scopes.len();
898 self.catch_scopes.push(catch_id);
900 let result = f(self);
903 self.catch_scopes.len(),
904 "catch scopes should be added and removed in stack order"
907 self.catch_scopes.pop().unwrap();
914 capture_clause: CaptureBy,
915 closure_node_id: NodeId,
917 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
919 let prev_is_generator = mem::replace(&mut self.is_generator, true);
920 let body_expr = body(self);
921 let span = body_expr.span;
922 let output = match ret_ty {
923 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
924 None => FunctionRetTy::Default(span),
931 let body_id = self.record_body(body_expr, Some(&decl));
932 self.is_generator = prev_is_generator;
934 let capture_clause = self.lower_capture_clause(capture_clause);
935 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
936 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
937 let generator = hir::Expr {
939 hir_id: closure_hir_id,
940 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
941 Some(hir::GeneratorMovability::Static)),
943 attrs: ThinVec::new(),
946 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
947 let gen_future = self.expr_std_path(
948 unstable_span, &["future", "from_generator"], None, ThinVec::new());
949 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
952 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
954 F: FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
956 let prev = mem::replace(&mut self.is_generator, false);
957 let result = f(self);
958 let r = self.record_body(result, decl);
959 self.is_generator = prev;
963 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
965 F: FnOnce(&mut LoweringContext<'_>) -> T,
967 // We're no longer in the base loop's condition; we're in another loop.
968 let was_in_loop_condition = self.is_in_loop_condition;
969 self.is_in_loop_condition = false;
971 let len = self.loop_scopes.len();
972 self.loop_scopes.push(loop_id);
974 let result = f(self);
977 self.loop_scopes.len(),
978 "Loop scopes should be added and removed in stack order"
981 self.loop_scopes.pop().unwrap();
983 self.is_in_loop_condition = was_in_loop_condition;
988 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
990 F: FnOnce(&mut LoweringContext<'_>) -> T,
992 let was_in_loop_condition = self.is_in_loop_condition;
993 self.is_in_loop_condition = true;
995 let result = f(self);
997 self.is_in_loop_condition = was_in_loop_condition;
1002 fn with_new_scopes<T, F>(&mut self, f: F) -> T
1004 F: FnOnce(&mut LoweringContext<'_>) -> T,
1006 let was_in_loop_condition = self.is_in_loop_condition;
1007 self.is_in_loop_condition = false;
1009 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
1010 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
1012 self.catch_scopes = catch_scopes;
1013 self.loop_scopes = loop_scopes;
1015 self.is_in_loop_condition = was_in_loop_condition;
1020 fn def_key(&mut self, id: DefId) -> DefKey {
1022 self.resolver.definitions().def_key(id.index)
1024 self.cstore.def_key(id)
1028 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1029 label.map(|label| hir::Label {
1034 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1035 let target_id = match destination {
1037 if let Def::Label(loop_id) = self.expect_full_def(id) {
1038 Ok(self.lower_node_id(loop_id).node_id)
1040 Err(hir::LoopIdError::UnresolvedLabel)
1047 .map(|id| Ok(self.lower_node_id(id).node_id))
1048 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1053 label: self.lower_label(destination.map(|(_, label)| label)),
1058 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1061 .map(|a| self.lower_attr(a))
1062 .collect::<Vec<_>>()
1066 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1070 path: attr.path.clone(),
1071 tokens: self.lower_token_stream(attr.tokens.clone()),
1072 is_sugared_doc: attr.is_sugared_doc,
1077 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1080 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1084 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1086 TokenTree::Token(span, token) => self.lower_token(token, span),
1087 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1090 delim: delimited.delim,
1091 tts: self.lower_token_stream(delimited.tts.into()).into(),
1097 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1099 Token::Interpolated(_) => {}
1100 other => return TokenTree::Token(span, other).into(),
1103 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1104 self.lower_token_stream(tts)
1107 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1109 attrs: self.lower_attrs(&arm.attrs),
1110 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1111 guard: match arm.guard {
1112 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1115 body: P(self.lower_expr(&arm.body)),
1119 fn lower_ty_binding(&mut self, b: &TypeBinding,
1120 itctx: ImplTraitContext<'_>) -> hir::TypeBinding {
1122 id: self.lower_node_id(b.id).node_id,
1124 ty: self.lower_ty(&b.ty, itctx),
1129 fn lower_generic_arg(&mut self,
1130 arg: &ast::GenericArg,
1131 itctx: ImplTraitContext<'_>)
1132 -> hir::GenericArg {
1134 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1135 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1139 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1140 P(self.lower_ty_direct(t, itctx))
1143 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1144 let kind = match t.node {
1145 TyKind::Infer => hir::TyKind::Infer,
1146 TyKind::Err => hir::TyKind::Err,
1147 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1148 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1149 TyKind::Rptr(ref region, ref mt) => {
1150 let span = t.span.shrink_to_lo();
1151 let lifetime = match *region {
1152 Some(ref lt) => self.lower_lifetime(lt),
1153 None => self.elided_ref_lifetime(span),
1155 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1157 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1160 this.with_anonymous_lifetime_mode(
1161 AnonymousLifetimeMode::PassThrough,
1163 hir::TyKind::BareFn(P(hir::BareFnTy {
1164 generic_params: this.lower_generic_params(
1167 ImplTraitContext::disallowed(),
1169 unsafety: this.lower_unsafety(f.unsafety),
1171 decl: this.lower_fn_decl(&f.decl, None, false, None),
1172 arg_names: this.lower_fn_args_to_names(&f.decl),
1178 TyKind::Never => hir::TyKind::Never,
1179 TyKind::Tup(ref tys) => {
1180 hir::TyKind::Tup(tys.iter().map(|ty| {
1181 self.lower_ty_direct(ty, itctx.reborrow())
1184 TyKind::Paren(ref ty) => {
1185 return self.lower_ty_direct(ty, itctx);
1187 TyKind::Path(ref qself, ref path) => {
1188 let id = self.lower_node_id(t.id);
1189 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1190 let ty = self.ty_path(id, t.span, qpath);
1191 if let hir::TyKind::TraitObject(..) = ty.node {
1192 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1196 TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1199 def: self.expect_full_def(t.id),
1200 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1204 TyKind::Array(ref ty, ref length) => {
1205 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1207 TyKind::Typeof(ref expr) => {
1208 hir::TyKind::Typeof(self.lower_anon_const(expr))
1210 TyKind::TraitObject(ref bounds, kind) => {
1211 let mut lifetime_bound = None;
1214 .filter_map(|bound| match *bound {
1215 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1216 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1218 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1219 GenericBound::Outlives(ref lifetime) => {
1220 if lifetime_bound.is_none() {
1221 lifetime_bound = Some(self.lower_lifetime(lifetime));
1227 let lifetime_bound =
1228 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1229 if kind != TraitObjectSyntax::Dyn {
1230 self.maybe_lint_bare_trait(t.span, t.id, false);
1232 hir::TyKind::TraitObject(bounds, lifetime_bound)
1234 TyKind::ImplTrait(def_node_id, ref bounds) => {
1237 ImplTraitContext::Existential(fn_def_id) => {
1238 self.lower_existential_impl_trait(
1239 span, fn_def_id, def_node_id,
1240 |this| this.lower_param_bounds(bounds, itctx),
1243 ImplTraitContext::Universal(in_band_ty_params) => {
1244 self.lower_node_id(def_node_id);
1245 // Add a definition for the in-band Param
1246 let def_index = self
1249 .opt_def_index(def_node_id)
1252 let hir_bounds = self.lower_param_bounds(
1254 ImplTraitContext::Universal(in_band_ty_params),
1256 // Set the name to `impl Bound1 + Bound2`
1257 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1258 in_band_ty_params.push(hir::GenericParam {
1260 name: ParamName::Plain(ident),
1261 pure_wrt_drop: false,
1265 kind: hir::GenericParamKind::Type {
1267 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1271 hir::TyKind::Path(hir::QPath::Resolved(
1275 def: Def::TyParam(DefId::local(def_index)),
1276 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1280 ImplTraitContext::Disallowed(pos) => {
1281 let allowed_in = if self.sess.features_untracked()
1282 .impl_trait_in_bindings {
1283 "bindings or function and inherent method return types"
1285 "function and inherent method return types"
1287 let mut err = struct_span_err!(
1291 "`impl Trait` not allowed outside of {}",
1294 if pos == ImplTraitPosition::Binding &&
1295 nightly_options::is_nightly_build() {
1297 "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1305 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1308 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1317 fn lower_existential_impl_trait(
1320 fn_def_id: Option<DefId>,
1321 exist_ty_node_id: NodeId,
1322 lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1324 // Make sure we know that some funky desugaring has been going on here.
1325 // This is a first: there is code in other places like for loop
1326 // desugaring that explicitly states that we don't want to track that.
1327 // Not tracking it makes lints in rustc and clippy very fragile as
1328 // frequently opened issues show.
1329 let exist_ty_span = self.allow_internal_unstable(
1330 CompilerDesugaringKind::ExistentialReturnType,
1334 let exist_ty_def_index = self
1337 .opt_def_index(exist_ty_node_id)
1340 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1342 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1344 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1350 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1351 let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1352 generics: hir::Generics {
1353 params: lifetime_defs,
1354 where_clause: hir::WhereClause {
1355 id: lctx.next_id().node_id,
1356 predicates: Vec::new().into(),
1361 impl_trait_fn: fn_def_id,
1363 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1364 // Generate an `existential type Foo: Trait;` declaration
1365 trace!("creating existential type with id {:#?}", exist_ty_id);
1367 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1368 let exist_ty_item = hir::Item {
1369 id: exist_ty_id.node_id,
1370 hir_id: exist_ty_id.hir_id,
1371 name: keywords::Invalid.name(),
1372 attrs: Default::default(),
1373 node: exist_ty_item_kind,
1374 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1375 span: exist_ty_span,
1378 // Insert the item into the global list. This usually happens
1379 // automatically for all AST items. But this existential type item
1380 // does not actually exist in the AST.
1381 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1383 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1384 hir::TyKind::Def(hir::ItemId { id: exist_ty_id.node_id }, lifetimes)
1388 fn lifetimes_from_impl_trait_bounds(
1390 exist_ty_id: NodeId,
1391 parent_index: DefIndex,
1392 bounds: &hir::GenericBounds,
1393 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1394 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1395 // appear in the bounds, excluding lifetimes that are created within the bounds.
1396 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1397 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1398 context: &'r mut LoweringContext<'a>,
1400 exist_ty_id: NodeId,
1401 collect_elided_lifetimes: bool,
1402 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1403 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1404 output_lifetimes: Vec<hir::GenericArg>,
1405 output_lifetime_params: Vec<hir::GenericParam>,
1408 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1409 fn nested_visit_map<'this>(
1411 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1412 hir::intravisit::NestedVisitorMap::None
1415 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1416 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1417 if parameters.parenthesized {
1418 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1419 self.collect_elided_lifetimes = false;
1420 hir::intravisit::walk_generic_args(self, span, parameters);
1421 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1423 hir::intravisit::walk_generic_args(self, span, parameters);
1427 fn visit_ty(&mut self, t: &'v hir::Ty) {
1428 // Don't collect elided lifetimes used inside of `fn()` syntax
1429 if let hir::TyKind::BareFn(_) = t.node {
1430 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1431 self.collect_elided_lifetimes = false;
1433 // Record the "stack height" of `for<'a>` lifetime bindings
1434 // to be able to later fully undo their introduction.
1435 let old_len = self.currently_bound_lifetimes.len();
1436 hir::intravisit::walk_ty(self, t);
1437 self.currently_bound_lifetimes.truncate(old_len);
1439 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1441 hir::intravisit::walk_ty(self, t)
1445 fn visit_poly_trait_ref(
1447 trait_ref: &'v hir::PolyTraitRef,
1448 modifier: hir::TraitBoundModifier,
1450 // Record the "stack height" of `for<'a>` lifetime bindings
1451 // to be able to later fully undo their introduction.
1452 let old_len = self.currently_bound_lifetimes.len();
1453 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1454 self.currently_bound_lifetimes.truncate(old_len);
1457 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1458 // Record the introduction of 'a in `for<'a> ...`
1459 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1460 // Introduce lifetimes one at a time so that we can handle
1461 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1462 let lt_name = hir::LifetimeName::Param(param.name);
1463 self.currently_bound_lifetimes.push(lt_name);
1466 hir::intravisit::walk_generic_param(self, param);
1469 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1470 let name = match lifetime.name {
1471 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1472 if self.collect_elided_lifetimes {
1473 // Use `'_` for both implicit and underscore lifetimes in
1474 // `abstract type Foo<'_>: SomeTrait<'_>;`
1475 hir::LifetimeName::Underscore
1480 hir::LifetimeName::Param(_) => lifetime.name,
1481 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1484 if !self.currently_bound_lifetimes.contains(&name)
1485 && !self.already_defined_lifetimes.contains(&name) {
1486 self.already_defined_lifetimes.insert(name);
1488 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1489 id: self.context.next_id().node_id,
1490 span: lifetime.span,
1494 // We need to manually create the ids here, because the
1495 // definitions will go into the explicit `existential type`
1496 // declaration and thus need to have their owner set to that item
1497 let def_node_id = self.context.sess.next_node_id();
1498 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1499 self.context.resolver.definitions().create_def_with_parent(
1502 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1503 DefIndexAddressSpace::High,
1508 let (name, kind) = match name {
1509 hir::LifetimeName::Underscore => (
1510 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident()),
1511 hir::LifetimeParamKind::Elided,
1513 hir::LifetimeName::Param(param_name) => (
1515 hir::LifetimeParamKind::Explicit,
1517 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1520 self.output_lifetime_params.push(hir::GenericParam {
1523 span: lifetime.span,
1524 pure_wrt_drop: false,
1527 kind: hir::GenericParamKind::Lifetime { kind }
1533 let mut lifetime_collector = ImplTraitLifetimeCollector {
1535 parent: parent_index,
1537 collect_elided_lifetimes: true,
1538 currently_bound_lifetimes: Vec::new(),
1539 already_defined_lifetimes: FxHashSet::default(),
1540 output_lifetimes: Vec::new(),
1541 output_lifetime_params: Vec::new(),
1544 for bound in bounds {
1545 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1549 lifetime_collector.output_lifetimes.into(),
1550 lifetime_collector.output_lifetime_params.into(),
1554 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1559 .map(|x| self.lower_foreign_item(x))
1564 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1571 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1573 node: hir::VariantKind {
1574 name: v.node.ident.name,
1575 attrs: self.lower_attrs(&v.node.attrs),
1576 data: self.lower_variant_data(&v.node.data),
1577 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1586 qself: &Option<QSelf>,
1588 param_mode: ParamMode,
1589 mut itctx: ImplTraitContext<'_>,
1591 let qself_position = qself.as_ref().map(|q| q.position);
1592 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1594 let resolution = self.resolver
1596 .unwrap_or_else(|| PathResolution::new(Def::Err));
1598 let proj_start = p.segments.len() - resolution.unresolved_segments();
1599 let path = P(hir::Path {
1600 def: resolution.base_def(),
1601 segments: p.segments[..proj_start]
1604 .map(|(i, segment)| {
1605 let param_mode = match (qself_position, param_mode) {
1606 (Some(j), ParamMode::Optional) if i < j => {
1607 // This segment is part of the trait path in a
1608 // qualified path - one of `a`, `b` or `Trait`
1609 // in `<X as a::b::Trait>::T::U::method`.
1615 // Figure out if this is a type/trait segment,
1616 // which may need lifetime elision performed.
1617 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1618 krate: def_id.krate,
1619 index: this.def_key(def_id).parent.expect("missing parent"),
1621 let type_def_id = match resolution.base_def() {
1622 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1623 Some(parent_def_id(self, def_id))
1625 Def::Variant(def_id) if i + 1 == proj_start => {
1626 Some(parent_def_id(self, def_id))
1629 | Def::Union(def_id)
1631 | Def::TyAlias(def_id)
1632 | Def::Trait(def_id) if i + 1 == proj_start =>
1638 let parenthesized_generic_args = match resolution.base_def() {
1639 // `a::b::Trait(Args)`
1640 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1641 // `a::b::Trait(Args)::TraitItem`
1642 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1643 if i + 2 == proj_start =>
1645 ParenthesizedGenericArgs::Ok
1647 // Avoid duplicated errors
1648 Def::Err => ParenthesizedGenericArgs::Ok,
1654 | Def::Variant(..) if i + 1 == proj_start =>
1656 ParenthesizedGenericArgs::Err
1658 // A warning for now, for compatibility reasons
1659 _ => ParenthesizedGenericArgs::Warn,
1662 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1663 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1666 assert!(!def_id.is_local());
1668 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1669 let n = item_generics.own_counts().lifetimes;
1670 self.type_def_lifetime_params.insert(def_id, n);
1673 self.lower_path_segment(
1678 parenthesized_generic_args,
1686 // Simple case, either no projections, or only fully-qualified.
1687 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1688 if resolution.unresolved_segments() == 0 {
1689 return hir::QPath::Resolved(qself, path);
1692 // Create the innermost type that we're projecting from.
1693 let mut ty = if path.segments.is_empty() {
1694 // If the base path is empty that means there exists a
1695 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1696 qself.expect("missing QSelf for <T>::...")
1698 // Otherwise, the base path is an implicit `Self` type path,
1699 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1700 // `<I as Iterator>::Item::default`.
1701 let new_id = self.next_id();
1702 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1705 // Anything after the base path are associated "extensions",
1706 // out of which all but the last one are associated types,
1707 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1708 // * base path is `std::vec::Vec<T>`
1709 // * "extensions" are `IntoIter`, `Item` and `clone`
1710 // * type nodes are:
1711 // 1. `std::vec::Vec<T>` (created above)
1712 // 2. `<std::vec::Vec<T>>::IntoIter`
1713 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1714 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1715 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1716 let segment = P(self.lower_path_segment(
1721 ParenthesizedGenericArgs::Warn,
1724 let qpath = hir::QPath::TypeRelative(ty, segment);
1726 // It's finished, return the extension of the right node type.
1727 if i == p.segments.len() - 1 {
1731 // Wrap the associated extension in another type node.
1732 let new_id = self.next_id();
1733 ty = P(self.ty_path(new_id, p.span, qpath));
1736 // Should've returned in the for loop above.
1739 "lower_qpath: no final extension segment in {}..{}",
1745 fn lower_path_extra(
1749 ident: Option<Ident>,
1750 param_mode: ParamMode,
1754 segments: p.segments
1757 self.lower_path_segment(
1762 ParenthesizedGenericArgs::Err,
1763 ImplTraitContext::disallowed(),
1766 .chain(ident.map(|ident| hir::PathSegment::from_ident(ident)))
1772 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1773 let def = self.expect_full_def(id);
1774 self.lower_path_extra(def, p, None, param_mode)
1777 fn lower_path_segment(
1780 segment: &PathSegment,
1781 param_mode: ParamMode,
1782 expected_lifetimes: usize,
1783 parenthesized_generic_args: ParenthesizedGenericArgs,
1784 itctx: ImplTraitContext<'_>,
1785 ) -> hir::PathSegment {
1786 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1787 let msg = "parenthesized parameters may only be used with a trait";
1788 match **generic_args {
1789 GenericArgs::AngleBracketed(ref data) => {
1790 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1792 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1793 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1794 ParenthesizedGenericArgs::Warn => {
1795 self.sess.buffer_lint(
1796 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1801 (hir::GenericArgs::none(), true)
1803 ParenthesizedGenericArgs::Err => {
1804 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1805 .span_label(data.span, "only traits may use parentheses")
1807 (hir::GenericArgs::none(), true)
1812 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1815 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1816 GenericArg::Lifetime(_) => true,
1819 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1820 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1821 if !generic_args.parenthesized && !has_lifetimes {
1823 self.elided_path_lifetimes(path_span, expected_lifetimes)
1825 .map(|lt| GenericArg::Lifetime(lt))
1826 .chain(generic_args.args.into_iter())
1828 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1829 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1830 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1831 let no_bindings = generic_args.bindings.is_empty();
1832 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1833 // If there are no (non-implicit) generic args or associated-type
1834 // bindings, our suggestion includes the angle brackets
1835 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1837 // Otherwise—sorry, this is kind of gross—we need to infer the
1838 // place to splice in the `'_, ` from the generics that do exist
1839 let first_generic_span = first_generic_span
1840 .expect("already checked that type args or bindings exist");
1841 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1843 self.sess.buffer_lint_with_diagnostic(
1844 ELIDED_LIFETIMES_IN_PATHS,
1847 "hidden lifetime parameters in types are deprecated",
1848 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1849 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1855 hir::PathSegment::new(
1862 fn lower_angle_bracketed_parameter_data(
1864 data: &AngleBracketedArgs,
1865 param_mode: ParamMode,
1866 mut itctx: ImplTraitContext<'_>,
1867 ) -> (hir::GenericArgs, bool) {
1868 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1869 let has_types = args.iter().any(|arg| match arg {
1870 ast::GenericArg::Type(_) => true,
1874 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1875 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1876 parenthesized: false,
1878 !has_types && param_mode == ParamMode::Optional)
1881 fn lower_parenthesized_parameter_data(
1883 data: &ParenthesisedArgs,
1884 ) -> (hir::GenericArgs, bool) {
1885 // Switch to `PassThrough` mode for anonymous lifetimes: this
1886 // means that we permit things like `&Ref<T>`, where `Ref` has
1887 // a hidden lifetime parameter. This is needed for backwards
1888 // compatibility, even in contexts like an impl header where
1889 // we generally don't permit such things (see #51008).
1890 self.with_anonymous_lifetime_mode(
1891 AnonymousLifetimeMode::PassThrough,
1893 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1896 .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
1898 let mk_tup = |this: &mut Self, tys, span| {
1899 let LoweredNodeId { node_id, hir_id } = this.next_id();
1900 hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1905 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1908 id: this.next_id().node_id,
1909 ident: Ident::from_str(FN_OUTPUT_NAME),
1912 .map(|ty| this.lower_ty(&ty, ImplTraitContext::disallowed()))
1913 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1914 span: output.as_ref().map_or(span, |ty| ty.span),
1917 parenthesized: true,
1925 fn lower_local(&mut self, l: &Local) -> (P<hir::Local>, SmallVec<[hir::ItemId; 1]>) {
1926 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1927 let mut ids = SmallVec::<[hir::ItemId; 1]>::new();
1928 if self.sess.features_untracked().impl_trait_in_bindings {
1929 if let Some(ref ty) = l.ty {
1930 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
1931 visitor.visit_ty(ty);
1934 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
1940 .map(|t| self.lower_ty(t,
1941 if self.sess.features_untracked().impl_trait_in_bindings {
1942 ImplTraitContext::Existential(Some(parent_def_id))
1944 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
1947 pat: self.lower_pat(&l.pat),
1948 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1950 attrs: l.attrs.clone(),
1951 source: hir::LocalSource::Normal,
1955 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1957 Mutability::Mutable => hir::MutMutable,
1958 Mutability::Immutable => hir::MutImmutable,
1962 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1963 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1967 pat: self.lower_pat(&arg.pat),
1971 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1974 .map(|arg| match arg.pat.node {
1975 PatKind::Ident(_, ident, _) => ident,
1976 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
1981 // Lowers a function declaration.
1983 // decl: the unlowered (ast) function declaration.
1984 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1985 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1986 // make_ret_async is also `Some`.
1987 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1988 // This guards against trait declarations and implementations where impl Trait is
1990 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1991 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
1992 // return type impl Trait item.
1996 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
1997 impl_trait_return_allow: bool,
1998 make_ret_async: Option<NodeId>,
1999 ) -> P<hir::FnDecl> {
2000 let inputs = decl.inputs
2003 if let Some((_, ref mut ibty)) = in_band_ty_params {
2004 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2006 self.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2009 .collect::<HirVec<_>>();
2011 let output = if let Some(ret_id) = make_ret_async {
2012 self.lower_async_fn_ret_ty(
2015 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
2020 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2021 Some((def_id, _)) if impl_trait_return_allow => {
2022 hir::Return(self.lower_ty(ty,
2023 ImplTraitContext::Existential(Some(def_id))))
2026 hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2029 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2036 variadic: decl.variadic,
2037 implicit_self: decl.inputs.get(0).map_or(
2038 hir::ImplicitSelfKind::None,
2040 let is_mutable_pat = match arg.pat.node {
2041 PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2042 PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2043 mt == Mutability::Mutable,
2048 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2049 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2050 // Given we are only considering `ImplicitSelf` types, we needn't consider
2051 // the case where we have a mutable pattern to a reference as that would
2052 // no longer be an `ImplicitSelf`.
2053 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2054 mt.mutbl == ast::Mutability::Mutable =>
2055 hir::ImplicitSelfKind::MutRef,
2056 TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2057 hir::ImplicitSelfKind::ImmRef,
2058 _ => hir::ImplicitSelfKind::None,
2065 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
2067 // fn_span: the span of the async function declaration. Used for error reporting.
2068 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
2069 // output: unlowered output type (`T` in `-> T`)
2070 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
2071 fn lower_async_fn_ret_ty(
2074 output: &FunctionRetTy,
2076 return_impl_trait_id: NodeId,
2077 ) -> hir::FunctionRetTy {
2078 // Get lifetimes used in the input arguments to the function. Our output type must also
2079 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
2080 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
2081 // is a subset of the other. We really want some new lifetime that is a subset of all input
2082 // lifetimes, but that doesn't exist at the moment.
2084 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
2085 context: &'r mut LoweringContext<'a>,
2086 // Lifetimes bound by HRTB
2087 currently_bound_lifetimes: Vec<hir::LifetimeName>,
2088 // Whether to count elided lifetimes.
2089 // Disabled inside of `Fn` or `fn` syntax.
2090 collect_elided_lifetimes: bool,
2091 // The lifetime found.
2092 // Multiple different or elided lifetimes cannot appear in async fn for now.
2093 output_lifetime: Option<(hir::LifetimeName, Span)>,
2096 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
2097 fn nested_visit_map<'this>(
2099 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
2100 hir::intravisit::NestedVisitorMap::None
2103 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
2104 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2105 if parameters.parenthesized {
2106 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2107 self.collect_elided_lifetimes = false;
2108 hir::intravisit::walk_generic_args(self, span, parameters);
2109 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2111 hir::intravisit::walk_generic_args(self, span, parameters);
2115 fn visit_ty(&mut self, t: &'v hir::Ty) {
2116 // Don't collect elided lifetimes used inside of `fn()` syntax
2117 if let &hir::TyKind::BareFn(_) = &t.node {
2118 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2119 self.collect_elided_lifetimes = false;
2121 // Record the "stack height" of `for<'a>` lifetime bindings
2122 // to be able to later fully undo their introduction.
2123 let old_len = self.currently_bound_lifetimes.len();
2124 hir::intravisit::walk_ty(self, t);
2125 self.currently_bound_lifetimes.truncate(old_len);
2127 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2129 hir::intravisit::walk_ty(self, t);
2133 fn visit_poly_trait_ref(
2135 trait_ref: &'v hir::PolyTraitRef,
2136 modifier: hir::TraitBoundModifier,
2138 // Record the "stack height" of `for<'a>` lifetime bindings
2139 // to be able to later fully undo their introduction.
2140 let old_len = self.currently_bound_lifetimes.len();
2141 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2142 self.currently_bound_lifetimes.truncate(old_len);
2145 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2146 // Record the introduction of 'a in `for<'a> ...`
2147 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2148 // Introduce lifetimes one at a time so that we can handle
2149 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2150 let lt_name = hir::LifetimeName::Param(param.name);
2151 self.currently_bound_lifetimes.push(lt_name);
2154 hir::intravisit::walk_generic_param(self, param);
2157 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2158 let name = match lifetime.name {
2159 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2160 if self.collect_elided_lifetimes {
2161 // Use `'_` for both implicit and underscore lifetimes in
2162 // `abstract type Foo<'_>: SomeTrait<'_>;`
2163 hir::LifetimeName::Underscore
2168 hir::LifetimeName::Param(_) => lifetime.name,
2169 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
2172 if !self.currently_bound_lifetimes.contains(&name) {
2173 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2174 // We don't currently have a reliable way to desugar `async fn` with
2175 // multiple potentially unrelated input lifetimes into
2176 // `-> impl Trait + 'lt`, so we report an error in this case.
2177 if current_lt_name != name {
2180 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2182 "multiple different lifetimes used in arguments of `async fn`",
2184 .span_label(current_lt_span, "first lifetime here")
2185 .span_label(lifetime.span, "different lifetime here")
2186 .help("`async fn` can only accept borrowed values \
2187 with identical lifetimes")
2189 } else if current_lt_name.is_elided() && name.is_elided() {
2192 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2194 "multiple elided lifetimes used in arguments of `async fn`",
2196 .span_label(current_lt_span, "first lifetime here")
2197 .span_label(lifetime.span, "different lifetime here")
2198 .help("consider giving these arguments named lifetimes")
2202 self.output_lifetime = Some((name, lifetime.span));
2208 let bound_lifetime = {
2209 let mut lifetime_collector = AsyncFnLifetimeCollector {
2211 currently_bound_lifetimes: Vec::new(),
2212 collect_elided_lifetimes: true,
2213 output_lifetime: None,
2217 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2219 lifetime_collector.output_lifetime
2222 let span = match output {
2223 FunctionRetTy::Ty(ty) => ty.span,
2224 FunctionRetTy::Default(span) => *span,
2227 let impl_trait_ty = self.lower_existential_impl_trait(
2228 span, Some(fn_def_id), return_impl_trait_id, |this| {
2229 let output_ty = match output {
2230 FunctionRetTy::Ty(ty) => {
2231 this.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2233 FunctionRetTy::Default(span) => {
2234 let LoweredNodeId { node_id, hir_id } = this.next_id();
2238 node: hir::TyKind::Tup(hir_vec![]),
2245 let future_params = P(hir::GenericArgs {
2247 bindings: hir_vec![hir::TypeBinding {
2248 ident: Ident::from_str(FN_OUTPUT_NAME),
2250 id: this.next_id().node_id,
2253 parenthesized: false,
2257 this.std_path(span, &["future", "Future"], Some(future_params), false);
2259 let LoweredNodeId { node_id, hir_id } = this.next_id();
2260 let mut bounds = vec![
2261 hir::GenericBound::Trait(
2263 trait_ref: hir::TraitRef {
2268 bound_generic_params: hir_vec![],
2271 hir::TraitBoundModifier::None
2275 if let Some((name, span)) = bound_lifetime {
2276 bounds.push(hir::GenericBound::Outlives(
2277 hir::Lifetime { id: this.next_id().node_id, name, span }));
2280 hir::HirVec::from(bounds)
2283 let LoweredNodeId { node_id, hir_id } = self.next_id();
2284 let impl_trait_ty = P(hir::Ty {
2286 node: impl_trait_ty,
2291 hir::FunctionRetTy::Return(impl_trait_ty)
2294 fn lower_param_bound(
2297 itctx: ImplTraitContext<'_>,
2298 ) -> hir::GenericBound {
2300 GenericBound::Trait(ref ty, modifier) => {
2301 hir::GenericBound::Trait(
2302 self.lower_poly_trait_ref(ty, itctx),
2303 self.lower_trait_bound_modifier(modifier),
2306 GenericBound::Outlives(ref lifetime) => {
2307 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2312 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2313 let span = l.ident.span;
2315 ident if ident.name == keywords::StaticLifetime.name() =>
2316 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2317 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2318 match self.anonymous_lifetime_mode {
2319 AnonymousLifetimeMode::CreateParameter => {
2320 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2321 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2324 AnonymousLifetimeMode::PassThrough => {
2325 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2328 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2331 self.maybe_collect_in_band_lifetime(ident);
2332 let param_name = ParamName::Plain(ident);
2333 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2338 fn new_named_lifetime(
2342 name: hir::LifetimeName,
2343 ) -> hir::Lifetime {
2345 id: self.lower_node_id(id).node_id,
2351 fn lower_generic_params(
2353 params: &[GenericParam],
2354 add_bounds: &NodeMap<Vec<GenericBound>>,
2355 mut itctx: ImplTraitContext<'_>,
2356 ) -> hir::HirVec<hir::GenericParam> {
2357 params.iter().map(|param| {
2358 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2362 fn lower_generic_param(&mut self,
2363 param: &GenericParam,
2364 add_bounds: &NodeMap<Vec<GenericBound>>,
2365 mut itctx: ImplTraitContext<'_>)
2366 -> hir::GenericParam {
2367 let mut bounds = self.with_anonymous_lifetime_mode(
2368 AnonymousLifetimeMode::ReportError,
2369 |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()),
2373 GenericParamKind::Lifetime => {
2374 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2375 self.is_collecting_in_band_lifetimes = false;
2377 let lt = self.with_anonymous_lifetime_mode(
2378 AnonymousLifetimeMode::ReportError,
2379 |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2381 let param_name = match lt.name {
2382 hir::LifetimeName::Param(param_name) => param_name,
2383 hir::LifetimeName::Implicit
2384 | hir::LifetimeName::Underscore
2385 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2386 hir::LifetimeName::Error => ParamName::Error,
2388 let param = hir::GenericParam {
2392 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2393 attrs: self.lower_attrs(¶m.attrs),
2395 kind: hir::GenericParamKind::Lifetime {
2396 kind: hir::LifetimeParamKind::Explicit,
2400 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2404 GenericParamKind::Type { ref default, .. } => {
2405 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2406 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2407 // Instead, use gensym("Self") to create a distinct name that looks the same.
2408 let ident = if param.ident.name == keywords::SelfType.name() {
2409 param.ident.gensym()
2414 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2415 if !add_bounds.is_empty() {
2416 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2417 bounds = bounds.into_iter()
2423 id: self.lower_node_id(param.id).node_id,
2424 name: hir::ParamName::Plain(ident),
2425 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2426 attrs: self.lower_attrs(¶m.attrs),
2429 kind: hir::GenericParamKind::Type {
2430 default: default.as_ref().map(|x| {
2431 self.lower_ty(x, ImplTraitContext::disallowed())
2433 synthetic: param.attrs.iter()
2434 .filter(|attr| attr.check_name("rustc_synthetic"))
2435 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2445 generics: &Generics,
2446 itctx: ImplTraitContext<'_>)
2449 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2450 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2451 // paths where report_error is called are also the only paths that advance to after
2452 // the match statement, so the error reporting could probably just be moved there.
2453 let mut add_bounds: NodeMap<Vec<_>> = NodeMap();
2454 for pred in &generics.where_clause.predicates {
2455 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2456 'next_bound: for bound in &bound_pred.bounds {
2457 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2458 let report_error = |this: &mut Self| {
2459 this.diagnostic().span_err(
2460 bound_pred.bounded_ty.span,
2461 "`?Trait` bounds are only permitted at the \
2462 point where a type parameter is declared",
2465 // Check if the where clause type is a plain type parameter.
2466 match bound_pred.bounded_ty.node {
2467 TyKind::Path(None, ref path)
2468 if path.segments.len() == 1
2469 && bound_pred.bound_generic_params.is_empty() =>
2471 if let Some(Def::TyParam(def_id)) = self.resolver
2472 .get_resolution(bound_pred.bounded_ty.id)
2473 .map(|d| d.base_def())
2475 if let Some(node_id) =
2476 self.resolver.definitions().as_local_node_id(def_id)
2478 for param in &generics.params {
2480 GenericParamKind::Type { .. } => {
2481 if node_id == param.id {
2482 add_bounds.entry(param.id)
2484 .push(bound.clone());
2485 continue 'next_bound;
2495 _ => report_error(self),
2503 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2504 where_clause: self.lower_where_clause(&generics.where_clause),
2505 span: generics.span,
2509 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2510 self.with_anonymous_lifetime_mode(
2511 AnonymousLifetimeMode::ReportError,
2514 id: this.lower_node_id(wc.id).node_id,
2515 predicates: wc.predicates
2517 .map(|predicate| this.lower_where_predicate(predicate))
2524 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2526 WherePredicate::BoundPredicate(WhereBoundPredicate {
2527 ref bound_generic_params,
2532 self.with_in_scope_lifetime_defs(
2533 &bound_generic_params,
2535 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2536 bound_generic_params: this.lower_generic_params(
2537 bound_generic_params,
2539 ImplTraitContext::disallowed(),
2541 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
2544 .filter_map(|bound| match *bound {
2545 // Ignore `?Trait` bounds.
2546 // Tthey were copied into type parameters already.
2547 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2548 _ => Some(this.lower_param_bound(
2550 ImplTraitContext::disallowed(),
2559 WherePredicate::RegionPredicate(WhereRegionPredicate {
2563 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2565 lifetime: self.lower_lifetime(lifetime),
2566 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2568 WherePredicate::EqPredicate(WhereEqPredicate {
2573 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2574 id: self.lower_node_id(id).node_id,
2575 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
2576 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
2582 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2584 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2588 .map(|f| self.lower_struct_field(f))
2590 self.lower_node_id(id).node_id,
2592 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2596 .map(|f| self.lower_struct_field(f))
2598 self.lower_node_id(id).node_id,
2600 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2604 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2605 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2606 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2607 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2609 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.ref_id);
2617 fn lower_poly_trait_ref(
2620 mut itctx: ImplTraitContext<'_>,
2621 ) -> hir::PolyTraitRef {
2622 let bound_generic_params =
2623 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx.reborrow());
2624 let trait_ref = self.with_parent_impl_lifetime_defs(
2625 &bound_generic_params,
2626 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2630 bound_generic_params,
2636 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2639 id: self.lower_node_id(f.id).node_id,
2640 ident: match f.ident {
2641 Some(ident) => ident,
2642 // FIXME(jseyfried) positional field hygiene
2643 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2645 vis: self.lower_visibility(&f.vis, None),
2646 ty: self.lower_ty(&f.ty, ImplTraitContext::disallowed()),
2647 attrs: self.lower_attrs(&f.attrs),
2651 fn lower_field(&mut self, f: &Field) -> hir::Field {
2653 id: self.next_id().node_id,
2655 expr: P(self.lower_expr(&f.expr)),
2657 is_shorthand: f.is_shorthand,
2661 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2663 ty: self.lower_ty(&mt.ty, itctx),
2664 mutbl: self.lower_mutability(mt.mutbl),
2668 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2669 -> hir::GenericBounds {
2670 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2673 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2674 let mut expr = None;
2676 let mut stmts = vec![];
2678 for (index, stmt) in b.stmts.iter().enumerate() {
2679 if index == b.stmts.len() - 1 {
2680 if let StmtKind::Expr(ref e) = stmt.node {
2681 expr = Some(P(self.lower_expr(e)));
2683 stmts.extend(self.lower_stmt(stmt));
2686 stmts.extend(self.lower_stmt(stmt));
2690 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2695 stmts: stmts.into(),
2697 rules: self.lower_block_check_mode(&b.rules),
2700 recovered: b.recovered,
2704 fn lower_async_body(
2710 self.lower_body(Some(decl), |this| {
2711 if let IsAsync::Async { closure_id, .. } = asyncness {
2712 let async_expr = this.make_async_expr(
2713 CaptureBy::Value, closure_id, None,
2715 let body = this.lower_block(body, false);
2716 this.expr_block(body, ThinVec::new())
2718 this.expr(body.span, async_expr, ThinVec::new())
2720 let body = this.lower_block(body, false);
2721 this.expr_block(body, ThinVec::new())
2730 attrs: &hir::HirVec<Attribute>,
2731 vis: &mut hir::Visibility,
2733 ) -> hir::ItemKind {
2735 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2736 ItemKind::Use(ref use_tree) => {
2737 // Start with an empty prefix
2740 span: use_tree.span,
2743 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2745 ItemKind::Static(ref t, m, ref e) => {
2746 let value = self.lower_body(None, |this| this.lower_expr(e));
2747 hir::ItemKind::Static(
2750 if self.sess.features_untracked().impl_trait_in_bindings {
2751 ImplTraitContext::Existential(None)
2753 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2756 self.lower_mutability(m),
2760 ItemKind::Const(ref t, ref e) => {
2761 let value = self.lower_body(None, |this| this.lower_expr(e));
2762 hir::ItemKind::Const(
2765 if self.sess.features_untracked().impl_trait_in_bindings {
2766 ImplTraitContext::Existential(None)
2768 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2774 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2775 let fn_def_id = self.resolver.definitions().local_def_id(id);
2776 self.with_new_scopes(|this| {
2777 // Note: we don't need to change the return type from `T` to
2778 // `impl Future<Output = T>` here because lower_body
2779 // only cares about the input argument patterns in the function
2780 // declaration (decl), not the return types.
2781 let body_id = this.lower_async_body(decl, header.asyncness, body);
2783 let (generics, fn_decl) = this.add_in_band_defs(
2786 AnonymousLifetimeMode::PassThrough,
2787 |this, idty| this.lower_fn_decl(
2789 Some((fn_def_id, idty)),
2791 header.asyncness.opt_return_id()
2797 this.lower_fn_header(header),
2803 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2804 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2805 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2806 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2807 self.lower_ty(t, ImplTraitContext::disallowed()),
2808 self.lower_generics(generics, ImplTraitContext::disallowed()),
2810 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2811 generics: self.lower_generics(generics, ImplTraitContext::disallowed()),
2812 bounds: self.lower_param_bounds(b, ImplTraitContext::disallowed()),
2813 impl_trait_fn: None,
2815 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2817 variants: enum_definition
2820 .map(|x| self.lower_variant(x))
2823 self.lower_generics(generics, ImplTraitContext::disallowed()),
2825 ItemKind::Struct(ref struct_def, ref generics) => {
2826 let struct_def = self.lower_variant_data(struct_def);
2827 hir::ItemKind::Struct(
2829 self.lower_generics(generics, ImplTraitContext::disallowed()),
2832 ItemKind::Union(ref vdata, ref generics) => {
2833 let vdata = self.lower_variant_data(vdata);
2834 hir::ItemKind::Union(
2836 self.lower_generics(generics, ImplTraitContext::disallowed()),
2848 let def_id = self.resolver.definitions().local_def_id(id);
2850 // Lower the "impl header" first. This ordering is important
2851 // for in-band lifetimes! Consider `'a` here:
2853 // impl Foo<'a> for u32 {
2854 // fn method(&'a self) { .. }
2857 // Because we start by lowering the `Foo<'a> for u32`
2858 // part, we will add `'a` to the list of generics on
2859 // the impl. When we then encounter it later in the
2860 // method, it will not be considered an in-band
2861 // lifetime to be added, but rather a reference to a
2863 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2866 AnonymousLifetimeMode::CreateParameter,
2868 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2869 this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
2872 if let Some(ref trait_ref) = trait_ref {
2873 if let Def::Trait(def_id) = trait_ref.path.def {
2874 this.trait_impls.entry(def_id).or_default().push(id);
2878 let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
2880 (trait_ref, lowered_ty)
2884 let new_impl_items = self.with_in_scope_lifetime_defs(
2885 &ast_generics.params,
2889 .map(|item| this.lower_impl_item_ref(item))
2894 hir::ItemKind::Impl(
2895 self.lower_unsafety(unsafety),
2896 self.lower_impl_polarity(polarity),
2897 self.lower_defaultness(defaultness, true /* [1] */),
2904 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2905 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
2908 .map(|item| self.lower_trait_item_ref(item))
2910 hir::ItemKind::Trait(
2911 self.lower_is_auto(is_auto),
2912 self.lower_unsafety(unsafety),
2913 self.lower_generics(generics, ImplTraitContext::disallowed()),
2918 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
2919 self.lower_generics(generics, ImplTraitContext::disallowed()),
2920 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2922 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2925 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2926 // not cause an assertion failure inside the `lower_defaultness` function
2934 vis: &mut hir::Visibility,
2936 attrs: &hir::HirVec<Attribute>,
2937 ) -> hir::ItemKind {
2938 let path = &tree.prefix;
2941 UseTreeKind::Simple(rename, id1, id2) => {
2942 *name = tree.ident().name;
2944 // First apply the prefix to the path
2945 let mut path = Path {
2949 .chain(path.segments.iter())
2955 // Correctly resolve `self` imports
2956 if path.segments.len() > 1
2957 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2959 let _ = path.segments.pop();
2960 if rename.is_none() {
2961 *name = path.segments.last().unwrap().ident.name;
2965 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2966 let mut defs = self.expect_full_def_from_use(id);
2967 // we want to return *something* from this function, so hang onto the first item
2969 let ret_def = defs.next().unwrap_or(Def::Err);
2971 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2972 let vis = vis.clone();
2973 let name = name.clone();
2974 let span = path.span;
2975 self.resolver.definitions().create_def_with_parent(
2979 DefIndexAddressSpace::High,
2982 self.allocate_hir_id_counter(new_node_id, &path);
2984 self.with_hir_id_owner(new_node_id, |this| {
2985 let new_id = this.lower_node_id(new_node_id);
2986 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2987 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
2988 let vis_kind = match vis.node {
2989 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2990 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2991 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2992 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
2993 let id = this.next_id();
2994 hir::VisibilityKind::Restricted {
2996 // We are allocating a new NodeId here
3002 let vis = respan(vis.span, vis_kind);
3008 hir_id: new_id.hir_id,
3010 attrs: attrs.clone(),
3019 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
3020 hir::ItemKind::Use(path, hir::UseKind::Single)
3022 UseTreeKind::Glob => {
3023 let path = P(self.lower_path(
3029 .chain(path.segments.iter())
3034 ParamMode::Explicit,
3036 hir::ItemKind::Use(path, hir::UseKind::Glob)
3038 UseTreeKind::Nested(ref trees) => {
3043 .chain(path.segments.iter())
3046 span: prefix.span.to(path.span),
3049 // Add all the nested PathListItems in the HIR
3050 for &(ref use_tree, id) in trees {
3051 self.allocate_hir_id_counter(id, &use_tree);
3055 } = self.lower_node_id(id);
3057 let mut vis = vis.clone();
3058 let mut name = name.clone();
3060 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
3062 self.with_hir_id_owner(new_id, |this| {
3063 let vis_kind = match vis.node {
3064 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3065 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3066 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3067 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3068 let id = this.next_id();
3069 hir::VisibilityKind::Restricted {
3071 // We are allocating a new NodeId here
3077 let vis = respan(vis.span, vis_kind);
3085 attrs: attrs.clone(),
3088 span: use_tree.span,
3094 // Privatize the degenerate import base, used only to check
3095 // the stability of `use a::{};`, to avoid it showing up as
3096 // a re-export by accident when `pub`, e.g. in documentation.
3097 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
3098 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3099 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3104 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3105 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3106 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
3108 let (generics, node) = match i.node {
3109 TraitItemKind::Const(ref ty, ref default) => (
3110 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3111 hir::TraitItemKind::Const(
3112 self.lower_ty(ty, ImplTraitContext::disallowed()),
3115 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
3118 TraitItemKind::Method(ref sig, None) => {
3119 let names = self.lower_fn_args_to_names(&sig.decl);
3120 let (generics, sig) = self.lower_method_sig(
3127 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3129 TraitItemKind::Method(ref sig, Some(ref body)) => {
3130 let body_id = self.lower_body(Some(&sig.decl), |this| {
3131 let body = this.lower_block(body, false);
3132 this.expr_block(body, ThinVec::new())
3134 let (generics, sig) = self.lower_method_sig(
3141 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3143 TraitItemKind::Type(ref bounds, ref default) => (
3144 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3145 hir::TraitItemKind::Type(
3146 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3149 .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3152 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3159 attrs: self.lower_attrs(&i.attrs),
3166 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3167 let (kind, has_default) = match i.node {
3168 TraitItemKind::Const(_, ref default) => {
3169 (hir::AssociatedItemKind::Const, default.is_some())
3171 TraitItemKind::Type(_, ref default) => {
3172 (hir::AssociatedItemKind::Type, default.is_some())
3174 TraitItemKind::Method(ref sig, ref default) => (
3175 hir::AssociatedItemKind::Method {
3176 has_self: sig.decl.has_self(),
3180 TraitItemKind::Macro(..) => unimplemented!(),
3183 id: hir::TraitItemId { node_id: i.id },
3186 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3191 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3192 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3193 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3195 let (generics, node) = match i.node {
3196 ImplItemKind::Const(ref ty, ref expr) => {
3197 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3199 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3200 hir::ImplItemKind::Const(
3201 self.lower_ty(ty, ImplTraitContext::disallowed()),
3206 ImplItemKind::Method(ref sig, ref body) => {
3207 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3208 let impl_trait_return_allow = !self.is_in_trait_impl;
3209 let (generics, sig) = self.lower_method_sig(
3213 impl_trait_return_allow,
3214 sig.header.asyncness.opt_return_id(),
3216 (generics, hir::ImplItemKind::Method(sig, body_id))
3218 ImplItemKind::Type(ref ty) => (
3219 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3220 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3222 ImplItemKind::Existential(ref bounds) => (
3223 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3224 hir::ImplItemKind::Existential(
3225 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3228 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3235 attrs: self.lower_attrs(&i.attrs),
3237 vis: self.lower_visibility(&i.vis, None),
3238 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3243 // [1] since `default impl` is not yet implemented, this is always true in impls
3246 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3248 id: hir::ImplItemId { node_id: i.id },
3251 vis: self.lower_visibility(&i.vis, Some(i.id)),
3252 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3253 kind: match i.node {
3254 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3255 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3256 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3257 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3258 has_self: sig.decl.has_self(),
3260 ImplItemKind::Macro(..) => unimplemented!(),
3264 // [1] since `default impl` is not yet implemented, this is always true in impls
3267 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3270 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3274 fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3276 ItemKind::Use(ref use_tree) => {
3277 let mut vec = smallvec![hir::ItemId { id: i.id }];
3278 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3281 ItemKind::MacroDef(..) => SmallVec::new(),
3283 ItemKind::Impl(.., None, _, _) => smallvec![hir::ItemId { id: i.id }],
3284 ItemKind::Static(ref ty, ..) => {
3285 let mut ids = smallvec![hir::ItemId { id: i.id }];
3286 if self.sess.features_untracked().impl_trait_in_bindings {
3287 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3288 visitor.visit_ty(ty);
3292 ItemKind::Const(ref ty, ..) => {
3293 let mut ids = smallvec![hir::ItemId { id: i.id }];
3294 if self.sess.features_untracked().impl_trait_in_bindings {
3295 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3296 visitor.visit_ty(ty);
3300 _ => smallvec![hir::ItemId { id: i.id }],
3304 fn lower_item_id_use_tree(&mut self,
3307 vec: &mut SmallVec<[hir::ItemId; 1]>)
3310 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3311 vec.push(hir::ItemId { id });
3312 self.lower_item_id_use_tree(nested, id, vec);
3314 UseTreeKind::Glob => {}
3315 UseTreeKind::Simple(_, id1, id2) => {
3316 for (_, &id) in self.expect_full_def_from_use(base_id)
3318 .zip([id1, id2].iter())
3320 vec.push(hir::ItemId { id });
3326 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3327 let mut name = i.ident.name;
3328 let mut vis = self.lower_visibility(&i.vis, None);
3329 let attrs = self.lower_attrs(&i.attrs);
3330 if let ItemKind::MacroDef(ref def) = i.node {
3331 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3332 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3333 let body = self.lower_token_stream(def.stream());
3334 self.exported_macros.push(hir::MacroDef {
3347 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3349 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3362 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3363 let node_id = self.lower_node_id(i.id).node_id;
3364 let def_id = self.resolver.definitions().local_def_id(node_id);
3368 attrs: self.lower_attrs(&i.attrs),
3369 node: match i.node {
3370 ForeignItemKind::Fn(ref fdec, ref generics) => {
3371 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3374 AnonymousLifetimeMode::PassThrough,
3377 // Disallow impl Trait in foreign items
3378 this.lower_fn_decl(fdec, None, false, None),
3379 this.lower_fn_args_to_names(fdec),
3384 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3386 ForeignItemKind::Static(ref t, m) => {
3387 hir::ForeignItemKind::Static(
3388 self.lower_ty(t, ImplTraitContext::disallowed()), m)
3390 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3391 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3393 vis: self.lower_visibility(&i.vis, None),
3398 fn lower_method_sig(
3400 generics: &Generics,
3403 impl_trait_return_allow: bool,
3404 is_async: Option<NodeId>,
3405 ) -> (hir::Generics, hir::MethodSig) {
3406 let header = self.lower_fn_header(sig.header);
3407 let (generics, decl) = self.add_in_band_defs(
3410 AnonymousLifetimeMode::PassThrough,
3411 |this, idty| this.lower_fn_decl(
3413 Some((fn_def_id, idty)),
3414 impl_trait_return_allow,
3418 (generics, hir::MethodSig { header, decl })
3421 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3423 IsAuto::Yes => hir::IsAuto::Yes,
3424 IsAuto::No => hir::IsAuto::No,
3428 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3430 unsafety: self.lower_unsafety(h.unsafety),
3431 asyncness: self.lower_asyncness(h.asyncness),
3432 constness: self.lower_constness(h.constness),
3437 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3439 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3440 Unsafety::Normal => hir::Unsafety::Normal,
3444 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3446 Constness::Const => hir::Constness::Const,
3447 Constness::NotConst => hir::Constness::NotConst,
3451 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3453 IsAsync::Async { .. } => hir::IsAsync::Async,
3454 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3458 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3460 UnOp::Deref => hir::UnDeref,
3461 UnOp::Not => hir::UnNot,
3462 UnOp::Neg => hir::UnNeg,
3466 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3468 node: match b.node {
3469 BinOpKind::Add => hir::BinOpKind::Add,
3470 BinOpKind::Sub => hir::BinOpKind::Sub,
3471 BinOpKind::Mul => hir::BinOpKind::Mul,
3472 BinOpKind::Div => hir::BinOpKind::Div,
3473 BinOpKind::Rem => hir::BinOpKind::Rem,
3474 BinOpKind::And => hir::BinOpKind::And,
3475 BinOpKind::Or => hir::BinOpKind::Or,
3476 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3477 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3478 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3479 BinOpKind::Shl => hir::BinOpKind::Shl,
3480 BinOpKind::Shr => hir::BinOpKind::Shr,
3481 BinOpKind::Eq => hir::BinOpKind::Eq,
3482 BinOpKind::Lt => hir::BinOpKind::Lt,
3483 BinOpKind::Le => hir::BinOpKind::Le,
3484 BinOpKind::Ne => hir::BinOpKind::Ne,
3485 BinOpKind::Ge => hir::BinOpKind::Ge,
3486 BinOpKind::Gt => hir::BinOpKind::Gt,
3492 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3493 let node = match p.node {
3494 PatKind::Wild => hir::PatKind::Wild,
3495 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3496 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3497 // `None` can occur in body-less function signatures
3498 def @ None | def @ Some(Def::Local(_)) => {
3499 let canonical_id = match def {
3500 Some(Def::Local(id)) => id,
3503 hir::PatKind::Binding(
3504 self.lower_binding_mode(binding_mode),
3507 sub.as_ref().map(|x| self.lower_pat(x)),
3510 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3515 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3520 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3521 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3522 let qpath = self.lower_qpath(
3526 ParamMode::Optional,
3527 ImplTraitContext::disallowed(),
3529 self.check_self_struct_ctor_feature(&qpath);
3530 hir::PatKind::TupleStruct(
3532 pats.iter().map(|x| self.lower_pat(x)).collect(),
3536 PatKind::Path(ref qself, ref path) => {
3537 let qpath = self.lower_qpath(
3541 ParamMode::Optional,
3542 ImplTraitContext::disallowed(),
3544 self.check_self_struct_ctor_feature(&qpath);
3545 hir::PatKind::Path(qpath)
3547 PatKind::Struct(ref path, ref fields, etc) => {
3548 let qpath = self.lower_qpath(
3552 ParamMode::Optional,
3553 ImplTraitContext::disallowed(),
3560 node: hir::FieldPat {
3561 id: self.next_id().node_id,
3562 ident: f.node.ident,
3563 pat: self.lower_pat(&f.node.pat),
3564 is_shorthand: f.node.is_shorthand,
3568 hir::PatKind::Struct(qpath, fs, etc)
3570 PatKind::Tuple(ref elts, ddpos) => {
3571 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3573 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3574 PatKind::Ref(ref inner, mutbl) => {
3575 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3577 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3578 P(self.lower_expr(e1)),
3579 P(self.lower_expr(e2)),
3580 self.lower_range_end(end),
3582 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3583 before.iter().map(|x| self.lower_pat(x)).collect(),
3584 slice.as_ref().map(|x| self.lower_pat(x)),
3585 after.iter().map(|x| self.lower_pat(x)).collect(),
3587 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3588 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3591 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3600 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3602 RangeEnd::Included(_) => hir::RangeEnd::Included,
3603 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3607 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3608 self.with_new_scopes(|this| {
3609 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3613 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3618 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3619 let kind = match e.node {
3620 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3621 ExprKind::ObsoleteInPlace(..) => {
3622 self.sess.abort_if_errors();
3623 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3625 ExprKind::Array(ref exprs) => {
3626 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3628 ExprKind::Repeat(ref expr, ref count) => {
3629 let expr = P(self.lower_expr(expr));
3630 let count = self.lower_anon_const(count);
3631 hir::ExprKind::Repeat(expr, count)
3633 ExprKind::Tup(ref elts) => {
3634 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3636 ExprKind::Call(ref f, ref args) => {
3637 let f = P(self.lower_expr(f));
3638 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3640 ExprKind::MethodCall(ref seg, ref args) => {
3641 let hir_seg = self.lower_path_segment(
3644 ParamMode::Optional,
3646 ParenthesizedGenericArgs::Err,
3647 ImplTraitContext::disallowed(),
3649 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3650 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3652 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3653 let binop = self.lower_binop(binop);
3654 let lhs = P(self.lower_expr(lhs));
3655 let rhs = P(self.lower_expr(rhs));
3656 hir::ExprKind::Binary(binop, lhs, rhs)
3658 ExprKind::Unary(op, ref ohs) => {
3659 let op = self.lower_unop(op);
3660 let ohs = P(self.lower_expr(ohs));
3661 hir::ExprKind::Unary(op, ohs)
3663 ExprKind::Lit(ref l) => hir::ExprKind::Lit(P((**l).clone())),
3664 ExprKind::Cast(ref expr, ref ty) => {
3665 let expr = P(self.lower_expr(expr));
3666 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3668 ExprKind::Type(ref expr, ref ty) => {
3669 let expr = P(self.lower_expr(expr));
3670 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3672 ExprKind::AddrOf(m, ref ohs) => {
3673 let m = self.lower_mutability(m);
3674 let ohs = P(self.lower_expr(ohs));
3675 hir::ExprKind::AddrOf(m, ohs)
3677 // More complicated than you might expect because the else branch
3678 // might be `if let`.
3679 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3680 let else_opt = else_opt.as_ref().map(|els| {
3682 ExprKind::IfLet(..) => {
3683 // wrap the if-let expr in a block
3684 let span = els.span;
3685 let els = P(self.lower_expr(els));
3686 let LoweredNodeId { node_id, hir_id } = self.next_id();
3687 let blk = P(hir::Block {
3692 rules: hir::DefaultBlock,
3694 targeted_by_break: false,
3695 recovered: blk.recovered,
3697 P(self.expr_block(blk, ThinVec::new()))
3699 _ => P(self.lower_expr(els)),
3703 let then_blk = self.lower_block(blk, false);
3704 let then_expr = self.expr_block(then_blk, ThinVec::new());
3706 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3708 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3709 hir::ExprKind::While(
3710 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3711 this.lower_block(body, false),
3712 this.lower_label(opt_label),
3715 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3716 hir::ExprKind::Loop(
3717 this.lower_block(body, false),
3718 this.lower_label(opt_label),
3719 hir::LoopSource::Loop,
3722 ExprKind::TryBlock(ref body) => {
3723 self.with_catch_scope(body.id, |this| {
3725 this.allow_internal_unstable(CompilerDesugaringKind::TryBlock, body.span);
3726 let mut block = this.lower_block(body, true).into_inner();
3727 let tail = block.expr.take().map_or_else(
3729 let LoweredNodeId { node_id, hir_id } = this.next_id();
3730 let span = this.sess.source_map().end_point(unstable_span);
3734 node: hir::ExprKind::Tup(hir_vec![]),
3735 attrs: ThinVec::new(),
3739 |x: P<hir::Expr>| x.into_inner(),
3741 block.expr = Some(this.wrap_in_try_constructor(
3742 "from_ok", tail, unstable_span));
3743 hir::ExprKind::Block(P(block), None)
3746 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3747 P(self.lower_expr(expr)),
3748 arms.iter().map(|x| self.lower_arm(x)).collect(),
3749 hir::MatchSource::Normal,
3751 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3752 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3753 this.with_new_scopes(|this| {
3754 let block = this.lower_block(block, false);
3755 this.expr_block(block, ThinVec::new())
3760 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3762 if let IsAsync::Async { closure_id, .. } = asyncness {
3763 let outer_decl = FnDecl {
3764 inputs: decl.inputs.clone(),
3765 output: FunctionRetTy::Default(fn_decl_span),
3768 // We need to lower the declaration outside the new scope, because we
3769 // have to conserve the state of being inside a loop condition for the
3770 // closure argument types.
3771 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3773 self.with_new_scopes(|this| {
3774 // FIXME(cramertj) allow `async` non-`move` closures with
3775 if capture_clause == CaptureBy::Ref &&
3776 !decl.inputs.is_empty()
3782 "`async` non-`move` closures with arguments \
3783 are not currently supported",
3785 .help("consider using `let` statements to manually capture \
3786 variables by reference before entering an \
3787 `async move` closure")
3791 // Transform `async |x: u8| -> X { ... }` into
3792 // `|x: u8| future_from_generator(|| -> X { ... })`
3793 let body_id = this.lower_body(Some(&outer_decl), |this| {
3794 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3797 let async_body = this.make_async_expr(
3798 capture_clause, closure_id, async_ret_ty,
3800 this.with_new_scopes(|this| this.lower_expr(body))
3802 this.expr(fn_decl_span, async_body, ThinVec::new())
3804 hir::ExprKind::Closure(
3805 this.lower_capture_clause(capture_clause),
3813 // Lower outside new scope to preserve `is_in_loop_condition`.
3814 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3816 self.with_new_scopes(|this| {
3817 let mut is_generator = false;
3818 let body_id = this.lower_body(Some(decl), |this| {
3819 let e = this.lower_expr(body);
3820 is_generator = this.is_generator;
3823 let generator_option = if is_generator {
3824 if !decl.inputs.is_empty() {
3829 "generators cannot have explicit arguments"
3831 this.sess.abort_if_errors();
3833 Some(match movability {
3834 Movability::Movable => hir::GeneratorMovability::Movable,
3835 Movability::Static => hir::GeneratorMovability::Static,
3838 if movability == Movability::Static {
3843 "closures cannot be static"
3848 hir::ExprKind::Closure(
3849 this.lower_capture_clause(capture_clause),
3858 ExprKind::Block(ref blk, opt_label) => {
3859 hir::ExprKind::Block(self.lower_block(blk,
3860 opt_label.is_some()),
3861 self.lower_label(opt_label))
3863 ExprKind::Assign(ref el, ref er) => {
3864 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3866 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
3867 self.lower_binop(op),
3868 P(self.lower_expr(el)),
3869 P(self.lower_expr(er)),
3871 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
3872 ExprKind::Index(ref el, ref er) => {
3873 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
3875 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3876 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3877 let id = self.next_id();
3878 let e1 = self.lower_expr(e1);
3879 let e2 = self.lower_expr(e2);
3880 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
3881 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
3882 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3883 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3884 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
3885 hir::ExprKind::Call(new, hir_vec![e1, e2])
3887 ExprKind::Range(ref e1, ref e2, lims) => {
3888 use syntax::ast::RangeLimits::*;
3890 let path = match (e1, e2, lims) {
3891 (&None, &None, HalfOpen) => "RangeFull",
3892 (&Some(..), &None, HalfOpen) => "RangeFrom",
3893 (&None, &Some(..), HalfOpen) => "RangeTo",
3894 (&Some(..), &Some(..), HalfOpen) => "Range",
3895 (&None, &Some(..), Closed) => "RangeToInclusive",
3896 (&Some(..), &Some(..), Closed) => unreachable!(),
3897 (_, &None, Closed) => self.diagnostic()
3898 .span_fatal(e.span, "inclusive range with no end")
3902 let fields = e1.iter()
3903 .map(|e| ("start", e))
3904 .chain(e2.iter().map(|e| ("end", e)))
3906 let expr = P(self.lower_expr(&e));
3907 let ident = Ident::new(Symbol::intern(s), e.span);
3908 self.field(ident, expr, e.span)
3910 .collect::<P<[hir::Field]>>();
3912 let is_unit = fields.is_empty();
3913 let struct_path = ["ops", path];
3914 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
3915 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3917 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3923 hir::ExprKind::Path(struct_path)
3925 hir::ExprKind::Struct(struct_path, fields, None)
3928 attrs: e.attrs.clone(),
3931 ExprKind::Path(ref qself, ref path) => {
3932 let qpath = self.lower_qpath(
3936 ParamMode::Optional,
3937 ImplTraitContext::disallowed(),
3939 self.check_self_struct_ctor_feature(&qpath);
3940 hir::ExprKind::Path(qpath)
3942 ExprKind::Break(opt_label, ref opt_expr) => {
3943 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3946 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3949 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3951 hir::ExprKind::Break(
3953 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3956 ExprKind::Continue(opt_label) => {
3957 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
3960 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3963 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3966 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
3967 ExprKind::InlineAsm(ref asm) => {
3968 let hir_asm = hir::InlineAsm {
3969 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3970 outputs: asm.outputs
3972 .map(|out| hir::InlineAsmOutput {
3973 constraint: out.constraint.clone(),
3975 is_indirect: out.is_indirect,
3976 span: out.expr.span,
3979 asm: asm.asm.clone(),
3980 asm_str_style: asm.asm_str_style,
3981 clobbers: asm.clobbers.clone().into(),
3982 volatile: asm.volatile,
3983 alignstack: asm.alignstack,
3984 dialect: asm.dialect,
3987 let outputs = asm.outputs
3989 .map(|out| self.lower_expr(&out.expr))
3991 let inputs = asm.inputs
3993 .map(|&(_, ref input)| self.lower_expr(input))
3995 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
3997 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4002 ParamMode::Optional,
4003 ImplTraitContext::disallowed(),
4005 fields.iter().map(|x| self.lower_field(x)).collect(),
4006 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4008 ExprKind::Paren(ref ex) => {
4009 let mut ex = self.lower_expr(ex);
4010 // include parens in span, but only if it is a super-span.
4011 if e.span.contains(ex.span) {
4014 // merge attributes into the inner expression.
4015 let mut attrs = e.attrs.clone();
4016 attrs.extend::<Vec<_>>(ex.attrs.into());
4021 ExprKind::Yield(ref opt_expr) => {
4022 self.is_generator = true;
4025 .map(|x| self.lower_expr(x))
4027 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
4029 hir::ExprKind::Yield(P(expr))
4032 // Desugar ExprIfLet
4033 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
4034 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4037 // match <sub_expr> {
4039 // _ => [<else_opt> | ()]
4042 let mut arms = vec![];
4044 // `<pat> => <body>`
4046 let body = self.lower_block(body, false);
4047 let body_expr = P(self.expr_block(body, ThinVec::new()));
4048 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4049 arms.push(self.arm(pats, body_expr));
4052 // _ => [<else_opt>|()]
4054 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4055 let wildcard_pattern = self.pat_wild(e.span);
4056 let body = if let Some(else_expr) = wildcard_arm {
4057 P(self.lower_expr(else_expr))
4059 self.expr_tuple(e.span, hir_vec![])
4061 arms.push(self.arm(hir_vec![wildcard_pattern], body));
4064 let contains_else_clause = else_opt.is_some();
4066 let sub_expr = P(self.lower_expr(sub_expr));
4068 hir::ExprKind::Match(
4071 hir::MatchSource::IfLetDesugar {
4072 contains_else_clause,
4077 // Desugar ExprWhileLet
4078 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4079 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4082 // [opt_ident]: loop {
4083 // match <sub_expr> {
4089 // Note that the block AND the condition are evaluated in the loop scope.
4090 // This is done to allow `break` from inside the condition of the loop.
4091 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4093 this.lower_block(body, false),
4094 this.expr_break(e.span, ThinVec::new()),
4095 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4099 // `<pat> => <body>`
4101 let body_expr = P(self.expr_block(body, ThinVec::new()));
4102 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4103 self.arm(pats, body_expr)
4108 let pat_under = self.pat_wild(e.span);
4109 self.arm(hir_vec![pat_under], break_expr)
4112 // `match <sub_expr> { ... }`
4113 let arms = hir_vec![pat_arm, break_arm];
4114 let match_expr = self.expr(
4116 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4120 // `[opt_ident]: loop { ... }`
4121 let loop_block = P(self.block_expr(P(match_expr)));
4122 let loop_expr = hir::ExprKind::Loop(
4124 self.lower_label(opt_label),
4125 hir::LoopSource::WhileLet,
4127 // add attributes to the outer returned expr node
4131 // Desugar ExprForLoop
4132 // From: `[opt_ident]: for <pat> in <head> <body>`
4133 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4137 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4139 // [opt_ident]: loop {
4141 // match ::std::iter::Iterator::next(&mut iter) {
4142 // ::std::option::Option::Some(val) => __next = val,
4143 // ::std::option::Option::None => break
4145 // let <pat> = __next;
4146 // StmtKind::Expr(<body>);
4154 let head = self.lower_expr(head);
4155 let head_sp = head.span;
4156 let desugared_span = self.allow_internal_unstable(
4157 CompilerDesugaringKind::ForLoop,
4161 let iter = self.str_to_ident("iter");
4163 let next_ident = self.str_to_ident("__next");
4164 let next_pat = self.pat_ident_binding_mode(
4167 hir::BindingAnnotation::Mutable,
4170 // `::std::option::Option::Some(val) => next = val`
4172 let val_ident = self.str_to_ident("val");
4173 let val_pat = self.pat_ident(pat.span, val_ident);
4174 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4175 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4176 let assign = P(self.expr(
4178 hir::ExprKind::Assign(next_expr, val_expr),
4181 let some_pat = self.pat_some(pat.span, val_pat);
4182 self.arm(hir_vec![some_pat], assign)
4185 // `::std::option::Option::None => break`
4188 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4189 let pat = self.pat_none(e.span);
4190 self.arm(hir_vec![pat], break_expr)
4194 let iter_pat = self.pat_ident_binding_mode(
4197 hir::BindingAnnotation::Mutable
4200 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4202 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4203 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4204 let next_path = &["iter", "Iterator", "next"];
4205 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4206 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4207 let arms = hir_vec![pat_arm, break_arm];
4211 hir::ExprKind::Match(
4214 hir::MatchSource::ForLoopDesugar
4219 let match_stmt = respan(
4221 hir::StmtKind::Expr(match_expr, self.next_id().node_id)
4224 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4227 let next_let = self.stmt_let_pat(
4231 hir::LocalSource::ForLoopDesugar,
4234 // `let <pat> = __next`
4235 let pat = self.lower_pat(pat);
4236 let pat_let = self.stmt_let_pat(
4240 hir::LocalSource::ForLoopDesugar,
4243 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4244 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4245 let body_stmt = respan(
4247 hir::StmtKind::Expr(body_expr, self.next_id().node_id)
4250 let loop_block = P(self.block_all(
4252 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4256 // `[opt_ident]: loop { ... }`
4257 let loop_expr = hir::ExprKind::Loop(
4259 self.lower_label(opt_label),
4260 hir::LoopSource::ForLoop,
4262 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4263 let loop_expr = P(hir::Expr {
4268 attrs: ThinVec::new(),
4271 // `mut iter => { ... }`
4272 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4274 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4275 let into_iter_expr = {
4276 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4277 let into_iter = P(self.expr_std_path(
4278 head_sp, into_iter_path, None, ThinVec::new()));
4279 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4282 let match_expr = P(self.expr_match(
4286 hir::MatchSource::ForLoopDesugar,
4289 // `{ let _result = ...; _result }`
4290 // underscore prevents an unused_variables lint if the head diverges
4291 let result_ident = self.str_to_ident("_result");
4292 let (let_stmt, let_stmt_binding) =
4293 self.stmt_let(e.span, false, result_ident, match_expr);
4295 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4296 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4297 // add the attributes to the outer returned expr node
4298 return self.expr_block(block, e.attrs.clone());
4301 // Desugar ExprKind::Try
4303 ExprKind::Try(ref sub_expr) => {
4306 // match Try::into_result(<expr>) {
4307 // Ok(val) => #[allow(unreachable_code)] val,
4308 // Err(err) => #[allow(unreachable_code)]
4309 // // If there is an enclosing `catch {...}`
4310 // break 'catch_target Try::from_error(From::from(err)),
4312 // return Try::from_error(From::from(err)),
4316 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4318 // Try::into_result(<expr>)
4321 let sub_expr = self.lower_expr(sub_expr);
4323 let path = &["ops", "Try", "into_result"];
4324 let path = P(self.expr_std_path(
4325 unstable_span, path, None, ThinVec::new()));
4326 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4329 // #[allow(unreachable_code)]
4331 // allow(unreachable_code)
4333 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4334 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4335 let uc_nested = attr::mk_nested_word_item(uc_ident);
4336 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4338 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4340 let attrs = vec![attr];
4342 // Ok(val) => #[allow(unreachable_code)] val,
4344 let val_ident = self.str_to_ident("val");
4345 let val_pat = self.pat_ident(e.span, val_ident);
4346 let val_expr = P(self.expr_ident_with_attrs(
4350 ThinVec::from(attrs.clone()),
4352 let ok_pat = self.pat_ok(e.span, val_pat);
4354 self.arm(hir_vec![ok_pat], val_expr)
4357 // Err(err) => #[allow(unreachable_code)]
4358 // return Try::from_error(From::from(err)),
4360 let err_ident = self.str_to_ident("err");
4361 let err_local = self.pat_ident(e.span, err_ident);
4363 let path = &["convert", "From", "from"];
4364 let from = P(self.expr_std_path(
4365 e.span, path, None, ThinVec::new()));
4366 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4368 self.expr_call(e.span, from, hir_vec![err_expr])
4371 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4372 let thin_attrs = ThinVec::from(attrs);
4373 let catch_scope = self.catch_scopes.last().map(|x| *x);
4374 let ret_expr = if let Some(catch_node) = catch_scope {
4377 hir::ExprKind::Break(
4380 target_id: Ok(catch_node),
4382 Some(from_err_expr),
4387 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4390 let err_pat = self.pat_err(e.span, err_local);
4391 self.arm(hir_vec![err_pat], ret_expr)
4394 hir::ExprKind::Match(
4396 hir_vec![err_arm, ok_arm],
4397 hir::MatchSource::TryDesugar,
4401 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4404 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4411 attrs: e.attrs.clone(),
4415 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
4416 smallvec![match s.node {
4417 StmtKind::Local(ref l) => {
4418 let (l, item_ids) = self.lower_local(l);
4419 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
4421 .map(|item_id| Spanned {
4422 node: hir::StmtKind::Decl(
4424 node: hir::DeclKind::Item(item_id),
4427 self.next_id().node_id,
4433 node: hir::StmtKind::Decl(
4435 node: hir::DeclKind::Local(l),
4438 self.lower_node_id(s.id).node_id,
4444 StmtKind::Item(ref it) => {
4445 // Can only use the ID once.
4446 let mut id = Some(s.id);
4447 return self.lower_item_id(it)
4449 .map(|item_id| Spanned {
4450 node: hir::StmtKind::Decl(
4452 node: hir::DeclKind::Item(item_id),
4456 .map(|id| self.lower_node_id(id).node_id)
4457 .unwrap_or_else(|| self.next_id().node_id),
4463 StmtKind::Expr(ref e) => Spanned {
4464 node: hir::StmtKind::Expr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4467 StmtKind::Semi(ref e) => Spanned {
4468 node: hir::StmtKind::Semi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4471 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4475 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4477 CaptureBy::Value => hir::CaptureByValue,
4478 CaptureBy::Ref => hir::CaptureByRef,
4482 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4483 /// the address space of that item instead of the item currently being
4484 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4485 /// lower a `Visibility` value although we haven't lowered the owning
4486 /// `ImplItem` in question yet.
4487 fn lower_visibility(
4490 explicit_owner: Option<NodeId>,
4491 ) -> hir::Visibility {
4492 let node = match v.node {
4493 VisibilityKind::Public => hir::VisibilityKind::Public,
4494 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4495 VisibilityKind::Restricted { ref path, id } => {
4496 let lowered_id = if let Some(owner) = explicit_owner {
4497 self.lower_node_id_with_owner(id, owner)
4499 self.lower_node_id(id)
4501 hir::VisibilityKind::Restricted {
4502 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4503 id: lowered_id.node_id,
4504 hir_id: lowered_id.hir_id,
4507 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4509 respan(v.span, node)
4512 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4514 Defaultness::Default => hir::Defaultness::Default {
4515 has_value: has_value,
4517 Defaultness::Final => {
4519 hir::Defaultness::Final
4524 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4526 BlockCheckMode::Default => hir::DefaultBlock,
4527 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4531 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4533 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4534 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4535 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4536 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4540 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4542 CompilerGenerated => hir::CompilerGenerated,
4543 UserProvided => hir::UserProvided,
4547 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4549 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4550 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4554 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4556 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4557 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4561 // Helper methods for building HIR.
4563 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4572 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4574 id: self.next_id().node_id,
4578 is_shorthand: false,
4582 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4583 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4584 P(self.expr(span, expr_break, attrs))
4591 args: hir::HirVec<hir::Expr>,
4593 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4596 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4597 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4600 fn expr_ident_with_attrs(
4605 attrs: ThinVec<Attribute>,
4607 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4611 def: Def::Local(binding),
4612 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4616 self.expr(span, expr_path, attrs)
4619 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4620 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4626 components: &[&str],
4627 params: Option<P<hir::GenericArgs>>,
4628 attrs: ThinVec<Attribute>,
4630 let path = self.std_path(span, components, params, true);
4633 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4642 arms: hir::HirVec<hir::Arm>,
4643 source: hir::MatchSource,
4645 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4648 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4649 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4652 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4653 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4656 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4657 let LoweredNodeId { node_id, hir_id } = self.next_id();
4670 ex: Option<P<hir::Expr>>,
4672 source: hir::LocalSource,
4674 let LoweredNodeId { node_id, hir_id } = self.next_id();
4676 let local = P(hir::Local {
4683 attrs: ThinVec::new(),
4686 let decl = respan(sp, hir::DeclKind::Local(local));
4687 respan(sp, hir::StmtKind::Decl(P(decl), self.next_id().node_id))
4696 ) -> (hir::Stmt, NodeId) {
4697 let pat = if mutbl {
4698 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4700 self.pat_ident(sp, ident)
4702 let pat_id = pat.id;
4704 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4709 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4710 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4716 stmts: hir::HirVec<hir::Stmt>,
4717 expr: Option<P<hir::Expr>>,
4719 let LoweredNodeId { node_id, hir_id } = self.next_id();
4726 rules: hir::DefaultBlock,
4728 targeted_by_break: false,
4733 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4734 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4737 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4738 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4741 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4742 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4745 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4746 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4752 components: &[&str],
4753 subpats: hir::HirVec<P<hir::Pat>>,
4755 let path = self.std_path(span, components, None, true);
4756 let qpath = hir::QPath::Resolved(None, P(path));
4757 let pt = if subpats.is_empty() {
4758 hir::PatKind::Path(qpath)
4760 hir::PatKind::TupleStruct(qpath, subpats, None)
4765 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4766 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4769 fn pat_ident_binding_mode(
4773 bm: hir::BindingAnnotation,
4775 let LoweredNodeId { node_id, hir_id } = self.next_id();
4780 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4785 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4786 self.pat(span, hir::PatKind::Wild)
4789 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4790 let LoweredNodeId { node_id, hir_id } = self.next_id();
4799 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4800 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4801 /// The path is also resolved according to `is_value`.
4805 components: &[&str],
4806 params: Option<P<hir::GenericArgs>>,
4810 .resolve_str_path(span, self.crate_root, components, params, is_value)
4813 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4815 let node = match qpath {
4816 hir::QPath::Resolved(None, path) => {
4817 // Turn trait object paths into `TyKind::TraitObject` instead.
4818 if let Def::Trait(_) = path.def {
4819 let principal = hir::PolyTraitRef {
4820 bound_generic_params: hir::HirVec::new(),
4821 trait_ref: hir::TraitRef {
4822 path: path.and_then(|path| path),
4824 hir_ref_id: id.hir_id,
4829 // The original ID is taken by the `PolyTraitRef`,
4830 // so the `Ty` itself needs a different one.
4831 id = self.next_id();
4832 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4834 hir::TyKind::Path(hir::QPath::Resolved(None, path))
4837 _ => hir::TyKind::Path(qpath),
4847 /// Invoked to create the lifetime argument for a type `&T`
4848 /// with no explicit lifetime.
4849 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4850 match self.anonymous_lifetime_mode {
4851 // Intercept when we are in an impl header and introduce an in-band lifetime.
4852 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4854 AnonymousLifetimeMode::CreateParameter => {
4855 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4857 id: self.next_id().node_id,
4859 name: hir::LifetimeName::Param(fresh_name),
4863 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
4865 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4869 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
4870 /// return a "error lifetime".
4871 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
4872 let (id, msg, label) = match id {
4873 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
4876 self.next_id().node_id,
4877 "`&` without an explicit lifetime name cannot be used here",
4878 "explicit lifetime name needed here",
4882 let mut err = struct_span_err!(
4889 err.span_label(span, label);
4892 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
4895 /// Invoked to create the lifetime argument(s) for a path like
4896 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4897 /// sorts of cases are deprecated. This may therefore report a warning or an
4898 /// error, depending on the mode.
4899 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4900 match self.anonymous_lifetime_mode {
4901 // NB. We intentionally ignore the create-parameter mode here
4902 // and instead "pass through" to resolve-lifetimes, which will then
4903 // report an error. This is because we don't want to support
4904 // impl elision for deprecated forms like
4906 // impl Foo for std::cell::Ref<u32> // note lack of '_
4907 AnonymousLifetimeMode::CreateParameter => {}
4909 AnonymousLifetimeMode::ReportError => {
4911 .map(|_| self.new_error_lifetime(None, span))
4915 // This is the normal case.
4916 AnonymousLifetimeMode::PassThrough => {}
4920 .map(|_| self.new_implicit_lifetime(span))
4924 /// Invoked to create the lifetime argument(s) for an elided trait object
4925 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4926 /// when the bound is written, even if it is written with `'_` like in
4927 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4928 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4929 match self.anonymous_lifetime_mode {
4930 // NB. We intentionally ignore the create-parameter mode here.
4931 // and instead "pass through" to resolve-lifetimes, which will apply
4932 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4933 // do not act like other elided lifetimes. In other words, given this:
4935 // impl Foo for Box<dyn Debug>
4937 // we do not introduce a fresh `'_` to serve as the bound, but instead
4938 // ultimately translate to the equivalent of:
4940 // impl Foo for Box<dyn Debug + 'static>
4942 // `resolve_lifetime` has the code to make that happen.
4943 AnonymousLifetimeMode::CreateParameter => {}
4945 AnonymousLifetimeMode::ReportError => {
4946 // ReportError applies to explicit use of `'_`.
4949 // This is the normal case.
4950 AnonymousLifetimeMode::PassThrough => {}
4953 self.new_implicit_lifetime(span)
4956 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4958 id: self.next_id().node_id,
4960 name: hir::LifetimeName::Implicit,
4964 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4965 self.sess.buffer_lint_with_diagnostic(
4966 builtin::BARE_TRAIT_OBJECTS,
4969 "trait objects without an explicit `dyn` are deprecated",
4970 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4974 fn wrap_in_try_constructor(
4976 method: &'static str,
4978 unstable_span: Span,
4980 let path = &["ops", "Try", method];
4981 let from_err = P(self.expr_std_path(unstable_span, path, None,
4983 P(self.expr_call(e.span, from_err, hir_vec![e]))
4986 fn check_self_struct_ctor_feature(&self, qp: &hir::QPath) {
4987 if let hir::QPath::Resolved(_, ref p) = qp {
4988 if p.segments.len() == 1 &&
4989 p.segments[0].ident.name == keywords::SelfType.name() &&
4990 !self.sess.features_untracked().self_struct_ctor {
4991 emit_feature_err(&self.sess.parse_sess, "self_struct_ctor",
4992 p.span, GateIssue::Language,
4993 "`Self` struct constructors are unstable");
4999 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5000 // Sorting by span ensures that we get things in order within a
5001 // file, and also puts the files in a sensible order.
5002 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5003 body_ids.sort_by_key(|b| bodies[b].value.span);