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::small_vec::OneVector;
56 use rustc_data_structures::thin_vec::ThinVec;
58 use util::common::FN_OUTPUT_NAME;
59 use util::nodemap::{DefIdMap, NodeMap};
61 use std::collections::BTreeMap;
69 use syntax::ext::hygiene::{Mark, SyntaxContext};
70 use syntax::print::pprust;
72 use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned};
73 use syntax::std_inject;
74 use syntax::symbol::{keywords, Symbol};
75 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
76 use syntax::parse::token::Token;
77 use syntax::visit::{self, Visitor};
78 use syntax_pos::{Span, MultiSpan};
80 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
82 pub struct LoweringContext<'a> {
83 crate_root: Option<&'static str>,
85 // Use to assign ids to hir nodes that do not directly correspond to an ast node
88 cstore: &'a dyn CrateStore,
90 resolver: &'a mut dyn Resolver,
92 /// The items being lowered are collected here.
93 items: BTreeMap<NodeId, hir::Item>,
95 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
96 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
97 bodies: BTreeMap<hir::BodyId, hir::Body>,
98 exported_macros: Vec<hir::MacroDef>,
100 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
101 trait_auto_impl: BTreeMap<DefId, NodeId>,
105 catch_scopes: Vec<NodeId>,
106 loop_scopes: Vec<NodeId>,
107 is_in_loop_condition: bool,
108 is_in_trait_impl: bool,
110 /// What to do when we encounter either an "anonymous lifetime
111 /// reference". The term "anonymous" is meant to encompass both
112 /// `'_` lifetimes as well as fully elided cases where nothing is
113 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
114 anonymous_lifetime_mode: AnonymousLifetimeMode,
116 // Used to create lifetime definitions from in-band lifetime usages.
117 // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
118 // When a named lifetime is encountered in a function or impl header and
119 // has not been defined
120 // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
121 // to this list. The results of this list are then added to the list of
122 // lifetime definitions in the corresponding impl or function generics.
123 lifetimes_to_define: Vec<(Span, ParamName)>,
125 // Whether or not in-band lifetimes are being collected. This is used to
126 // indicate whether or not we're in a place where new lifetimes will result
127 // in in-band lifetime definitions, such a function or an impl header.
128 // This will always be false unless the `in_band_lifetimes` or
129 // `impl_header_lifetime_elision` feature is enabled.
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 universal existential parameter.
181 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
182 /// equivalent to a fresh existential parameter like `abstract type T; fn foo() -> T`.
184 /// We store a DefId here so we can look up necessary information later
187 /// `impl Trait` is not accepted in this position.
191 impl<'a> ImplTraitContext<'a> {
192 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
193 use self::ImplTraitContext::*;
195 Universal(params) => Universal(params),
196 Existential(did) => Existential(*did),
197 Disallowed => Disallowed,
204 cstore: &dyn CrateStore,
205 dep_graph: &DepGraph,
207 resolver: &mut dyn Resolver,
209 // We're constructing the HIR here; we don't care what we will
210 // read, since we haven't even constructed the *input* to
212 dep_graph.assert_ignored();
215 crate_root: std_inject::injected_crate_name(),
219 items: BTreeMap::new(),
220 trait_items: BTreeMap::new(),
221 impl_items: BTreeMap::new(),
222 bodies: BTreeMap::new(),
223 trait_impls: BTreeMap::new(),
224 trait_auto_impl: BTreeMap::new(),
225 exported_macros: Vec::new(),
226 catch_scopes: Vec::new(),
227 loop_scopes: Vec::new(),
228 is_in_loop_condition: false,
229 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
230 type_def_lifetime_params: DefIdMap(),
231 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
232 item_local_id_counters: NodeMap(),
233 node_id_to_hir_id: IndexVec::new(),
235 is_in_trait_impl: false,
236 lifetimes_to_define: Vec::new(),
237 is_collecting_in_band_lifetimes: false,
238 in_scope_lifetimes: Vec::new(),
242 #[derive(Copy, Clone, PartialEq)]
244 /// Any path in a type context.
246 /// The `module::Type` in `module::Type::method` in an expression.
251 struct LoweredNodeId {
256 enum ParenthesizedGenericArgs {
262 /// What to do when we encounter an **anonymous** lifetime
263 /// reference. Anonymous lifetime references come in two flavors. You
264 /// have implicit, or fully elided, references to lifetimes, like the
265 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
266 /// or `Ref<'_, T>`. These often behave the same, but not always:
268 /// - certain usages of implicit references are deprecated, like
269 /// `Ref<T>`, and we sometimes just give hard errors in those cases
271 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
272 /// the same as `Box<dyn Foo + '_>`.
274 /// We describe the effects of the various modes in terms of three cases:
276 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
277 /// of a `&` (e.g., the missing lifetime in something like `&T`)
278 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
279 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
280 /// elided bounds follow special rules. Note that this only covers
281 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
282 /// '_>` is a case of "modern" elision.
283 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
284 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
285 /// non-deprecated equivalent.
287 /// Currently, the handling of lifetime elision is somewhat spread out
288 /// between HIR lowering and -- as described below -- the
289 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
290 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
291 /// everything into HIR lowering.
292 #[derive(Copy, Clone)]
293 enum AnonymousLifetimeMode {
294 /// For **Modern** cases, create a new anonymous region parameter
295 /// and reference that.
297 /// For **Dyn Bound** cases, pass responsibility to
298 /// `resolve_lifetime` code.
300 /// For **Deprecated** cases, report an error.
303 /// Pass responsibility to `resolve_lifetime` code for all cases.
307 impl<'a> LoweringContext<'a> {
308 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
309 /// Full-crate AST visitor that inserts into a fresh
310 /// `LoweringContext` any information that may be
311 /// needed from arbitrary locations in the crate.
312 /// E.g. The number of lifetime generic parameters
313 /// declared for every type and trait definition.
314 struct MiscCollector<'lcx, 'interner: 'lcx> {
315 lctx: &'lcx mut LoweringContext<'interner>,
318 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
319 fn visit_item(&mut self, item: &'lcx Item) {
320 self.lctx.allocate_hir_id_counter(item.id, item);
323 ItemKind::Struct(_, ref generics)
324 | ItemKind::Union(_, ref generics)
325 | ItemKind::Enum(_, ref generics)
326 | ItemKind::Ty(_, ref generics)
327 | ItemKind::Existential(_, ref generics)
328 | ItemKind::Trait(_, _, ref generics, ..) => {
329 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
333 .filter(|param| match param.kind {
334 ast::GenericParamKind::Lifetime { .. } => true,
338 self.lctx.type_def_lifetime_params.insert(def_id, count);
342 visit::walk_item(self, item);
345 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
346 self.lctx.allocate_hir_id_counter(item.id, item);
347 visit::walk_trait_item(self, item);
350 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
351 self.lctx.allocate_hir_id_counter(item.id, item);
352 visit::walk_impl_item(self, item);
356 struct ItemLowerer<'lcx, 'interner: 'lcx> {
357 lctx: &'lcx mut LoweringContext<'interner>,
360 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
361 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
363 F: FnOnce(&mut Self),
365 let old = self.lctx.is_in_trait_impl;
366 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
372 self.lctx.is_in_trait_impl = old;
376 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
377 fn visit_item(&mut self, item: &'lcx Item) {
378 let mut item_lowered = true;
379 self.lctx.with_hir_id_owner(item.id, |lctx| {
380 if let Some(hir_item) = lctx.lower_item(item) {
381 lctx.items.insert(item.id, hir_item);
383 item_lowered = false;
388 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
389 hir::ItemKind::Impl(_, _, _, ref generics, ..)
390 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
391 generics.params.clone()
396 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
397 let this = &mut ItemLowerer { lctx: this };
398 if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
399 this.with_trait_impl_ref(opt_trait_ref, |this| {
400 visit::walk_item(this, item)
403 visit::walk_item(this, item);
409 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
410 self.lctx.with_hir_id_owner(item.id, |lctx| {
411 let id = hir::TraitItemId { node_id: item.id };
412 let hir_item = lctx.lower_trait_item(item);
413 lctx.trait_items.insert(id, hir_item);
416 visit::walk_trait_item(self, item);
419 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
420 self.lctx.with_hir_id_owner(item.id, |lctx| {
421 let id = hir::ImplItemId { node_id: item.id };
422 let hir_item = lctx.lower_impl_item(item);
423 lctx.impl_items.insert(id, hir_item);
425 visit::walk_impl_item(self, item);
429 self.lower_node_id(CRATE_NODE_ID);
430 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
432 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
433 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
435 let module = self.lower_mod(&c.module);
436 let attrs = self.lower_attrs(&c.attrs);
437 let body_ids = body_ids(&self.bodies);
441 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
447 exported_macros: hir::HirVec::from(self.exported_macros),
449 trait_items: self.trait_items,
450 impl_items: self.impl_items,
453 trait_impls: self.trait_impls,
454 trait_auto_impl: self.trait_auto_impl,
458 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
459 if self.item_local_id_counters.insert(owner, 0).is_some() {
461 "Tried to allocate item_local_id_counter for {:?} twice",
465 // Always allocate the first HirId for the owner itself
466 self.lower_node_id_with_owner(owner, owner)
469 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
471 F: FnOnce(&mut Self) -> hir::HirId,
473 if ast_node_id == DUMMY_NODE_ID {
474 return LoweredNodeId {
475 node_id: DUMMY_NODE_ID,
476 hir_id: hir::DUMMY_HIR_ID,
480 let min_size = ast_node_id.as_usize() + 1;
482 if min_size > self.node_id_to_hir_id.len() {
483 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
486 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
488 if existing_hir_id == hir::DUMMY_HIR_ID {
489 // Generate a new HirId
490 let hir_id = alloc_hir_id(self);
491 self.node_id_to_hir_id[ast_node_id] = hir_id;
493 node_id: ast_node_id,
498 node_id: ast_node_id,
499 hir_id: existing_hir_id,
504 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
506 F: FnOnce(&mut Self) -> T,
508 let counter = self.item_local_id_counters
509 .insert(owner, HIR_ID_COUNTER_LOCKED)
510 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
511 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
512 self.current_hir_id_owner.push((def_index, counter));
514 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
516 debug_assert!(def_index == new_def_index);
517 debug_assert!(new_counter >= counter);
519 let prev = self.item_local_id_counters
520 .insert(owner, new_counter)
522 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
526 /// This method allocates a new HirId for the given NodeId and stores it in
527 /// the LoweringContext's NodeId => HirId map.
528 /// Take care not to call this method if the resulting HirId is then not
529 /// actually used in the HIR, as that would trigger an assertion in the
530 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
531 /// properly. Calling the method twice with the same NodeId is fine though.
532 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
533 self.lower_node_id_generic(ast_node_id, |this| {
534 let &mut (def_index, ref mut local_id_counter) =
535 this.current_hir_id_owner.last_mut().unwrap();
536 let local_id = *local_id_counter;
537 *local_id_counter += 1;
540 local_id: hir::ItemLocalId(local_id),
545 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
546 self.lower_node_id_generic(ast_node_id, |this| {
547 let local_id_counter = this
548 .item_local_id_counters
550 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
551 let local_id = *local_id_counter;
553 // We want to be sure not to modify the counter in the map while it
554 // is also on the stack. Otherwise we'll get lost updates when writing
555 // back from the stack to the map.
556 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
558 *local_id_counter += 1;
562 .opt_def_index(owner)
563 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
564 that do not belong to the current owner");
568 local_id: hir::ItemLocalId(local_id),
573 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
574 let body = hir::Body {
575 arguments: decl.map_or(hir_vec![], |decl| {
576 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
578 is_generator: self.is_generator,
582 self.bodies.insert(id, body);
586 fn next_id(&mut self) -> LoweredNodeId {
587 self.lower_node_id(self.sess.next_node_id())
590 fn expect_full_def(&mut self, id: NodeId) -> Def {
591 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
592 if pr.unresolved_segments() != 0 {
593 bug!("path not fully resolved: {:?}", pr);
599 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item=Def> {
600 self.resolver.get_import(id).present_items().map(|pr| {
601 if pr.unresolved_segments() != 0 {
602 bug!("path not fully resolved: {:?}", pr);
608 fn diagnostic(&self) -> &errors::Handler {
609 self.sess.diagnostic()
612 fn str_to_ident(&self, s: &'static str) -> Ident {
613 Ident::with_empty_ctxt(Symbol::gensym(s))
616 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
617 let mark = Mark::fresh(Mark::root());
618 mark.set_expn_info(source_map::ExpnInfo {
620 def_site: Some(span),
621 format: source_map::CompilerDesugaring(reason),
622 allow_internal_unstable: true,
623 allow_internal_unsafe: false,
624 local_inner_macros: false,
625 edition: source_map::hygiene::default_edition(),
627 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
630 fn with_anonymous_lifetime_mode<R>(
632 anonymous_lifetime_mode: AnonymousLifetimeMode,
633 op: impl FnOnce(&mut Self) -> R,
635 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
636 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
637 let result = op(self);
638 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
642 /// Creates a new hir::GenericParam for every new lifetime and
643 /// type parameter encountered while evaluating `f`. Definitions
644 /// are created with the parent provided. If no `parent_id` is
645 /// provided, no definitions will be returned.
647 /// Presuming that in-band lifetimes are enabled, then
648 /// `self.anonymous_lifetime_mode` will be updated to match the
649 /// argument while `f` is running (and restored afterwards).
650 fn collect_in_band_defs<T, F>(
653 anonymous_lifetime_mode: AnonymousLifetimeMode,
655 ) -> (Vec<hir::GenericParam>, T)
657 F: FnOnce(&mut LoweringContext) -> (Vec<hir::GenericParam>, T),
659 assert!(!self.is_collecting_in_band_lifetimes);
660 assert!(self.lifetimes_to_define.is_empty());
661 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
663 if self.sess.features_untracked().impl_header_lifetime_elision {
664 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
665 self.is_collecting_in_band_lifetimes = true;
666 } else if self.sess.features_untracked().in_band_lifetimes {
667 self.is_collecting_in_band_lifetimes = true;
670 let (in_band_ty_params, res) = f(self);
672 self.is_collecting_in_band_lifetimes = false;
673 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
675 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
677 let params = lifetimes_to_define
679 .map(|(span, hir_name)| {
680 let def_node_id = self.next_id().node_id;
682 // Get the name we'll use to make the def-path. Note
683 // that collisions are ok here and this shouldn't
684 // really show up for end-user.
685 let str_name = match hir_name {
686 ParamName::Plain(ident) => ident.as_interned_str(),
687 ParamName::Fresh(_) => keywords::UnderscoreLifetime.name().as_interned_str(),
690 // Add a definition for the in-band lifetime def
691 self.resolver.definitions().create_def_with_parent(
694 DefPathData::LifetimeParam(str_name),
695 DefIndexAddressSpace::High,
706 pure_wrt_drop: false,
707 kind: hir::GenericParamKind::Lifetime { in_band: true }
710 .chain(in_band_ty_params.into_iter())
716 /// When there is a reference to some lifetime `'a`, and in-band
717 /// lifetimes are enabled, then we want to push that lifetime into
718 /// the vector of names to define later. In that case, it will get
719 /// added to the appropriate generics.
720 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
721 if !self.is_collecting_in_band_lifetimes {
725 if !self.sess.features_untracked().in_band_lifetimes {
729 if self.in_scope_lifetimes.contains(&ident.modern()) {
733 let hir_name = ParamName::Plain(ident);
735 if self.lifetimes_to_define.iter()
736 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
740 self.lifetimes_to_define.push((ident.span, hir_name));
743 /// When we have either an elided or `'_` lifetime in an impl
744 /// header, we convert it to
745 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
746 assert!(self.is_collecting_in_band_lifetimes);
747 let index = self.lifetimes_to_define.len();
748 let hir_name = ParamName::Fresh(index);
749 self.lifetimes_to_define.push((span, hir_name));
753 // Evaluates `f` with the lifetimes in `params` in-scope.
754 // This is used to track which lifetimes have already been defined, and
755 // which are new in-band lifetimes that need to have a definition created
757 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
759 F: FnOnce(&mut LoweringContext) -> T,
761 let old_len = self.in_scope_lifetimes.len();
762 let lt_def_names = params.iter().filter_map(|param| match param.kind {
763 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
766 self.in_scope_lifetimes.extend(lt_def_names);
770 self.in_scope_lifetimes.truncate(old_len);
774 // Same as the method above, but accepts `hir::GenericParam`s
775 // instead of `ast::GenericParam`s.
776 // This should only be used with generics that have already had their
777 // in-band lifetimes added. In practice, this means that this function is
778 // only used when lowering a child item of a trait or impl.
779 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
780 params: &HirVec<hir::GenericParam>,
783 F: FnOnce(&mut LoweringContext) -> T,
785 let old_len = self.in_scope_lifetimes.len();
786 let lt_def_names = params.iter().filter_map(|param| match param.kind {
787 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
790 self.in_scope_lifetimes.extend(lt_def_names);
794 self.in_scope_lifetimes.truncate(old_len);
798 /// Appends in-band lifetime defs and argument-position `impl
799 /// Trait` defs to the existing set of generics.
801 /// Presuming that in-band lifetimes are enabled, then
802 /// `self.anonymous_lifetime_mode` will be updated to match the
803 /// argument while `f` is running (and restored afterwards).
804 fn add_in_band_defs<F, T>(
808 anonymous_lifetime_mode: AnonymousLifetimeMode,
810 ) -> (hir::Generics, T)
812 F: FnOnce(&mut LoweringContext, &mut Vec<hir::GenericParam>) -> T,
814 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
817 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
818 let mut params = Vec::new();
819 let generics = this.lower_generics(
821 ImplTraitContext::Universal(&mut params),
823 let res = f(this, &mut params);
824 (params, (generics, res))
829 lowered_generics.params = lowered_generics
836 (lowered_generics, res)
839 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
841 F: FnOnce(&mut LoweringContext) -> T,
843 let len = self.catch_scopes.len();
844 self.catch_scopes.push(catch_id);
846 let result = f(self);
849 self.catch_scopes.len(),
850 "catch scopes should be added and removed in stack order"
853 self.catch_scopes.pop().unwrap();
860 capture_clause: CaptureBy,
861 closure_node_id: NodeId,
863 body: impl FnOnce(&mut LoweringContext) -> hir::Expr,
865 let prev_is_generator = mem::replace(&mut self.is_generator, true);
866 let body_expr = body(self);
867 let span = body_expr.span;
868 let output = match ret_ty {
869 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
870 None => FunctionRetTy::Default(span),
877 let body_id = self.record_body(body_expr, Some(&decl));
878 self.is_generator = prev_is_generator;
880 let capture_clause = self.lower_capture_clause(capture_clause);
881 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
882 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
883 let generator = hir::Expr {
885 hir_id: closure_hir_id,
886 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
887 Some(hir::GeneratorMovability::Static)),
889 attrs: ThinVec::new(),
892 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
893 let gen_future = self.expr_std_path(
894 unstable_span, &["future", "from_generator"], None, ThinVec::new());
895 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
898 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
900 F: FnOnce(&mut LoweringContext) -> hir::Expr,
902 let prev = mem::replace(&mut self.is_generator, false);
903 let result = f(self);
904 let r = self.record_body(result, decl);
905 self.is_generator = prev;
909 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
911 F: FnOnce(&mut LoweringContext) -> T,
913 // We're no longer in the base loop's condition; we're in another loop.
914 let was_in_loop_condition = self.is_in_loop_condition;
915 self.is_in_loop_condition = false;
917 let len = self.loop_scopes.len();
918 self.loop_scopes.push(loop_id);
920 let result = f(self);
923 self.loop_scopes.len(),
924 "Loop scopes should be added and removed in stack order"
927 self.loop_scopes.pop().unwrap();
929 self.is_in_loop_condition = was_in_loop_condition;
934 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
936 F: FnOnce(&mut LoweringContext) -> T,
938 let was_in_loop_condition = self.is_in_loop_condition;
939 self.is_in_loop_condition = true;
941 let result = f(self);
943 self.is_in_loop_condition = was_in_loop_condition;
948 fn with_new_scopes<T, F>(&mut self, f: F) -> T
950 F: FnOnce(&mut LoweringContext) -> T,
952 let was_in_loop_condition = self.is_in_loop_condition;
953 self.is_in_loop_condition = false;
955 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
956 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
957 let result = f(self);
958 self.catch_scopes = catch_scopes;
959 self.loop_scopes = loop_scopes;
961 self.is_in_loop_condition = was_in_loop_condition;
966 fn def_key(&mut self, id: DefId) -> DefKey {
968 self.resolver.definitions().def_key(id.index)
970 self.cstore.def_key(id)
974 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
975 label.map(|label| hir::Label {
980 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
981 let target_id = match destination {
983 if let Def::Label(loop_id) = self.expect_full_def(id) {
984 Ok(self.lower_node_id(loop_id).node_id)
986 Err(hir::LoopIdError::UnresolvedLabel)
992 .map(|innermost_loop_id| *innermost_loop_id)
993 .map(|id| Ok(self.lower_node_id(id).node_id))
994 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
999 label: self.lower_label(destination.map(|(_, label)| label)),
1004 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1007 .map(|a| self.lower_attr(a))
1008 .collect::<Vec<_>>()
1012 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1016 path: attr.path.clone(),
1017 tokens: self.lower_token_stream(attr.tokens.clone()),
1018 is_sugared_doc: attr.is_sugared_doc,
1023 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1026 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1030 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1032 TokenTree::Token(span, token) => self.lower_token(token, span),
1033 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1036 delim: delimited.delim,
1037 tts: self.lower_token_stream(delimited.tts.into()).into(),
1043 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1045 Token::Interpolated(_) => {}
1046 other => return TokenTree::Token(span, other).into(),
1049 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1050 self.lower_token_stream(tts)
1053 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1055 attrs: self.lower_attrs(&arm.attrs),
1056 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1057 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1058 body: P(self.lower_expr(&arm.body)),
1062 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1064 id: self.lower_node_id(b.id).node_id,
1066 ty: self.lower_ty(&b.ty, itctx),
1071 fn lower_generic_arg(&mut self,
1072 arg: &ast::GenericArg,
1073 itctx: ImplTraitContext)
1074 -> hir::GenericArg {
1076 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1077 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1081 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1082 P(self.lower_ty_direct(t, itctx))
1085 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext) -> hir::Ty {
1086 let kind = match t.node {
1087 TyKind::Infer => hir::TyKind::Infer,
1088 TyKind::Err => hir::TyKind::Err,
1089 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1090 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1091 TyKind::Rptr(ref region, ref mt) => {
1092 let span = t.span.shrink_to_lo();
1093 let lifetime = match *region {
1094 Some(ref lt) => self.lower_lifetime(lt),
1095 None => self.elided_ref_lifetime(span),
1097 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1099 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1102 this.with_anonymous_lifetime_mode(
1103 AnonymousLifetimeMode::PassThrough,
1105 hir::TyKind::BareFn(P(hir::BareFnTy {
1106 generic_params: this.lower_generic_params(
1109 ImplTraitContext::Disallowed,
1111 unsafety: this.lower_unsafety(f.unsafety),
1113 decl: this.lower_fn_decl(&f.decl, None, false, None),
1114 arg_names: this.lower_fn_args_to_names(&f.decl),
1120 TyKind::Never => hir::TyKind::Never,
1121 TyKind::Tup(ref tys) => {
1122 hir::TyKind::Tup(tys.iter().map(|ty| {
1123 self.lower_ty_direct(ty, itctx.reborrow())
1126 TyKind::Paren(ref ty) => {
1127 return self.lower_ty_direct(ty, itctx);
1129 TyKind::Path(ref qself, ref path) => {
1130 let id = self.lower_node_id(t.id);
1131 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1132 let ty = self.ty_path(id, t.span, qpath);
1133 if let hir::TyKind::TraitObject(..) = ty.node {
1134 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1138 TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1141 def: self.expect_full_def(t.id),
1142 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1146 TyKind::Array(ref ty, ref length) => {
1147 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1149 TyKind::Typeof(ref expr) => {
1150 hir::TyKind::Typeof(self.lower_anon_const(expr))
1152 TyKind::TraitObject(ref bounds, kind) => {
1153 let mut lifetime_bound = None;
1156 .filter_map(|bound| match *bound {
1157 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1158 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1160 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1161 GenericBound::Outlives(ref lifetime) => {
1162 if lifetime_bound.is_none() {
1163 lifetime_bound = Some(self.lower_lifetime(lifetime));
1169 let lifetime_bound =
1170 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1171 if kind != TraitObjectSyntax::Dyn {
1172 self.maybe_lint_bare_trait(t.span, t.id, false);
1174 hir::TyKind::TraitObject(bounds, lifetime_bound)
1176 TyKind::ImplTrait(def_node_id, ref bounds) => {
1179 ImplTraitContext::Existential(fn_def_id) => {
1180 self.lower_existential_impl_trait(
1181 span, fn_def_id, def_node_id,
1182 |this| this.lower_param_bounds(bounds, itctx),
1185 ImplTraitContext::Universal(in_band_ty_params) => {
1186 self.lower_node_id(def_node_id);
1187 // Add a definition for the in-band Param
1188 let def_index = self
1191 .opt_def_index(def_node_id)
1194 let hir_bounds = self.lower_param_bounds(
1196 ImplTraitContext::Universal(in_band_ty_params),
1198 // Set the name to `impl Bound1 + Bound2`
1199 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1200 in_band_ty_params.push(hir::GenericParam {
1202 name: ParamName::Plain(ident),
1203 pure_wrt_drop: false,
1207 kind: hir::GenericParamKind::Type {
1209 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1213 hir::TyKind::Path(hir::QPath::Resolved(
1217 def: Def::TyParam(DefId::local(def_index)),
1218 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1222 ImplTraitContext::Disallowed => {
1227 "`impl Trait` not allowed outside of function \
1228 and inherent method return types"
1234 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1237 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1246 fn lower_existential_impl_trait(
1250 exist_ty_node_id: NodeId,
1251 lower_bounds: impl FnOnce(&mut LoweringContext) -> hir::GenericBounds,
1253 // Make sure we know that some funky desugaring has been going on here.
1254 // This is a first: there is code in other places like for loop
1255 // desugaring that explicitly states that we don't want to track that.
1256 // Not tracking it makes lints in rustc and clippy very fragile as
1257 // frequently opened issues show.
1258 let exist_ty_span = self.allow_internal_unstable(
1259 CompilerDesugaringKind::ExistentialReturnType,
1263 let exist_ty_def_index = self
1266 .opt_def_index(exist_ty_node_id)
1270 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1272 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1274 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1280 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1281 let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1282 generics: hir::Generics {
1283 params: lifetime_defs,
1284 where_clause: hir::WhereClause {
1285 id: lctx.next_id().node_id,
1286 predicates: Vec::new().into(),
1291 impl_trait_fn: Some(fn_def_id),
1293 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1294 // Generate an `existential type Foo: Trait;` declaration
1295 trace!("creating existential type with id {:#?}", exist_ty_id);
1297 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1298 let exist_ty_item = hir::Item {
1299 id: exist_ty_id.node_id,
1300 hir_id: exist_ty_id.hir_id,
1301 name: keywords::Invalid.name(),
1302 attrs: Default::default(),
1303 node: exist_ty_item_kind,
1304 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1305 span: exist_ty_span,
1308 // Insert the item into the global list. This usually happens
1309 // automatically for all AST items. But this existential type item
1310 // does not actually exist in the AST.
1311 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1313 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1314 let path = P(hir::Path {
1315 span: exist_ty_span,
1316 def: Def::Existential(DefId::local(exist_ty_def_index)),
1317 segments: hir_vec![hir::PathSegment {
1319 ident: Ident::new(keywords::Invalid.name(), exist_ty_span),
1320 args: Some(P(hir::GenericArgs {
1321 parenthesized: false,
1322 bindings: HirVec::new(),
1327 hir::TyKind::Path(hir::QPath::Resolved(None, path))
1331 fn lifetimes_from_impl_trait_bounds(
1333 exist_ty_id: NodeId,
1334 parent_index: DefIndex,
1335 bounds: &hir::GenericBounds,
1336 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1337 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1338 // appear in the bounds, excluding lifetimes that are created within the bounds.
1339 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1340 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1341 context: &'r mut LoweringContext<'a>,
1343 exist_ty_id: NodeId,
1344 collect_elided_lifetimes: bool,
1345 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1346 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1347 output_lifetimes: Vec<hir::GenericArg>,
1348 output_lifetime_params: Vec<hir::GenericParam>,
1351 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1352 fn nested_visit_map<'this>(
1354 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1355 hir::intravisit::NestedVisitorMap::None
1358 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1359 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1360 if parameters.parenthesized {
1361 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1362 self.collect_elided_lifetimes = false;
1363 hir::intravisit::walk_generic_args(self, span, parameters);
1364 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1366 hir::intravisit::walk_generic_args(self, span, parameters);
1370 fn visit_ty(&mut self, t: &'v hir::Ty) {
1371 // Don't collect elided lifetimes used inside of `fn()` syntax
1372 if let hir::TyKind::BareFn(_) = t.node {
1373 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1374 self.collect_elided_lifetimes = false;
1376 // Record the "stack height" of `for<'a>` lifetime bindings
1377 // to be able to later fully undo their introduction.
1378 let old_len = self.currently_bound_lifetimes.len();
1379 hir::intravisit::walk_ty(self, t);
1380 self.currently_bound_lifetimes.truncate(old_len);
1382 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1384 hir::intravisit::walk_ty(self, t)
1388 fn visit_poly_trait_ref(
1390 trait_ref: &'v hir::PolyTraitRef,
1391 modifier: hir::TraitBoundModifier,
1393 // Record the "stack height" of `for<'a>` lifetime bindings
1394 // to be able to later fully undo their introduction.
1395 let old_len = self.currently_bound_lifetimes.len();
1396 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1397 self.currently_bound_lifetimes.truncate(old_len);
1400 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1401 // Record the introduction of 'a in `for<'a> ...`
1402 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1403 // Introduce lifetimes one at a time so that we can handle
1404 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1405 let lt_name = hir::LifetimeName::Param(param.name);
1406 self.currently_bound_lifetimes.push(lt_name);
1409 hir::intravisit::walk_generic_param(self, param);
1412 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1413 let name = match lifetime.name {
1414 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1415 if self.collect_elided_lifetimes {
1416 // Use `'_` for both implicit and underscore lifetimes in
1417 // `abstract type Foo<'_>: SomeTrait<'_>;`
1418 hir::LifetimeName::Underscore
1423 hir::LifetimeName::Param(_) => lifetime.name,
1424 hir::LifetimeName::Static => return,
1427 if !self.currently_bound_lifetimes.contains(&name)
1428 && !self.already_defined_lifetimes.contains(&name) {
1429 self.already_defined_lifetimes.insert(name);
1431 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1432 id: self.context.next_id().node_id,
1433 span: lifetime.span,
1437 // We need to manually create the ids here, because the
1438 // definitions will go into the explicit `existential type`
1439 // declaration and thus need to have their owner set to that item
1440 let def_node_id = self.context.sess.next_node_id();
1441 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1442 self.context.resolver.definitions().create_def_with_parent(
1445 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1446 DefIndexAddressSpace::High,
1451 let name = match name {
1452 hir::LifetimeName::Underscore => {
1453 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident())
1455 hir::LifetimeName::Param(param_name) => param_name,
1456 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1459 self.output_lifetime_params.push(hir::GenericParam {
1462 span: lifetime.span,
1463 pure_wrt_drop: false,
1466 kind: hir::GenericParamKind::Lifetime {
1474 let mut lifetime_collector = ImplTraitLifetimeCollector {
1476 parent: parent_index,
1478 collect_elided_lifetimes: true,
1479 currently_bound_lifetimes: Vec::new(),
1480 already_defined_lifetimes: FxHashSet::default(),
1481 output_lifetimes: Vec::new(),
1482 output_lifetime_params: Vec::new(),
1485 for bound in bounds {
1486 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1490 lifetime_collector.output_lifetimes.into(),
1491 lifetime_collector.output_lifetime_params.into(),
1495 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1500 .map(|x| self.lower_foreign_item(x))
1505 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1512 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1514 node: hir::VariantKind {
1515 name: v.node.ident.name,
1516 attrs: self.lower_attrs(&v.node.attrs),
1517 data: self.lower_variant_data(&v.node.data),
1518 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1527 qself: &Option<QSelf>,
1529 param_mode: ParamMode,
1530 mut itctx: ImplTraitContext,
1532 let qself_position = qself.as_ref().map(|q| q.position);
1533 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1535 let resolution = self.resolver
1537 .unwrap_or(PathResolution::new(Def::Err));
1539 let proj_start = p.segments.len() - resolution.unresolved_segments();
1540 let path = P(hir::Path {
1541 def: resolution.base_def(),
1542 segments: p.segments[..proj_start]
1545 .map(|(i, segment)| {
1546 let param_mode = match (qself_position, param_mode) {
1547 (Some(j), ParamMode::Optional) if i < j => {
1548 // This segment is part of the trait path in a
1549 // qualified path - one of `a`, `b` or `Trait`
1550 // in `<X as a::b::Trait>::T::U::method`.
1556 // Figure out if this is a type/trait segment,
1557 // which may need lifetime elision performed.
1558 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1559 krate: def_id.krate,
1560 index: this.def_key(def_id).parent.expect("missing parent"),
1562 let type_def_id = match resolution.base_def() {
1563 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1564 Some(parent_def_id(self, def_id))
1566 Def::Variant(def_id) if i + 1 == proj_start => {
1567 Some(parent_def_id(self, def_id))
1570 | Def::Union(def_id)
1572 | Def::TyAlias(def_id)
1573 | Def::Trait(def_id) if i + 1 == proj_start =>
1579 let parenthesized_generic_args = match resolution.base_def() {
1580 // `a::b::Trait(Args)`
1581 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1582 // `a::b::Trait(Args)::TraitItem`
1583 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1584 if i + 2 == proj_start =>
1586 ParenthesizedGenericArgs::Ok
1588 // Avoid duplicated errors
1589 Def::Err => ParenthesizedGenericArgs::Ok,
1595 | Def::Variant(..) if i + 1 == proj_start =>
1597 ParenthesizedGenericArgs::Err
1599 // A warning for now, for compatibility reasons
1600 _ => ParenthesizedGenericArgs::Warn,
1603 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1604 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1607 assert!(!def_id.is_local());
1609 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1610 let n = item_generics.own_counts().lifetimes;
1611 self.type_def_lifetime_params.insert(def_id, n);
1614 self.lower_path_segment(
1619 parenthesized_generic_args,
1627 // Simple case, either no projections, or only fully-qualified.
1628 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1629 if resolution.unresolved_segments() == 0 {
1630 return hir::QPath::Resolved(qself, path);
1633 // Create the innermost type that we're projecting from.
1634 let mut ty = if path.segments.is_empty() {
1635 // If the base path is empty that means there exists a
1636 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1637 qself.expect("missing QSelf for <T>::...")
1639 // Otherwise, the base path is an implicit `Self` type path,
1640 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1641 // `<I as Iterator>::Item::default`.
1642 let new_id = self.next_id();
1643 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1646 // Anything after the base path are associated "extensions",
1647 // out of which all but the last one are associated types,
1648 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1649 // * base path is `std::vec::Vec<T>`
1650 // * "extensions" are `IntoIter`, `Item` and `clone`
1651 // * type nodes are:
1652 // 1. `std::vec::Vec<T>` (created above)
1653 // 2. `<std::vec::Vec<T>>::IntoIter`
1654 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1655 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1656 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1657 let segment = P(self.lower_path_segment(
1662 ParenthesizedGenericArgs::Warn,
1665 let qpath = hir::QPath::TypeRelative(ty, segment);
1667 // It's finished, return the extension of the right node type.
1668 if i == p.segments.len() - 1 {
1672 // Wrap the associated extension in another type node.
1673 let new_id = self.next_id();
1674 ty = P(self.ty_path(new_id, p.span, qpath));
1677 // Should've returned in the for loop above.
1680 "lower_qpath: no final extension segment in {}..{}",
1686 fn lower_path_extra(
1690 ident: Option<Ident>,
1691 param_mode: ParamMode,
1695 segments: p.segments
1698 self.lower_path_segment(
1703 ParenthesizedGenericArgs::Err,
1704 ImplTraitContext::Disallowed,
1707 .chain(ident.map(|ident| hir::PathSegment::from_ident(ident)))
1713 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1714 let def = self.expect_full_def(id);
1715 self.lower_path_extra(def, p, None, param_mode)
1718 fn lower_path_segment(
1721 segment: &PathSegment,
1722 param_mode: ParamMode,
1723 expected_lifetimes: usize,
1724 parenthesized_generic_args: ParenthesizedGenericArgs,
1725 itctx: ImplTraitContext,
1726 ) -> hir::PathSegment {
1727 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1728 let msg = "parenthesized parameters may only be used with a trait";
1729 match **generic_args {
1730 GenericArgs::AngleBracketed(ref data) => {
1731 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1733 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1734 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1735 ParenthesizedGenericArgs::Warn => {
1736 self.sess.buffer_lint(
1737 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1742 (hir::GenericArgs::none(), true)
1744 ParenthesizedGenericArgs::Err => {
1745 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1746 .span_label(data.span, "only traits may use parentheses")
1748 (hir::GenericArgs::none(), true)
1753 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1756 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1757 GenericArg::Lifetime(_) => true,
1760 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1761 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1762 if !generic_args.parenthesized && !has_lifetimes {
1764 self.elided_path_lifetimes(path_span, expected_lifetimes)
1766 .map(|lt| GenericArg::Lifetime(lt))
1767 .chain(generic_args.args.into_iter())
1769 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1770 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1771 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1772 let no_bindings = generic_args.bindings.is_empty();
1773 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1774 // If there are no (non-implicit) generic args or associated-type
1775 // bindings, our suggestion includes the angle brackets
1776 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1778 // Otherwise—sorry, this is kind of gross—we need to infer the
1779 // place to splice in the `'_, ` from the generics that do exist
1780 let first_generic_span = first_generic_span
1781 .expect("already checked that type args or bindings exist");
1782 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1784 self.sess.buffer_lint_with_diagnostic(
1785 ELIDED_LIFETIMES_IN_PATHS,
1788 "hidden lifetime parameters in types are deprecated",
1789 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1790 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1796 hir::PathSegment::new(
1803 fn lower_angle_bracketed_parameter_data(
1805 data: &AngleBracketedArgs,
1806 param_mode: ParamMode,
1807 mut itctx: ImplTraitContext,
1808 ) -> (hir::GenericArgs, bool) {
1809 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1810 let has_types = args.iter().any(|arg| match arg {
1811 ast::GenericArg::Type(_) => true,
1815 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1816 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1817 parenthesized: false,
1819 !has_types && param_mode == ParamMode::Optional)
1822 fn lower_parenthesized_parameter_data(
1824 data: &ParenthesisedArgs,
1825 ) -> (hir::GenericArgs, bool) {
1826 // Switch to `PassThrough` mode for anonymous lifetimes: this
1827 // means that we permit things like `&Ref<T>`, where `Ref` has
1828 // a hidden lifetime parameter. This is needed for backwards
1829 // compatibility, even in contexts like an impl header where
1830 // we generally don't permit such things (see #51008).
1831 self.with_anonymous_lifetime_mode(
1832 AnonymousLifetimeMode::PassThrough,
1834 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1835 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1836 let inputs = inputs.iter().map(|ty| this.lower_ty_direct(ty, DISALLOWED)).collect();
1837 let mk_tup = |this: &mut Self, tys, span| {
1838 let LoweredNodeId { node_id, hir_id } = this.next_id();
1839 hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1844 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1847 id: this.next_id().node_id,
1848 ident: Ident::from_str(FN_OUTPUT_NAME),
1851 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1852 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1853 span: output.as_ref().map_or(span, |ty| ty.span),
1856 parenthesized: true,
1864 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1865 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1871 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1872 pat: self.lower_pat(&l.pat),
1873 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1875 attrs: l.attrs.clone(),
1876 source: hir::LocalSource::Normal,
1880 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1882 Mutability::Mutable => hir::MutMutable,
1883 Mutability::Immutable => hir::MutImmutable,
1887 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1888 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1892 pat: self.lower_pat(&arg.pat),
1896 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1899 .map(|arg| match arg.pat.node {
1900 PatKind::Ident(_, ident, _) => ident,
1901 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
1906 // Lowers a function declaration.
1908 // decl: the unlowered (ast) function declaration.
1909 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1910 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1911 // make_ret_async is also `Some`.
1912 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1913 // This guards against trait declarations and implementations where impl Trait is
1915 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1916 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
1917 // return type impl Trait item.
1921 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
1922 impl_trait_return_allow: bool,
1923 make_ret_async: Option<NodeId>,
1924 ) -> P<hir::FnDecl> {
1925 let inputs = decl.inputs
1928 if let Some((_, ref mut ibty)) = in_band_ty_params {
1929 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
1931 self.lower_ty_direct(&arg.ty, ImplTraitContext::Disallowed)
1934 .collect::<HirVec<_>>();
1936 let output = if let Some(ret_id) = make_ret_async {
1937 self.lower_async_fn_ret_ty(
1940 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
1945 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
1946 Some((def_id, _)) if impl_trait_return_allow => {
1947 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1949 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1951 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1958 variadic: decl.variadic,
1959 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1960 TyKind::ImplicitSelf => true,
1961 TyKind::Rptr(_, ref mt) => mt.ty.node.is_implicit_self(),
1967 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
1969 // fn_span: the span of the async function declaration. Used for error reporting.
1970 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
1971 // output: unlowered output type (`T` in `-> T`)
1972 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
1973 fn lower_async_fn_ret_ty(
1976 output: &FunctionRetTy,
1978 return_impl_trait_id: NodeId,
1979 ) -> hir::FunctionRetTy {
1980 // Get lifetimes used in the input arguments to the function. Our output type must also
1981 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
1982 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
1983 // is a subset of the other. We really want some new lifetime that is a subset of all input
1984 // lifetimes, but that doesn't exist at the moment.
1986 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
1987 context: &'r mut LoweringContext<'a>,
1988 // Lifetimes bound by HRTB
1989 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1990 // Whether to count elided lifetimes.
1991 // Disabled inside of `Fn` or `fn` syntax.
1992 collect_elided_lifetimes: bool,
1993 // The lifetime found.
1994 // Multiple different or elided lifetimes cannot appear in async fn for now.
1995 output_lifetime: Option<(hir::LifetimeName, Span)>,
1998 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
1999 fn nested_visit_map<'this>(
2001 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
2002 hir::intravisit::NestedVisitorMap::None
2005 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
2006 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2007 if parameters.parenthesized {
2008 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2009 self.collect_elided_lifetimes = false;
2010 hir::intravisit::walk_generic_args(self, span, parameters);
2011 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2013 hir::intravisit::walk_generic_args(self, span, parameters);
2017 fn visit_ty(&mut self, t: &'v hir::Ty) {
2018 // Don't collect elided lifetimes used inside of `fn()` syntax
2019 if let &hir::TyKind::BareFn(_) = &t.node {
2020 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2021 self.collect_elided_lifetimes = false;
2023 // Record the "stack height" of `for<'a>` lifetime bindings
2024 // to be able to later fully undo their introduction.
2025 let old_len = self.currently_bound_lifetimes.len();
2026 hir::intravisit::walk_ty(self, t);
2027 self.currently_bound_lifetimes.truncate(old_len);
2029 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2031 hir::intravisit::walk_ty(self, t);
2035 fn visit_poly_trait_ref(
2037 trait_ref: &'v hir::PolyTraitRef,
2038 modifier: hir::TraitBoundModifier,
2040 // Record the "stack height" of `for<'a>` lifetime bindings
2041 // to be able to later fully undo their introduction.
2042 let old_len = self.currently_bound_lifetimes.len();
2043 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2044 self.currently_bound_lifetimes.truncate(old_len);
2047 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2048 // Record the introduction of 'a in `for<'a> ...`
2049 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2050 // Introduce lifetimes one at a time so that we can handle
2051 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2052 let lt_name = hir::LifetimeName::Param(param.name);
2053 self.currently_bound_lifetimes.push(lt_name);
2056 hir::intravisit::walk_generic_param(self, param);
2059 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2060 let name = match lifetime.name {
2061 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2062 if self.collect_elided_lifetimes {
2063 // Use `'_` for both implicit and underscore lifetimes in
2064 // `abstract type Foo<'_>: SomeTrait<'_>;`
2065 hir::LifetimeName::Underscore
2070 hir::LifetimeName::Param(_) => lifetime.name,
2071 hir::LifetimeName::Static => return,
2074 if !self.currently_bound_lifetimes.contains(&name) {
2075 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2076 // We don't currently have a reliable way to desugar `async fn` with
2077 // multiple potentially unrelated input lifetimes into
2078 // `-> impl Trait + 'lt`, so we report an error in this case.
2079 if current_lt_name != name {
2082 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2084 "multiple different lifetimes used in arguments of `async fn`",
2086 .span_label(current_lt_span, "first lifetime here")
2087 .span_label(lifetime.span, "different lifetime here")
2088 .help("`async fn` can only accept borrowed values \
2089 with identical lifetimes")
2091 } else if current_lt_name.is_elided() && name.is_elided() {
2094 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2096 "multiple elided lifetimes used in arguments of `async fn`",
2098 .span_label(current_lt_span, "first lifetime here")
2099 .span_label(lifetime.span, "different lifetime here")
2100 .help("consider giving these arguments named lifetimes")
2104 self.output_lifetime = Some((name, lifetime.span));
2110 let bound_lifetime = {
2111 let mut lifetime_collector = AsyncFnLifetimeCollector {
2113 currently_bound_lifetimes: Vec::new(),
2114 collect_elided_lifetimes: true,
2115 output_lifetime: None,
2119 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2121 lifetime_collector.output_lifetime
2124 let span = match output {
2125 FunctionRetTy::Ty(ty) => ty.span,
2126 FunctionRetTy::Default(span) => *span,
2129 let impl_trait_ty = self.lower_existential_impl_trait(
2130 span, fn_def_id, return_impl_trait_id, |this| {
2131 let output_ty = match output {
2132 FunctionRetTy::Ty(ty) =>
2133 this.lower_ty(ty, ImplTraitContext::Existential(fn_def_id)),
2134 FunctionRetTy::Default(span) => {
2135 let LoweredNodeId { node_id, hir_id } = this.next_id();
2139 node: hir::TyKind::Tup(hir_vec![]),
2146 let future_params = P(hir::GenericArgs {
2148 bindings: hir_vec![hir::TypeBinding {
2149 ident: Ident::from_str(FN_OUTPUT_NAME),
2151 id: this.next_id().node_id,
2154 parenthesized: false,
2158 this.std_path(span, &["future", "Future"], Some(future_params), false);
2160 let LoweredNodeId { node_id, hir_id } = this.next_id();
2161 let mut bounds = vec![
2162 hir::GenericBound::Trait(
2164 trait_ref: hir::TraitRef {
2169 bound_generic_params: hir_vec![],
2172 hir::TraitBoundModifier::None
2176 if let Some((name, span)) = bound_lifetime {
2177 bounds.push(hir::GenericBound::Outlives(
2178 hir::Lifetime { id: this.next_id().node_id, name, span }));
2181 hir::HirVec::from(bounds)
2184 let LoweredNodeId { node_id, hir_id } = self.next_id();
2185 let impl_trait_ty = P(hir::Ty {
2187 node: impl_trait_ty,
2192 hir::FunctionRetTy::Return(impl_trait_ty)
2195 fn lower_param_bound(
2198 itctx: ImplTraitContext,
2199 ) -> hir::GenericBound {
2201 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2202 self.lower_poly_trait_ref(ty, itctx),
2203 self.lower_trait_bound_modifier(modifier),
2205 GenericBound::Outlives(ref lifetime) => {
2206 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2211 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2212 let span = l.ident.span;
2214 ident if ident.name == keywords::StaticLifetime.name() =>
2215 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2216 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2217 match self.anonymous_lifetime_mode {
2218 AnonymousLifetimeMode::CreateParameter => {
2219 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2220 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2223 AnonymousLifetimeMode::PassThrough => {
2224 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2228 self.maybe_collect_in_band_lifetime(ident);
2229 let param_name = ParamName::Plain(ident);
2230 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2235 fn new_named_lifetime(
2239 name: hir::LifetimeName,
2240 ) -> hir::Lifetime {
2242 id: self.lower_node_id(id).node_id,
2248 fn lower_generic_params(
2250 params: &[GenericParam],
2251 add_bounds: &NodeMap<Vec<GenericBound>>,
2252 mut itctx: ImplTraitContext,
2253 ) -> hir::HirVec<hir::GenericParam> {
2254 params.iter().map(|param| {
2255 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2259 fn lower_generic_param(&mut self,
2260 param: &GenericParam,
2261 add_bounds: &NodeMap<Vec<GenericBound>>,
2262 mut itctx: ImplTraitContext)
2263 -> hir::GenericParam {
2264 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx.reborrow());
2266 GenericParamKind::Lifetime => {
2267 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2268 self.is_collecting_in_band_lifetimes = false;
2270 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
2271 let param_name = match lt.name {
2272 hir::LifetimeName::Param(param_name) => param_name,
2273 _ => hir::ParamName::Plain(lt.name.ident()),
2275 let param = hir::GenericParam {
2279 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2280 attrs: self.lower_attrs(¶m.attrs),
2282 kind: hir::GenericParamKind::Lifetime { in_band: false }
2285 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2289 GenericParamKind::Type { ref default, .. } => {
2290 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2291 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2292 // Instead, use gensym("Self") to create a distinct name that looks the same.
2293 let ident = if param.ident.name == keywords::SelfType.name() {
2294 param.ident.gensym()
2299 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2300 if !add_bounds.is_empty() {
2301 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2302 bounds = bounds.into_iter()
2308 id: self.lower_node_id(param.id).node_id,
2309 name: hir::ParamName::Plain(ident),
2310 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2311 attrs: self.lower_attrs(¶m.attrs),
2314 kind: hir::GenericParamKind::Type {
2315 default: default.as_ref().map(|x| {
2316 self.lower_ty(x, ImplTraitContext::Disallowed)
2318 synthetic: param.attrs.iter()
2319 .filter(|attr| attr.check_name("rustc_synthetic"))
2320 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2330 generics: &Generics,
2331 itctx: ImplTraitContext)
2334 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2335 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2336 // paths where report_error is called are also the only paths that advance to after
2337 // the match statement, so the error reporting could probably just be moved there.
2338 let mut add_bounds: NodeMap<Vec<_>> = NodeMap();
2339 for pred in &generics.where_clause.predicates {
2340 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2341 'next_bound: for bound in &bound_pred.bounds {
2342 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2343 let report_error = |this: &mut Self| {
2344 this.diagnostic().span_err(
2345 bound_pred.bounded_ty.span,
2346 "`?Trait` bounds are only permitted at the \
2347 point where a type parameter is declared",
2350 // Check if the where clause type is a plain type parameter.
2351 match bound_pred.bounded_ty.node {
2352 TyKind::Path(None, ref path)
2353 if path.segments.len() == 1
2354 && bound_pred.bound_generic_params.is_empty() =>
2356 if let Some(Def::TyParam(def_id)) = self.resolver
2357 .get_resolution(bound_pred.bounded_ty.id)
2358 .map(|d| d.base_def())
2360 if let Some(node_id) =
2361 self.resolver.definitions().as_local_node_id(def_id)
2363 for param in &generics.params {
2365 GenericParamKind::Type { .. } => {
2366 if node_id == param.id {
2367 add_bounds.entry(param.id)
2369 .push(bound.clone());
2370 continue 'next_bound;
2380 _ => report_error(self),
2388 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2389 where_clause: self.lower_where_clause(&generics.where_clause),
2390 span: generics.span,
2394 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2396 id: self.lower_node_id(wc.id).node_id,
2397 predicates: wc.predicates
2399 .map(|predicate| self.lower_where_predicate(predicate))
2404 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2406 WherePredicate::BoundPredicate(WhereBoundPredicate {
2407 ref bound_generic_params,
2412 self.with_in_scope_lifetime_defs(
2413 &bound_generic_params,
2415 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2416 bound_generic_params: this.lower_generic_params(
2417 bound_generic_params,
2419 ImplTraitContext::Disallowed,
2421 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2424 .filter_map(|bound| match *bound {
2425 // Ignore `?Trait` bounds.
2426 // Tthey were copied into type parameters already.
2427 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2428 _ => Some(this.lower_param_bound(
2430 ImplTraitContext::Disallowed,
2439 WherePredicate::RegionPredicate(WhereRegionPredicate {
2443 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2445 lifetime: self.lower_lifetime(lifetime),
2446 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2448 WherePredicate::EqPredicate(WhereEqPredicate {
2453 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2454 id: self.lower_node_id(id).node_id,
2455 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2456 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2462 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2464 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2468 .map(|f| self.lower_struct_field(f))
2470 self.lower_node_id(id).node_id,
2472 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2476 .map(|f| self.lower_struct_field(f))
2478 self.lower_node_id(id).node_id,
2480 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2484 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2485 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2486 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2487 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2489 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.ref_id);
2497 fn lower_poly_trait_ref(
2500 mut itctx: ImplTraitContext,
2501 ) -> hir::PolyTraitRef {
2502 let bound_generic_params =
2503 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx.reborrow());
2504 let trait_ref = self.with_parent_impl_lifetime_defs(
2505 &bound_generic_params,
2506 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2510 bound_generic_params,
2516 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2519 id: self.lower_node_id(f.id).node_id,
2520 ident: match f.ident {
2521 Some(ident) => ident,
2522 // FIXME(jseyfried) positional field hygiene
2523 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2525 vis: self.lower_visibility(&f.vis, None),
2526 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2527 attrs: self.lower_attrs(&f.attrs),
2531 fn lower_field(&mut self, f: &Field) -> hir::Field {
2533 id: self.next_id().node_id,
2535 expr: P(self.lower_expr(&f.expr)),
2537 is_shorthand: f.is_shorthand,
2541 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2543 ty: self.lower_ty(&mt.ty, itctx),
2544 mutbl: self.lower_mutability(mt.mutbl),
2548 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext)
2549 -> hir::GenericBounds {
2550 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2553 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2554 let mut expr = None;
2556 let mut stmts = vec![];
2558 for (index, stmt) in b.stmts.iter().enumerate() {
2559 if index == b.stmts.len() - 1 {
2560 if let StmtKind::Expr(ref e) = stmt.node {
2561 expr = Some(P(self.lower_expr(e)));
2563 stmts.extend(self.lower_stmt(stmt));
2566 stmts.extend(self.lower_stmt(stmt));
2570 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2575 stmts: stmts.into(),
2577 rules: self.lower_block_check_mode(&b.rules),
2580 recovered: b.recovered,
2584 fn lower_async_body(
2590 self.lower_body(Some(decl), |this| {
2591 if let IsAsync::Async { closure_id, .. } = asyncness {
2592 let async_expr = this.make_async_expr(
2593 CaptureBy::Value, closure_id, None,
2595 let body = this.lower_block(body, false);
2596 this.expr_block(body, ThinVec::new())
2598 this.expr(body.span, async_expr, ThinVec::new())
2600 let body = this.lower_block(body, false);
2601 this.expr_block(body, ThinVec::new())
2610 attrs: &hir::HirVec<Attribute>,
2611 vis: &mut hir::Visibility,
2613 ) -> hir::ItemKind {
2615 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2616 ItemKind::Use(ref use_tree) => {
2617 // Start with an empty prefix
2620 span: use_tree.span,
2623 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2625 ItemKind::Static(ref t, m, ref e) => {
2626 let value = self.lower_body(None, |this| this.lower_expr(e));
2627 hir::ItemKind::Static(
2628 self.lower_ty(t, ImplTraitContext::Disallowed),
2629 self.lower_mutability(m),
2633 ItemKind::Const(ref t, ref e) => {
2634 let value = self.lower_body(None, |this| this.lower_expr(e));
2635 hir::ItemKind::Const(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2637 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2638 let fn_def_id = self.resolver.definitions().local_def_id(id);
2640 self.with_new_scopes(|this| {
2641 // Note: we don't need to change the return type from `T` to
2642 // `impl Future<Output = T>` here because lower_body
2643 // only cares about the input argument patterns in the function
2644 // declaration (decl), not the return types.
2645 let body_id = this.lower_async_body(decl, header.asyncness, body);
2647 let (generics, fn_decl) = this.add_in_band_defs(
2650 AnonymousLifetimeMode::PassThrough,
2651 |this, idty| this.lower_fn_decl(
2652 decl, Some((fn_def_id, idty)), true, header.asyncness.opt_return_id()),
2657 this.lower_fn_header(header),
2663 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2664 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2665 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2666 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2667 self.lower_ty(t, ImplTraitContext::Disallowed),
2668 self.lower_generics(generics, ImplTraitContext::Disallowed),
2670 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2671 generics: self.lower_generics(generics, ImplTraitContext::Disallowed),
2672 bounds: self.lower_param_bounds(b, ImplTraitContext::Disallowed),
2673 impl_trait_fn: None,
2675 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2677 variants: enum_definition
2680 .map(|x| self.lower_variant(x))
2683 self.lower_generics(generics, ImplTraitContext::Disallowed),
2685 ItemKind::Struct(ref struct_def, ref generics) => {
2686 let struct_def = self.lower_variant_data(struct_def);
2687 hir::ItemKind::Struct(
2689 self.lower_generics(generics, ImplTraitContext::Disallowed),
2692 ItemKind::Union(ref vdata, ref generics) => {
2693 let vdata = self.lower_variant_data(vdata);
2694 hir::ItemKind::Union(
2696 self.lower_generics(generics, ImplTraitContext::Disallowed),
2708 let def_id = self.resolver.definitions().local_def_id(id);
2710 // Lower the "impl header" first. This ordering is important
2711 // for in-band lifetimes! Consider `'a` here:
2713 // impl Foo<'a> for u32 {
2714 // fn method(&'a self) { .. }
2717 // Because we start by lowering the `Foo<'a> for u32`
2718 // part, we will add `'a` to the list of generics on
2719 // the impl. When we then encounter it later in the
2720 // method, it will not be considered an in-band
2721 // lifetime to be added, but rather a reference to a
2723 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2726 AnonymousLifetimeMode::CreateParameter,
2728 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2729 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2732 if let Some(ref trait_ref) = trait_ref {
2733 if let Def::Trait(def_id) = trait_ref.path.def {
2734 this.trait_impls.entry(def_id).or_default().push(id);
2738 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2740 (trait_ref, lowered_ty)
2744 let new_impl_items = self.with_in_scope_lifetime_defs(
2745 &ast_generics.params,
2749 .map(|item| this.lower_impl_item_ref(item))
2754 hir::ItemKind::Impl(
2755 self.lower_unsafety(unsafety),
2756 self.lower_impl_polarity(polarity),
2757 self.lower_defaultness(defaultness, true /* [1] */),
2764 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2765 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2768 .map(|item| self.lower_trait_item_ref(item))
2770 hir::ItemKind::Trait(
2771 self.lower_is_auto(is_auto),
2772 self.lower_unsafety(unsafety),
2773 self.lower_generics(generics, ImplTraitContext::Disallowed),
2778 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
2779 self.lower_generics(generics, ImplTraitContext::Disallowed),
2780 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2782 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2785 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2786 // not cause an assertion failure inside the `lower_defaultness` function
2794 vis: &mut hir::Visibility,
2796 attrs: &hir::HirVec<Attribute>,
2797 ) -> hir::ItemKind {
2798 let path = &tree.prefix;
2801 UseTreeKind::Simple(rename, id1, id2) => {
2802 *name = tree.ident().name;
2804 // First apply the prefix to the path
2805 let mut path = Path {
2809 .chain(path.segments.iter())
2815 // Correctly resolve `self` imports
2816 if path.segments.len() > 1
2817 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2819 let _ = path.segments.pop();
2820 if rename.is_none() {
2821 *name = path.segments.last().unwrap().ident.name;
2825 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2826 let mut defs = self.expect_full_def_from_use(id);
2827 // we want to return *something* from this function, so hang onto the first item
2829 let ret_def = defs.next().unwrap_or(Def::Err);
2831 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2832 let vis = vis.clone();
2833 let name = name.clone();
2834 let span = path.span;
2835 self.resolver.definitions().create_def_with_parent(
2839 DefIndexAddressSpace::High,
2842 self.allocate_hir_id_counter(new_node_id, &path);
2844 self.with_hir_id_owner(new_node_id, |this| {
2845 let new_id = this.lower_node_id(new_node_id);
2846 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2847 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
2848 let vis_kind = match vis.node {
2849 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2850 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2851 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2852 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
2853 let id = this.next_id();
2854 hir::VisibilityKind::Restricted {
2856 // We are allocating a new NodeId here
2862 let vis = respan(vis.span, vis_kind);
2868 hir_id: new_id.hir_id,
2870 attrs: attrs.clone(),
2879 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2880 hir::ItemKind::Use(path, hir::UseKind::Single)
2882 UseTreeKind::Glob => {
2883 let path = P(self.lower_path(
2889 .chain(path.segments.iter())
2894 ParamMode::Explicit,
2896 hir::ItemKind::Use(path, hir::UseKind::Glob)
2898 UseTreeKind::Nested(ref trees) => {
2903 .chain(path.segments.iter())
2906 span: prefix.span.to(path.span),
2909 // Add all the nested PathListItems in the HIR
2910 for &(ref use_tree, id) in trees {
2911 self.allocate_hir_id_counter(id, &use_tree);
2915 } = self.lower_node_id(id);
2917 let mut vis = vis.clone();
2918 let mut name = name.clone();
2920 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2922 self.with_hir_id_owner(new_id, |this| {
2923 let vis_kind = match vis.node {
2924 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2925 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2926 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2927 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
2928 let id = this.next_id();
2929 hir::VisibilityKind::Restricted {
2931 // We are allocating a new NodeId here
2937 let vis = respan(vis.span, vis_kind);
2945 attrs: attrs.clone(),
2948 span: use_tree.span,
2954 // Privatize the degenerate import base, used only to check
2955 // the stability of `use a::{};`, to avoid it showing up as
2956 // a re-export by accident when `pub`, e.g. in documentation.
2957 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2958 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
2959 hir::ItemKind::Use(path, hir::UseKind::ListStem)
2964 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2965 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2966 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2968 let (generics, node) = match i.node {
2969 TraitItemKind::Const(ref ty, ref default) => (
2970 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2971 hir::TraitItemKind::Const(
2972 self.lower_ty(ty, ImplTraitContext::Disallowed),
2975 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2978 TraitItemKind::Method(ref sig, None) => {
2979 let names = self.lower_fn_args_to_names(&sig.decl);
2980 let (generics, sig) = self.lower_method_sig(
2987 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
2989 TraitItemKind::Method(ref sig, Some(ref body)) => {
2990 let body_id = self.lower_body(Some(&sig.decl), |this| {
2991 let body = this.lower_block(body, false);
2992 this.expr_block(body, ThinVec::new())
2995 let (generics, sig) = self.lower_method_sig(
3003 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3005 TraitItemKind::Type(ref bounds, ref default) => (
3006 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3007 hir::TraitItemKind::Type(
3008 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3011 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
3014 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3021 attrs: self.lower_attrs(&i.attrs),
3028 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3029 let (kind, has_default) = match i.node {
3030 TraitItemKind::Const(_, ref default) => {
3031 (hir::AssociatedItemKind::Const, default.is_some())
3033 TraitItemKind::Type(_, ref default) => {
3034 (hir::AssociatedItemKind::Type, default.is_some())
3036 TraitItemKind::Method(ref sig, ref default) => (
3037 hir::AssociatedItemKind::Method {
3038 has_self: sig.decl.has_self(),
3042 TraitItemKind::Macro(..) => unimplemented!(),
3045 id: hir::TraitItemId { node_id: i.id },
3048 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3053 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3054 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3055 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3057 let (generics, node) = match i.node {
3058 ImplItemKind::Const(ref ty, ref expr) => {
3059 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3061 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3062 hir::ImplItemKind::Const(
3063 self.lower_ty(ty, ImplTraitContext::Disallowed),
3068 ImplItemKind::Method(ref sig, ref body) => {
3069 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3070 let impl_trait_return_allow = !self.is_in_trait_impl;
3071 let (generics, sig) = self.lower_method_sig(
3075 impl_trait_return_allow,
3076 sig.header.asyncness.opt_return_id(),
3078 (generics, hir::ImplItemKind::Method(sig, body_id))
3080 ImplItemKind::Type(ref ty) => (
3081 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3082 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
3084 ImplItemKind::Existential(ref bounds) => (
3085 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3086 hir::ImplItemKind::Existential(
3087 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3090 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3097 attrs: self.lower_attrs(&i.attrs),
3099 vis: self.lower_visibility(&i.vis, None),
3100 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3105 // [1] since `default impl` is not yet implemented, this is always true in impls
3108 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3110 id: hir::ImplItemId { node_id: i.id },
3113 vis: self.lower_visibility(&i.vis, Some(i.id)),
3114 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3115 kind: match i.node {
3116 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3117 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3118 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3119 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3120 has_self: sig.decl.has_self(),
3122 ImplItemKind::Macro(..) => unimplemented!(),
3126 // [1] since `default impl` is not yet implemented, this is always true in impls
3129 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3132 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3136 /// Lowers `impl Trait` items and appends them to the list
3137 fn lower_impl_trait_ids(
3141 ids: &mut OneVector<hir::ItemId>,
3143 if let Some(id) = header.asyncness.opt_return_id() {
3144 ids.push(hir::ItemId { id });
3146 struct IdVisitor<'a> { ids: &'a mut OneVector<hir::ItemId> }
3147 impl<'a, 'b> Visitor<'a> for IdVisitor<'b> {
3148 fn visit_ty(&mut self, ty: &'a Ty) {
3154 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
3157 visit::walk_ty(self, ty);
3159 fn visit_path_segment(
3162 path_segment: &'v PathSegment,
3164 if let Some(ref p) = path_segment.args {
3165 if let GenericArgs::Parenthesized(_) = **p {
3169 visit::walk_path_segment(self, path_span, path_segment)
3172 let mut visitor = IdVisitor { ids };
3174 FunctionRetTy::Default(_) => {},
3175 FunctionRetTy::Ty(ref ty) => visitor.visit_ty(ty),
3179 fn lower_item_id(&mut self, i: &Item) -> OneVector<hir::ItemId> {
3181 ItemKind::Use(ref use_tree) => {
3182 let mut vec = smallvec![hir::ItemId { id: i.id }];
3183 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3186 ItemKind::MacroDef(..) => OneVector::new(),
3187 ItemKind::Fn(ref decl, ref header, ..) => {
3188 let mut ids = smallvec![hir::ItemId { id: i.id }];
3189 self.lower_impl_trait_ids(decl, header, &mut ids);
3192 ItemKind::Impl(.., None, _, ref items) => {
3193 let mut ids = smallvec![hir::ItemId { id: i.id }];
3195 if let ImplItemKind::Method(ref sig, _) = item.node {
3196 self.lower_impl_trait_ids(&sig.decl, &sig.header, &mut ids);
3201 _ => smallvec![hir::ItemId { id: i.id }],
3205 fn lower_item_id_use_tree(&mut self,
3208 vec: &mut OneVector<hir::ItemId>)
3211 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3212 vec.push(hir::ItemId { id });
3213 self.lower_item_id_use_tree(nested, id, vec);
3215 UseTreeKind::Glob => {}
3216 UseTreeKind::Simple(_, id1, id2) => {
3217 for (_, &id) in self.expect_full_def_from_use(base_id)
3219 .zip([id1, id2].iter())
3221 vec.push(hir::ItemId { id });
3227 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3228 let mut name = i.ident.name;
3229 let mut vis = self.lower_visibility(&i.vis, None);
3230 let attrs = self.lower_attrs(&i.attrs);
3231 if let ItemKind::MacroDef(ref def) = i.node {
3232 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3233 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3234 let body = self.lower_token_stream(def.stream());
3235 self.exported_macros.push(hir::MacroDef {
3248 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3250 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3263 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3264 let node_id = self.lower_node_id(i.id).node_id;
3265 let def_id = self.resolver.definitions().local_def_id(node_id);
3269 attrs: self.lower_attrs(&i.attrs),
3270 node: match i.node {
3271 ForeignItemKind::Fn(ref fdec, ref generics) => {
3272 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3275 AnonymousLifetimeMode::PassThrough,
3278 // Disallow impl Trait in foreign items
3279 this.lower_fn_decl(fdec, None, false, None),
3280 this.lower_fn_args_to_names(fdec),
3285 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3287 ForeignItemKind::Static(ref t, m) => {
3288 hir::ForeignItemKind::Static(self.lower_ty(t, ImplTraitContext::Disallowed), m)
3290 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3291 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3293 vis: self.lower_visibility(&i.vis, None),
3298 fn lower_method_sig(
3300 generics: &Generics,
3303 impl_trait_return_allow: bool,
3304 is_async: Option<NodeId>,
3305 ) -> (hir::Generics, hir::MethodSig) {
3306 let header = self.lower_fn_header(sig.header);
3307 let (generics, decl) = self.add_in_band_defs(
3310 AnonymousLifetimeMode::PassThrough,
3311 |this, idty| this.lower_fn_decl(
3313 Some((fn_def_id, idty)),
3314 impl_trait_return_allow,
3318 (generics, hir::MethodSig { header, decl })
3321 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3323 IsAuto::Yes => hir::IsAuto::Yes,
3324 IsAuto::No => hir::IsAuto::No,
3328 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3330 unsafety: self.lower_unsafety(h.unsafety),
3331 asyncness: self.lower_asyncness(h.asyncness),
3332 constness: self.lower_constness(h.constness),
3337 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3339 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3340 Unsafety::Normal => hir::Unsafety::Normal,
3344 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3346 Constness::Const => hir::Constness::Const,
3347 Constness::NotConst => hir::Constness::NotConst,
3351 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3353 IsAsync::Async { .. } => hir::IsAsync::Async,
3354 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3358 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3360 UnOp::Deref => hir::UnDeref,
3361 UnOp::Not => hir::UnNot,
3362 UnOp::Neg => hir::UnNeg,
3366 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3368 node: match b.node {
3369 BinOpKind::Add => hir::BinOpKind::Add,
3370 BinOpKind::Sub => hir::BinOpKind::Sub,
3371 BinOpKind::Mul => hir::BinOpKind::Mul,
3372 BinOpKind::Div => hir::BinOpKind::Div,
3373 BinOpKind::Rem => hir::BinOpKind::Rem,
3374 BinOpKind::And => hir::BinOpKind::And,
3375 BinOpKind::Or => hir::BinOpKind::Or,
3376 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3377 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3378 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3379 BinOpKind::Shl => hir::BinOpKind::Shl,
3380 BinOpKind::Shr => hir::BinOpKind::Shr,
3381 BinOpKind::Eq => hir::BinOpKind::Eq,
3382 BinOpKind::Lt => hir::BinOpKind::Lt,
3383 BinOpKind::Le => hir::BinOpKind::Le,
3384 BinOpKind::Ne => hir::BinOpKind::Ne,
3385 BinOpKind::Ge => hir::BinOpKind::Ge,
3386 BinOpKind::Gt => hir::BinOpKind::Gt,
3392 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3393 let node = match p.node {
3394 PatKind::Wild => hir::PatKind::Wild,
3395 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3396 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3397 // `None` can occur in body-less function signatures
3398 def @ None | def @ Some(Def::Local(_)) => {
3399 let canonical_id = match def {
3400 Some(Def::Local(id)) => id,
3403 hir::PatKind::Binding(
3404 self.lower_binding_mode(binding_mode),
3407 sub.as_ref().map(|x| self.lower_pat(x)),
3410 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3415 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3420 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3421 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3422 let qpath = self.lower_qpath(
3426 ParamMode::Optional,
3427 ImplTraitContext::Disallowed,
3429 hir::PatKind::TupleStruct(
3431 pats.iter().map(|x| self.lower_pat(x)).collect(),
3435 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3439 ParamMode::Optional,
3440 ImplTraitContext::Disallowed,
3442 PatKind::Struct(ref path, ref fields, etc) => {
3443 let qpath = self.lower_qpath(
3447 ParamMode::Optional,
3448 ImplTraitContext::Disallowed,
3455 node: hir::FieldPat {
3456 id: self.next_id().node_id,
3457 ident: f.node.ident,
3458 pat: self.lower_pat(&f.node.pat),
3459 is_shorthand: f.node.is_shorthand,
3463 hir::PatKind::Struct(qpath, fs, etc)
3465 PatKind::Tuple(ref elts, ddpos) => {
3466 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3468 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3469 PatKind::Ref(ref inner, mutbl) => {
3470 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3472 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3473 P(self.lower_expr(e1)),
3474 P(self.lower_expr(e2)),
3475 self.lower_range_end(end),
3477 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3478 before.iter().map(|x| self.lower_pat(x)).collect(),
3479 slice.as_ref().map(|x| self.lower_pat(x)),
3480 after.iter().map(|x| self.lower_pat(x)).collect(),
3482 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3483 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3486 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3495 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3497 RangeEnd::Included(_) => hir::RangeEnd::Included,
3498 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3502 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3503 self.with_new_scopes(|this| {
3504 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3508 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3513 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3514 let kind = match e.node {
3515 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3516 ExprKind::ObsoleteInPlace(..) => {
3517 self.sess.abort_if_errors();
3518 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3520 ExprKind::Array(ref exprs) => {
3521 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3523 ExprKind::Repeat(ref expr, ref count) => {
3524 let expr = P(self.lower_expr(expr));
3525 let count = self.lower_anon_const(count);
3526 hir::ExprKind::Repeat(expr, count)
3528 ExprKind::Tup(ref elts) => {
3529 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3531 ExprKind::Call(ref f, ref args) => {
3532 let f = P(self.lower_expr(f));
3533 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3535 ExprKind::MethodCall(ref seg, ref args) => {
3536 let hir_seg = self.lower_path_segment(
3539 ParamMode::Optional,
3541 ParenthesizedGenericArgs::Err,
3542 ImplTraitContext::Disallowed,
3544 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3545 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3547 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3548 let binop = self.lower_binop(binop);
3549 let lhs = P(self.lower_expr(lhs));
3550 let rhs = P(self.lower_expr(rhs));
3551 hir::ExprKind::Binary(binop, lhs, rhs)
3553 ExprKind::Unary(op, ref ohs) => {
3554 let op = self.lower_unop(op);
3555 let ohs = P(self.lower_expr(ohs));
3556 hir::ExprKind::Unary(op, ohs)
3558 ExprKind::Lit(ref l) => hir::ExprKind::Lit(P((**l).clone())),
3559 ExprKind::Cast(ref expr, ref ty) => {
3560 let expr = P(self.lower_expr(expr));
3561 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3563 ExprKind::Type(ref expr, ref ty) => {
3564 let expr = P(self.lower_expr(expr));
3565 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3567 ExprKind::AddrOf(m, ref ohs) => {
3568 let m = self.lower_mutability(m);
3569 let ohs = P(self.lower_expr(ohs));
3570 hir::ExprKind::AddrOf(m, ohs)
3572 // More complicated than you might expect because the else branch
3573 // might be `if let`.
3574 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3575 let else_opt = else_opt.as_ref().map(|els| {
3577 ExprKind::IfLet(..) => {
3578 // wrap the if-let expr in a block
3579 let span = els.span;
3580 let els = P(self.lower_expr(els));
3581 let LoweredNodeId { node_id, hir_id } = self.next_id();
3582 let blk = P(hir::Block {
3587 rules: hir::DefaultBlock,
3589 targeted_by_break: false,
3590 recovered: blk.recovered,
3592 P(self.expr_block(blk, ThinVec::new()))
3594 _ => P(self.lower_expr(els)),
3598 let then_blk = self.lower_block(blk, false);
3599 let then_expr = self.expr_block(then_blk, ThinVec::new());
3601 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3603 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3604 hir::ExprKind::While(
3605 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3606 this.lower_block(body, false),
3607 this.lower_label(opt_label),
3610 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3611 hir::ExprKind::Loop(
3612 this.lower_block(body, false),
3613 this.lower_label(opt_label),
3614 hir::LoopSource::Loop,
3617 ExprKind::TryBlock(ref body) => {
3618 self.with_catch_scope(body.id, |this| {
3620 this.allow_internal_unstable(CompilerDesugaringKind::TryBlock, body.span);
3621 let mut block = this.lower_block(body, true).into_inner();
3622 let tail = block.expr.take().map_or_else(
3624 let LoweredNodeId { node_id, hir_id } = this.next_id();
3625 let span = this.sess.source_map().end_point(unstable_span);
3629 node: hir::ExprKind::Tup(hir_vec![]),
3630 attrs: ThinVec::new(),
3634 |x: P<hir::Expr>| x.into_inner(),
3636 block.expr = Some(this.wrap_in_try_constructor(
3637 "from_ok", tail, unstable_span));
3638 hir::ExprKind::Block(P(block), None)
3641 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3642 P(self.lower_expr(expr)),
3643 arms.iter().map(|x| self.lower_arm(x)).collect(),
3644 hir::MatchSource::Normal,
3646 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3647 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3648 this.with_new_scopes(|this| {
3649 let block = this.lower_block(block, false);
3650 this.expr_block(block, ThinVec::new())
3655 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3657 if let IsAsync::Async { closure_id, .. } = asyncness {
3658 let outer_decl = FnDecl {
3659 inputs: decl.inputs.clone(),
3660 output: FunctionRetTy::Default(fn_decl_span),
3663 // We need to lower the declaration outside the new scope, because we
3664 // have to conserve the state of being inside a loop condition for the
3665 // closure argument types.
3666 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3668 self.with_new_scopes(|this| {
3669 // FIXME(cramertj) allow `async` non-`move` closures with
3670 if capture_clause == CaptureBy::Ref &&
3671 !decl.inputs.is_empty()
3677 "`async` non-`move` closures with arguments \
3678 are not currently supported",
3680 .help("consider using `let` statements to manually capture \
3681 variables by reference before entering an \
3682 `async move` closure")
3686 // Transform `async |x: u8| -> X { ... }` into
3687 // `|x: u8| future_from_generator(|| -> X { ... })`
3688 let body_id = this.lower_body(Some(&outer_decl), |this| {
3689 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3692 let async_body = this.make_async_expr(
3693 capture_clause, closure_id, async_ret_ty,
3695 this.with_new_scopes(|this| this.lower_expr(body))
3697 this.expr(fn_decl_span, async_body, ThinVec::new())
3699 hir::ExprKind::Closure(
3700 this.lower_capture_clause(capture_clause),
3708 // Lower outside new scope to preserve `is_in_loop_condition`.
3709 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3711 self.with_new_scopes(|this| {
3712 let mut is_generator = false;
3713 let body_id = this.lower_body(Some(decl), |this| {
3714 let e = this.lower_expr(body);
3715 is_generator = this.is_generator;
3718 let generator_option = if is_generator {
3719 if !decl.inputs.is_empty() {
3724 "generators cannot have explicit arguments"
3726 this.sess.abort_if_errors();
3728 Some(match movability {
3729 Movability::Movable => hir::GeneratorMovability::Movable,
3730 Movability::Static => hir::GeneratorMovability::Static,
3733 if movability == Movability::Static {
3738 "closures cannot be static"
3743 hir::ExprKind::Closure(
3744 this.lower_capture_clause(capture_clause),
3753 ExprKind::Block(ref blk, opt_label) => {
3754 hir::ExprKind::Block(self.lower_block(blk,
3755 opt_label.is_some()),
3756 self.lower_label(opt_label))
3758 ExprKind::Assign(ref el, ref er) => {
3759 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3761 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
3762 self.lower_binop(op),
3763 P(self.lower_expr(el)),
3764 P(self.lower_expr(er)),
3766 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
3767 ExprKind::Index(ref el, ref er) => {
3768 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
3770 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3771 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3772 let id = self.next_id();
3773 let e1 = self.lower_expr(e1);
3774 let e2 = self.lower_expr(e2);
3775 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
3776 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
3777 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3778 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3779 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
3780 hir::ExprKind::Call(new, hir_vec![e1, e2])
3782 ExprKind::Range(ref e1, ref e2, lims) => {
3783 use syntax::ast::RangeLimits::*;
3785 let path = match (e1, e2, lims) {
3786 (&None, &None, HalfOpen) => "RangeFull",
3787 (&Some(..), &None, HalfOpen) => "RangeFrom",
3788 (&None, &Some(..), HalfOpen) => "RangeTo",
3789 (&Some(..), &Some(..), HalfOpen) => "Range",
3790 (&None, &Some(..), Closed) => "RangeToInclusive",
3791 (&Some(..), &Some(..), Closed) => unreachable!(),
3792 (_, &None, Closed) => self.diagnostic()
3793 .span_fatal(e.span, "inclusive range with no end")
3797 let fields = e1.iter()
3798 .map(|e| ("start", e))
3799 .chain(e2.iter().map(|e| ("end", e)))
3801 let expr = P(self.lower_expr(&e));
3802 let ident = Ident::new(Symbol::intern(s), e.span);
3803 self.field(ident, expr, e.span)
3805 .collect::<P<[hir::Field]>>();
3807 let is_unit = fields.is_empty();
3808 let struct_path = iter::once("ops")
3809 .chain(iter::once(path))
3810 .collect::<Vec<_>>();
3811 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
3812 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3814 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3820 hir::ExprKind::Path(struct_path)
3822 hir::ExprKind::Struct(struct_path, fields, None)
3825 attrs: e.attrs.clone(),
3828 ExprKind::Path(ref qself, ref path) => hir::ExprKind::Path(self.lower_qpath(
3832 ParamMode::Optional,
3833 ImplTraitContext::Disallowed,
3835 ExprKind::Break(opt_label, ref opt_expr) => {
3836 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3839 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3842 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3844 hir::ExprKind::Break(
3846 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3849 ExprKind::Continue(opt_label) => {
3850 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
3853 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3856 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3859 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
3860 ExprKind::InlineAsm(ref asm) => {
3861 let hir_asm = hir::InlineAsm {
3862 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3863 outputs: asm.outputs
3865 .map(|out| hir::InlineAsmOutput {
3866 constraint: out.constraint.clone(),
3868 is_indirect: out.is_indirect,
3871 asm: asm.asm.clone(),
3872 asm_str_style: asm.asm_str_style,
3873 clobbers: asm.clobbers.clone().into(),
3874 volatile: asm.volatile,
3875 alignstack: asm.alignstack,
3876 dialect: asm.dialect,
3879 let outputs = asm.outputs
3881 .map(|out| self.lower_expr(&out.expr))
3883 let inputs = asm.inputs
3885 .map(|&(_, ref input)| self.lower_expr(input))
3887 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
3889 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
3894 ParamMode::Optional,
3895 ImplTraitContext::Disallowed,
3897 fields.iter().map(|x| self.lower_field(x)).collect(),
3898 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3900 ExprKind::Paren(ref ex) => {
3901 let mut ex = self.lower_expr(ex);
3902 // include parens in span, but only if it is a super-span.
3903 if e.span.contains(ex.span) {
3906 // merge attributes into the inner expression.
3907 let mut attrs = e.attrs.clone();
3908 attrs.extend::<Vec<_>>(ex.attrs.into());
3913 ExprKind::Yield(ref opt_expr) => {
3914 self.is_generator = true;
3917 .map(|x| self.lower_expr(x))
3919 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
3921 hir::ExprKind::Yield(P(expr))
3924 // Desugar ExprIfLet
3925 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3926 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3929 // match <sub_expr> {
3931 // _ => [<else_opt> | ()]
3934 let mut arms = vec![];
3936 // `<pat> => <body>`
3938 let body = self.lower_block(body, false);
3939 let body_expr = P(self.expr_block(body, ThinVec::new()));
3940 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3941 arms.push(self.arm(pats, body_expr));
3944 // _ => [<else_opt>|()]
3946 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3947 let wildcard_pattern = self.pat_wild(e.span);
3948 let body = if let Some(else_expr) = wildcard_arm {
3949 P(self.lower_expr(else_expr))
3951 self.expr_tuple(e.span, hir_vec![])
3953 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3956 let contains_else_clause = else_opt.is_some();
3958 let sub_expr = P(self.lower_expr(sub_expr));
3960 hir::ExprKind::Match(
3963 hir::MatchSource::IfLetDesugar {
3964 contains_else_clause,
3969 // Desugar ExprWhileLet
3970 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3971 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3974 // [opt_ident]: loop {
3975 // match <sub_expr> {
3981 // Note that the block AND the condition are evaluated in the loop scope.
3982 // This is done to allow `break` from inside the condition of the loop.
3983 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3985 this.lower_block(body, false),
3986 this.expr_break(e.span, ThinVec::new()),
3987 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3991 // `<pat> => <body>`
3993 let body_expr = P(self.expr_block(body, ThinVec::new()));
3994 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3995 self.arm(pats, body_expr)
4000 let pat_under = self.pat_wild(e.span);
4001 self.arm(hir_vec![pat_under], break_expr)
4004 // `match <sub_expr> { ... }`
4005 let arms = hir_vec![pat_arm, break_arm];
4006 let match_expr = self.expr(
4008 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4012 // `[opt_ident]: loop { ... }`
4013 let loop_block = P(self.block_expr(P(match_expr)));
4014 let loop_expr = hir::ExprKind::Loop(
4016 self.lower_label(opt_label),
4017 hir::LoopSource::WhileLet,
4019 // add attributes to the outer returned expr node
4023 // Desugar ExprForLoop
4024 // From: `[opt_ident]: for <pat> in <head> <body>`
4025 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4029 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4031 // [opt_ident]: loop {
4033 // match ::std::iter::Iterator::next(&mut iter) {
4034 // ::std::option::Option::Some(val) => __next = val,
4035 // ::std::option::Option::None => break
4037 // let <pat> = __next;
4038 // StmtKind::Expr(<body>);
4046 let head = self.lower_expr(head);
4047 let head_sp = head.span;
4049 let iter = self.str_to_ident("iter");
4051 let next_ident = self.str_to_ident("__next");
4052 let next_sp = self.allow_internal_unstable(
4053 CompilerDesugaringKind::ForLoop,
4056 let next_pat = self.pat_ident_binding_mode(
4059 hir::BindingAnnotation::Mutable,
4062 // `::std::option::Option::Some(val) => next = val`
4064 let val_ident = self.str_to_ident("val");
4065 let val_pat = self.pat_ident(pat.span, val_ident);
4066 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4067 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4068 let assign = P(self.expr(
4070 hir::ExprKind::Assign(next_expr, val_expr),
4073 let some_pat = self.pat_some(pat.span, val_pat);
4074 self.arm(hir_vec![some_pat], assign)
4077 // `::std::option::Option::None => break`
4080 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4081 let pat = self.pat_none(e.span);
4082 self.arm(hir_vec![pat], break_expr)
4087 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
4089 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4091 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4092 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4093 let next_path = &["iter", "Iterator", "next"];
4094 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4095 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4096 let arms = hir_vec![pat_arm, break_arm];
4100 hir::ExprKind::Match(
4103 hir::MatchSource::ForLoopDesugar
4108 let match_stmt = respan(
4110 hir::StmtKind::Expr(match_expr, self.next_id().node_id)
4113 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4117 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
4119 // `let <pat> = __next`
4120 let pat = self.lower_pat(pat);
4121 let pat_let = self.stmt_let_pat(
4125 hir::LocalSource::ForLoopDesugar,
4128 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4129 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4130 let body_stmt = respan(
4132 hir::StmtKind::Expr(body_expr, self.next_id().node_id)
4135 let loop_block = P(self.block_all(
4137 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4141 // `[opt_ident]: loop { ... }`
4142 let loop_expr = hir::ExprKind::Loop(
4144 self.lower_label(opt_label),
4145 hir::LoopSource::ForLoop,
4147 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4148 let loop_expr = P(hir::Expr {
4153 attrs: ThinVec::new(),
4156 // `mut iter => { ... }`
4157 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4159 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4160 let into_iter_expr = {
4161 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4162 let into_iter = P(self.expr_std_path(
4163 head_sp, into_iter_path, None, ThinVec::new()));
4164 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4167 let match_expr = P(self.expr_match(
4171 hir::MatchSource::ForLoopDesugar,
4174 // `{ let _result = ...; _result }`
4175 // underscore prevents an unused_variables lint if the head diverges
4176 let result_ident = self.str_to_ident("_result");
4177 let (let_stmt, let_stmt_binding) =
4178 self.stmt_let(e.span, false, result_ident, match_expr);
4180 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4181 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4182 // add the attributes to the outer returned expr node
4183 return self.expr_block(block, e.attrs.clone());
4186 // Desugar ExprKind::Try
4188 ExprKind::Try(ref sub_expr) => {
4191 // match Try::into_result(<expr>) {
4192 // Ok(val) => #[allow(unreachable_code)] val,
4193 // Err(err) => #[allow(unreachable_code)]
4194 // // If there is an enclosing `catch {...}`
4195 // break 'catch_target Try::from_error(From::from(err)),
4197 // return Try::from_error(From::from(err)),
4201 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4203 // Try::into_result(<expr>)
4206 let sub_expr = self.lower_expr(sub_expr);
4208 let path = &["ops", "Try", "into_result"];
4209 let path = P(self.expr_std_path(
4210 unstable_span, path, None, ThinVec::new()));
4211 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4214 // #[allow(unreachable_code)]
4216 // allow(unreachable_code)
4218 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4219 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4220 let uc_nested = attr::mk_nested_word_item(uc_ident);
4221 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4223 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4225 let attrs = vec![attr];
4227 // Ok(val) => #[allow(unreachable_code)] val,
4229 let val_ident = self.str_to_ident("val");
4230 let val_pat = self.pat_ident(e.span, val_ident);
4231 let val_expr = P(self.expr_ident_with_attrs(
4235 ThinVec::from(attrs.clone()),
4237 let ok_pat = self.pat_ok(e.span, val_pat);
4239 self.arm(hir_vec![ok_pat], val_expr)
4242 // Err(err) => #[allow(unreachable_code)]
4243 // return Try::from_error(From::from(err)),
4245 let err_ident = self.str_to_ident("err");
4246 let err_local = self.pat_ident(e.span, err_ident);
4248 let path = &["convert", "From", "from"];
4249 let from = P(self.expr_std_path(
4250 e.span, path, None, ThinVec::new()));
4251 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4253 self.expr_call(e.span, from, hir_vec![err_expr])
4256 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4257 let thin_attrs = ThinVec::from(attrs);
4258 let catch_scope = self.catch_scopes.last().map(|x| *x);
4259 let ret_expr = if let Some(catch_node) = catch_scope {
4262 hir::ExprKind::Break(
4265 target_id: Ok(catch_node),
4267 Some(from_err_expr),
4272 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4275 let err_pat = self.pat_err(e.span, err_local);
4276 self.arm(hir_vec![err_pat], ret_expr)
4279 hir::ExprKind::Match(
4281 hir_vec![err_arm, ok_arm],
4282 hir::MatchSource::TryDesugar,
4286 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4289 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4296 attrs: e.attrs.clone(),
4300 fn lower_stmt(&mut self, s: &Stmt) -> OneVector<hir::Stmt> {
4301 smallvec![match s.node {
4302 StmtKind::Local(ref l) => Spanned {
4303 node: hir::StmtKind::Decl(
4305 node: hir::DeclKind::Local(self.lower_local(l)),
4308 self.lower_node_id(s.id).node_id,
4312 StmtKind::Item(ref it) => {
4313 // Can only use the ID once.
4314 let mut id = Some(s.id);
4315 return self.lower_item_id(it)
4317 .map(|item_id| Spanned {
4318 node: hir::StmtKind::Decl(
4320 node: hir::DeclKind::Item(item_id),
4324 .map(|id| self.lower_node_id(id).node_id)
4325 .unwrap_or_else(|| self.next_id().node_id),
4331 StmtKind::Expr(ref e) => Spanned {
4332 node: hir::StmtKind::Expr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4335 StmtKind::Semi(ref e) => Spanned {
4336 node: hir::StmtKind::Semi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4339 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4343 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4345 CaptureBy::Value => hir::CaptureByValue,
4346 CaptureBy::Ref => hir::CaptureByRef,
4350 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4351 /// the address space of that item instead of the item currently being
4352 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4353 /// lower a `Visibility` value although we haven't lowered the owning
4354 /// `ImplItem` in question yet.
4355 fn lower_visibility(
4358 explicit_owner: Option<NodeId>,
4359 ) -> hir::Visibility {
4360 let node = match v.node {
4361 VisibilityKind::Public => hir::VisibilityKind::Public,
4362 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4363 VisibilityKind::Restricted { ref path, id } => {
4364 let lowered_id = if let Some(owner) = explicit_owner {
4365 self.lower_node_id_with_owner(id, owner)
4367 self.lower_node_id(id)
4369 hir::VisibilityKind::Restricted {
4370 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4371 id: lowered_id.node_id,
4372 hir_id: lowered_id.hir_id,
4375 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4377 respan(v.span, node)
4380 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4382 Defaultness::Default => hir::Defaultness::Default {
4383 has_value: has_value,
4385 Defaultness::Final => {
4387 hir::Defaultness::Final
4392 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4394 BlockCheckMode::Default => hir::DefaultBlock,
4395 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4399 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4401 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4402 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4403 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4404 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4408 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4410 CompilerGenerated => hir::CompilerGenerated,
4411 UserProvided => hir::UserProvided,
4415 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4417 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4418 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4422 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4424 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4425 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4429 // Helper methods for building HIR.
4431 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4440 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4442 id: self.next_id().node_id,
4446 is_shorthand: false,
4450 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4451 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4452 P(self.expr(span, expr_break, attrs))
4459 args: hir::HirVec<hir::Expr>,
4461 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4464 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4465 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4468 fn expr_ident_with_attrs(
4473 attrs: ThinVec<Attribute>,
4475 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4479 def: Def::Local(binding),
4480 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4484 self.expr(span, expr_path, attrs)
4487 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4488 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4494 components: &[&str],
4495 params: Option<P<hir::GenericArgs>>,
4496 attrs: ThinVec<Attribute>,
4498 let path = self.std_path(span, components, params, true);
4501 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4510 arms: hir::HirVec<hir::Arm>,
4511 source: hir::MatchSource,
4513 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4516 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4517 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4520 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4521 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4524 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4525 let LoweredNodeId { node_id, hir_id } = self.next_id();
4538 ex: Option<P<hir::Expr>>,
4540 source: hir::LocalSource,
4542 let LoweredNodeId { node_id, hir_id } = self.next_id();
4544 let local = P(hir::Local {
4551 attrs: ThinVec::new(),
4554 let decl = respan(sp, hir::DeclKind::Local(local));
4555 respan(sp, hir::StmtKind::Decl(P(decl), self.next_id().node_id))
4564 ) -> (hir::Stmt, NodeId) {
4565 let pat = if mutbl {
4566 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4568 self.pat_ident(sp, ident)
4570 let pat_id = pat.id;
4572 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4577 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4578 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4584 stmts: hir::HirVec<hir::Stmt>,
4585 expr: Option<P<hir::Expr>>,
4587 let LoweredNodeId { node_id, hir_id } = self.next_id();
4594 rules: hir::DefaultBlock,
4596 targeted_by_break: false,
4601 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4602 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4605 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4606 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4609 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4610 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4613 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4614 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4620 components: &[&str],
4621 subpats: hir::HirVec<P<hir::Pat>>,
4623 let path = self.std_path(span, components, None, true);
4624 let qpath = hir::QPath::Resolved(None, P(path));
4625 let pt = if subpats.is_empty() {
4626 hir::PatKind::Path(qpath)
4628 hir::PatKind::TupleStruct(qpath, subpats, None)
4633 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4634 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4637 fn pat_ident_binding_mode(
4641 bm: hir::BindingAnnotation,
4643 let LoweredNodeId { node_id, hir_id } = self.next_id();
4648 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4653 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4654 self.pat(span, hir::PatKind::Wild)
4657 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4658 let LoweredNodeId { node_id, hir_id } = self.next_id();
4667 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4668 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4669 /// The path is also resolved according to `is_value`.
4673 components: &[&str],
4674 params: Option<P<hir::GenericArgs>>,
4678 .resolve_str_path(span, self.crate_root, components, params, is_value)
4681 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4683 let node = match qpath {
4684 hir::QPath::Resolved(None, path) => {
4685 // Turn trait object paths into `TyKind::TraitObject` instead.
4686 if let Def::Trait(_) = path.def {
4687 let principal = hir::PolyTraitRef {
4688 bound_generic_params: hir::HirVec::new(),
4689 trait_ref: hir::TraitRef {
4690 path: path.and_then(|path| path),
4692 hir_ref_id: id.hir_id,
4697 // The original ID is taken by the `PolyTraitRef`,
4698 // so the `Ty` itself needs a different one.
4699 id = self.next_id();
4700 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4702 hir::TyKind::Path(hir::QPath::Resolved(None, path))
4705 _ => hir::TyKind::Path(qpath),
4715 /// Invoked to create the lifetime argument for a type `&T`
4716 /// with no explicit lifetime.
4717 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4718 match self.anonymous_lifetime_mode {
4719 // Intercept when we are in an impl header and introduce an in-band lifetime.
4720 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4722 AnonymousLifetimeMode::CreateParameter => {
4723 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4725 id: self.next_id().node_id,
4727 name: hir::LifetimeName::Param(fresh_name),
4731 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4735 /// Invoked to create the lifetime argument(s) for a path like
4736 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4737 /// sorts of cases are deprecated. This may therefore report a warning or an
4738 /// error, depending on the mode.
4739 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4740 match self.anonymous_lifetime_mode {
4741 // NB. We intentionally ignore the create-parameter mode here
4742 // and instead "pass through" to resolve-lifetimes, which will then
4743 // report an error. This is because we don't want to support
4744 // impl elision for deprecated forms like
4746 // impl Foo for std::cell::Ref<u32> // note lack of '_
4747 AnonymousLifetimeMode::CreateParameter => {}
4749 // This is the normal case.
4750 AnonymousLifetimeMode::PassThrough => {}
4754 .map(|_| self.new_implicit_lifetime(span))
4758 /// Invoked to create the lifetime argument(s) for an elided trait object
4759 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4760 /// when the bound is written, even if it is written with `'_` like in
4761 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4762 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4763 match self.anonymous_lifetime_mode {
4764 // NB. We intentionally ignore the create-parameter mode here.
4765 // and instead "pass through" to resolve-lifetimes, which will apply
4766 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4767 // do not act like other elided lifetimes. In other words, given this:
4769 // impl Foo for Box<dyn Debug>
4771 // we do not introduce a fresh `'_` to serve as the bound, but instead
4772 // ultimately translate to the equivalent of:
4774 // impl Foo for Box<dyn Debug + 'static>
4776 // `resolve_lifetime` has the code to make that happen.
4777 AnonymousLifetimeMode::CreateParameter => {}
4779 // This is the normal case.
4780 AnonymousLifetimeMode::PassThrough => {}
4783 self.new_implicit_lifetime(span)
4786 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4788 id: self.next_id().node_id,
4790 name: hir::LifetimeName::Implicit,
4794 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4795 self.sess.buffer_lint_with_diagnostic(
4796 builtin::BARE_TRAIT_OBJECTS,
4799 "trait objects without an explicit `dyn` are deprecated",
4800 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4804 fn wrap_in_try_constructor(
4806 method: &'static str,
4808 unstable_span: Span,
4810 let path = &["ops", "Try", method];
4811 let from_err = P(self.expr_std_path(unstable_span, path, None,
4813 P(self.expr_call(e.span, from_err, hir_vec![e]))
4817 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4818 // Sorting by span ensures that we get things in order within a
4819 // file, and also puts the files in a sensible order.
4820 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4821 body_ids.sort_by_key(|b| bodies[b].value.span);