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::indexed_vec::IndexVec;
54 use rustc_data_structures::small_vec::OneVector;
55 use rustc_data_structures::thin_vec::ThinVec;
57 use util::common::FN_OUTPUT_NAME;
58 use util::nodemap::{DefIdMap, NodeMap};
60 use std::collections::{BTreeMap, HashSet};
68 use syntax::ext::hygiene::{Mark, SyntaxContext};
69 use syntax::print::pprust;
71 use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned};
72 use syntax::std_inject;
73 use syntax::symbol::{keywords, Symbol};
74 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
75 use syntax::parse::token::Token;
76 use syntax::visit::{self, Visitor};
77 use syntax_pos::{Span, MultiSpan};
79 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
81 pub struct LoweringContext<'a> {
82 crate_root: Option<&'static str>,
84 // Use to assign ids to hir nodes that do not directly correspond to an ast node
87 cstore: &'a dyn CrateStore,
89 resolver: &'a mut dyn Resolver,
91 /// The items being lowered are collected here.
92 items: BTreeMap<NodeId, hir::Item>,
94 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
95 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
96 bodies: BTreeMap<hir::BodyId, hir::Body>,
97 exported_macros: Vec<hir::MacroDef>,
99 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
100 trait_auto_impl: BTreeMap<DefId, NodeId>,
104 catch_scopes: Vec<NodeId>,
105 loop_scopes: Vec<NodeId>,
106 is_in_loop_condition: bool,
107 is_in_trait_impl: bool,
109 /// What to do when we encounter either an "anonymous lifetime
110 /// reference". The term "anonymous" is meant to encompass both
111 /// `'_` lifetimes as well as fully elided cases where nothing is
112 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
113 anonymous_lifetime_mode: AnonymousLifetimeMode,
115 // Used to create lifetime definitions from in-band lifetime usages.
116 // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
117 // When a named lifetime is encountered in a function or impl header and
118 // has not been defined
119 // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
120 // to this list. The results of this list are then added to the list of
121 // lifetime definitions in the corresponding impl or function generics.
122 lifetimes_to_define: Vec<(Span, ParamName)>,
124 // Whether or not in-band lifetimes are being collected. This is used to
125 // indicate whether or not we're in a place where new lifetimes will result
126 // in in-band lifetime definitions, such a function or an impl header.
127 // This will always be false unless the `in_band_lifetimes` or
128 // `impl_header_lifetime_elision` feature is enabled.
129 is_collecting_in_band_lifetimes: bool,
131 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
132 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
133 // against this list to see if it is already in-scope, or if a definition
134 // needs to be created for it.
135 in_scope_lifetimes: Vec<Ident>,
137 type_def_lifetime_params: DefIdMap<usize>,
139 current_hir_id_owner: Vec<(DefIndex, u32)>,
140 item_local_id_counters: NodeMap<u32>,
141 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
145 /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
146 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
148 /// Obtain the resolution for a node id
149 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
151 /// Obtain the possible resolutions for the given `use` statement.
152 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
154 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
155 /// This should only return `None` during testing.
156 fn definitions(&mut self) -> &mut Definitions;
158 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
159 /// it based on `is_value`.
163 crate_root: Option<&str>,
165 params: Option<P<hir::GenericArgs>>,
171 enum ImplTraitContext<'a> {
172 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
173 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
174 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
176 /// Newly generated parameters should be inserted into the given `Vec`
177 Universal(&'a mut Vec<hir::GenericParam>),
179 /// Treat `impl Trait` as shorthand for a new universal existential parameter.
180 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
181 /// equivalent to a fresh existential parameter like `abstract type T; fn foo() -> T`.
183 /// We store a DefId here so we can look up necessary information later
186 /// `impl Trait` is not accepted in this position.
190 impl<'a> ImplTraitContext<'a> {
191 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
192 use self::ImplTraitContext::*;
194 Universal(params) => Universal(params),
195 Existential(did) => Existential(*did),
196 Disallowed => Disallowed,
203 cstore: &dyn CrateStore,
204 dep_graph: &DepGraph,
206 resolver: &mut dyn Resolver,
208 // We're constructing the HIR here; we don't care what we will
209 // read, since we haven't even constructed the *input* to
211 dep_graph.assert_ignored();
214 crate_root: std_inject::injected_crate_name(),
218 items: BTreeMap::new(),
219 trait_items: BTreeMap::new(),
220 impl_items: BTreeMap::new(),
221 bodies: BTreeMap::new(),
222 trait_impls: BTreeMap::new(),
223 trait_auto_impl: BTreeMap::new(),
224 exported_macros: Vec::new(),
225 catch_scopes: Vec::new(),
226 loop_scopes: Vec::new(),
227 is_in_loop_condition: false,
228 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
229 type_def_lifetime_params: DefIdMap(),
230 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
231 item_local_id_counters: NodeMap(),
232 node_id_to_hir_id: IndexVec::new(),
234 is_in_trait_impl: false,
235 lifetimes_to_define: Vec::new(),
236 is_collecting_in_band_lifetimes: false,
237 in_scope_lifetimes: Vec::new(),
241 #[derive(Copy, Clone, PartialEq)]
243 /// Any path in a type context.
245 /// The `module::Type` in `module::Type::method` in an expression.
250 struct LoweredNodeId {
255 enum ParenthesizedGenericArgs {
261 /// What to do when we encounter an **anonymous** lifetime
262 /// reference. Anonymous lifetime references come in two flavors. You
263 /// have implicit, or fully elided, references to lifetimes, like the
264 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
265 /// or `Ref<'_, T>`. These often behave the same, but not always:
267 /// - certain usages of implicit references are deprecated, like
268 /// `Ref<T>`, and we sometimes just give hard errors in those cases
270 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
271 /// the same as `Box<dyn Foo + '_>`.
273 /// We describe the effects of the various modes in terms of three cases:
275 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
276 /// of a `&` (e.g., the missing lifetime in something like `&T`)
277 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
278 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
279 /// elided bounds follow special rules. Note that this only covers
280 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
281 /// '_>` is a case of "modern" elision.
282 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
283 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
284 /// non-deprecated equivalent.
286 /// Currently, the handling of lifetime elision is somewhat spread out
287 /// between HIR lowering and -- as described below -- the
288 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
289 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
290 /// everything into HIR lowering.
291 #[derive(Copy, Clone)]
292 enum AnonymousLifetimeMode {
293 /// For **Modern** cases, create a new anonymous region parameter
294 /// and reference that.
296 /// For **Dyn Bound** cases, pass responsibility to
297 /// `resolve_lifetime` code.
299 /// For **Deprecated** cases, report an error.
302 /// Pass responsibility to `resolve_lifetime` code for all cases.
306 impl<'a> LoweringContext<'a> {
307 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
308 /// Full-crate AST visitor that inserts into a fresh
309 /// `LoweringContext` any information that may be
310 /// needed from arbitrary locations in the crate.
311 /// E.g. The number of lifetime generic parameters
312 /// declared for every type and trait definition.
313 struct MiscCollector<'lcx, 'interner: 'lcx> {
314 lctx: &'lcx mut LoweringContext<'interner>,
317 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
318 fn visit_item(&mut self, item: &'lcx Item) {
319 self.lctx.allocate_hir_id_counter(item.id, item);
322 ItemKind::Struct(_, ref generics)
323 | ItemKind::Union(_, ref generics)
324 | ItemKind::Enum(_, ref generics)
325 | ItemKind::Ty(_, ref generics)
326 | ItemKind::Existential(_, ref generics)
327 | ItemKind::Trait(_, _, ref generics, ..) => {
328 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
332 .filter(|param| match param.kind {
333 ast::GenericParamKind::Lifetime { .. } => true,
337 self.lctx.type_def_lifetime_params.insert(def_id, count);
341 visit::walk_item(self, item);
344 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
345 self.lctx.allocate_hir_id_counter(item.id, item);
346 visit::walk_trait_item(self, item);
349 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
350 self.lctx.allocate_hir_id_counter(item.id, item);
351 visit::walk_impl_item(self, item);
355 struct ItemLowerer<'lcx, 'interner: 'lcx> {
356 lctx: &'lcx mut LoweringContext<'interner>,
359 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
360 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
362 F: FnOnce(&mut Self),
364 let old = self.lctx.is_in_trait_impl;
365 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
371 self.lctx.is_in_trait_impl = old;
375 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
376 fn visit_item(&mut self, item: &'lcx Item) {
377 let mut item_lowered = true;
378 self.lctx.with_hir_id_owner(item.id, |lctx| {
379 if let Some(hir_item) = lctx.lower_item(item) {
380 lctx.items.insert(item.id, hir_item);
382 item_lowered = false;
387 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
388 hir::ItemKind::Impl(_, _, _, ref generics, ..)
389 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
390 generics.params.clone()
395 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
396 let this = &mut ItemLowerer { lctx: this };
397 if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
398 this.with_trait_impl_ref(opt_trait_ref, |this| {
399 visit::walk_item(this, item)
402 visit::walk_item(this, item);
408 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
409 self.lctx.with_hir_id_owner(item.id, |lctx| {
410 let id = hir::TraitItemId { node_id: item.id };
411 let hir_item = lctx.lower_trait_item(item);
412 lctx.trait_items.insert(id, hir_item);
415 visit::walk_trait_item(self, item);
418 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
419 self.lctx.with_hir_id_owner(item.id, |lctx| {
420 let id = hir::ImplItemId { node_id: item.id };
421 let hir_item = lctx.lower_impl_item(item);
422 lctx.impl_items.insert(id, hir_item);
424 visit::walk_impl_item(self, item);
428 self.lower_node_id(CRATE_NODE_ID);
429 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
431 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
432 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
434 let module = self.lower_mod(&c.module);
435 let attrs = self.lower_attrs(&c.attrs);
436 let body_ids = body_ids(&self.bodies);
440 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
446 exported_macros: hir::HirVec::from(self.exported_macros),
448 trait_items: self.trait_items,
449 impl_items: self.impl_items,
452 trait_impls: self.trait_impls,
453 trait_auto_impl: self.trait_auto_impl,
457 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
458 if self.item_local_id_counters.insert(owner, 0).is_some() {
460 "Tried to allocate item_local_id_counter for {:?} twice",
464 // Always allocate the first HirId for the owner itself
465 self.lower_node_id_with_owner(owner, owner)
468 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
470 F: FnOnce(&mut Self) -> hir::HirId,
472 if ast_node_id == DUMMY_NODE_ID {
473 return LoweredNodeId {
474 node_id: DUMMY_NODE_ID,
475 hir_id: hir::DUMMY_HIR_ID,
479 let min_size = ast_node_id.as_usize() + 1;
481 if min_size > self.node_id_to_hir_id.len() {
482 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
485 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
487 if existing_hir_id == hir::DUMMY_HIR_ID {
488 // Generate a new HirId
489 let hir_id = alloc_hir_id(self);
490 self.node_id_to_hir_id[ast_node_id] = hir_id;
492 node_id: ast_node_id,
497 node_id: ast_node_id,
498 hir_id: existing_hir_id,
503 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
505 F: FnOnce(&mut Self) -> T,
507 let counter = self.item_local_id_counters
508 .insert(owner, HIR_ID_COUNTER_LOCKED)
509 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
510 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
511 self.current_hir_id_owner.push((def_index, counter));
513 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
515 debug_assert!(def_index == new_def_index);
516 debug_assert!(new_counter >= counter);
518 let prev = self.item_local_id_counters
519 .insert(owner, new_counter)
521 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
525 /// This method allocates a new HirId for the given NodeId and stores it in
526 /// the LoweringContext's NodeId => HirId map.
527 /// Take care not to call this method if the resulting HirId is then not
528 /// actually used in the HIR, as that would trigger an assertion in the
529 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
530 /// properly. Calling the method twice with the same NodeId is fine though.
531 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
532 self.lower_node_id_generic(ast_node_id, |this| {
533 let &mut (def_index, ref mut local_id_counter) =
534 this.current_hir_id_owner.last_mut().unwrap();
535 let local_id = *local_id_counter;
536 *local_id_counter += 1;
539 local_id: hir::ItemLocalId(local_id),
544 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
545 self.lower_node_id_generic(ast_node_id, |this| {
546 let local_id_counter = this
547 .item_local_id_counters
549 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
550 let local_id = *local_id_counter;
552 // We want to be sure not to modify the counter in the map while it
553 // is also on the stack. Otherwise we'll get lost updates when writing
554 // back from the stack to the map.
555 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
557 *local_id_counter += 1;
561 .opt_def_index(owner)
562 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
563 that do not belong to the current owner");
567 local_id: hir::ItemLocalId(local_id),
572 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
573 let body = hir::Body {
574 arguments: decl.map_or(hir_vec![], |decl| {
575 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
577 is_generator: self.is_generator,
581 self.bodies.insert(id, body);
585 fn next_id(&mut self) -> LoweredNodeId {
586 self.lower_node_id(self.sess.next_node_id())
589 fn expect_full_def(&mut self, id: NodeId) -> Def {
590 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
591 if pr.unresolved_segments() != 0 {
592 bug!("path not fully resolved: {:?}", pr);
598 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item=Def> {
599 self.resolver.get_import(id).present_items().map(|pr| {
600 if pr.unresolved_segments() != 0 {
601 bug!("path not fully resolved: {:?}", pr);
607 fn diagnostic(&self) -> &errors::Handler {
608 self.sess.diagnostic()
611 fn str_to_ident(&self, s: &'static str) -> Ident {
612 Ident::with_empty_ctxt(Symbol::gensym(s))
615 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
616 let mark = Mark::fresh(Mark::root());
617 mark.set_expn_info(source_map::ExpnInfo {
619 def_site: Some(span),
620 format: source_map::CompilerDesugaring(reason),
621 allow_internal_unstable: true,
622 allow_internal_unsafe: false,
623 local_inner_macros: false,
624 edition: source_map::hygiene::default_edition(),
626 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
629 fn with_anonymous_lifetime_mode<R>(
631 anonymous_lifetime_mode: AnonymousLifetimeMode,
632 op: impl FnOnce(&mut Self) -> R,
634 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
635 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
636 let result = op(self);
637 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
641 /// Creates a new hir::GenericParam for every new lifetime and
642 /// type parameter encountered while evaluating `f`. Definitions
643 /// are created with the parent provided. If no `parent_id` is
644 /// provided, no definitions will be returned.
646 /// Presuming that in-band lifetimes are enabled, then
647 /// `self.anonymous_lifetime_mode` will be updated to match the
648 /// argument while `f` is running (and restored afterwards).
649 fn collect_in_band_defs<T, F>(
652 anonymous_lifetime_mode: AnonymousLifetimeMode,
654 ) -> (Vec<hir::GenericParam>, T)
656 F: FnOnce(&mut LoweringContext) -> (Vec<hir::GenericParam>, T),
658 assert!(!self.is_collecting_in_band_lifetimes);
659 assert!(self.lifetimes_to_define.is_empty());
660 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
662 if self.sess.features_untracked().impl_header_lifetime_elision {
663 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
664 self.is_collecting_in_band_lifetimes = true;
665 } else if self.sess.features_untracked().in_band_lifetimes {
666 self.is_collecting_in_band_lifetimes = true;
669 let (in_band_ty_params, res) = f(self);
671 self.is_collecting_in_band_lifetimes = false;
672 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
674 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
676 let params = lifetimes_to_define
678 .map(|(span, hir_name)| {
679 let def_node_id = self.next_id().node_id;
681 // Get the name we'll use to make the def-path. Note
682 // that collisions are ok here and this shouldn't
683 // really show up for end-user.
684 let str_name = match hir_name {
685 ParamName::Plain(ident) => ident.as_interned_str(),
686 ParamName::Fresh(_) => keywords::UnderscoreLifetime.name().as_interned_str(),
689 // Add a definition for the in-band lifetime def
690 self.resolver.definitions().create_def_with_parent(
693 DefPathData::LifetimeParam(str_name),
694 DefIndexAddressSpace::High,
705 pure_wrt_drop: false,
706 kind: hir::GenericParamKind::Lifetime { in_band: true }
709 .chain(in_band_ty_params.into_iter())
715 /// When there is a reference to some lifetime `'a`, and in-band
716 /// lifetimes are enabled, then we want to push that lifetime into
717 /// the vector of names to define later. In that case, it will get
718 /// added to the appropriate generics.
719 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
720 if !self.is_collecting_in_band_lifetimes {
724 if !self.sess.features_untracked().in_band_lifetimes {
728 if self.in_scope_lifetimes.contains(&ident.modern()) {
732 let hir_name = ParamName::Plain(ident);
734 if self.lifetimes_to_define.iter()
735 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
739 self.lifetimes_to_define.push((ident.span, hir_name));
742 /// When we have either an elided or `'_` lifetime in an impl
743 /// header, we convert it to
744 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
745 assert!(self.is_collecting_in_band_lifetimes);
746 let index = self.lifetimes_to_define.len();
747 let hir_name = ParamName::Fresh(index);
748 self.lifetimes_to_define.push((span, hir_name));
752 // Evaluates `f` with the lifetimes in `params` in-scope.
753 // This is used to track which lifetimes have already been defined, and
754 // which are new in-band lifetimes that need to have a definition created
756 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
758 F: FnOnce(&mut LoweringContext) -> T,
760 let old_len = self.in_scope_lifetimes.len();
761 let lt_def_names = params.iter().filter_map(|param| match param.kind {
762 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
765 self.in_scope_lifetimes.extend(lt_def_names);
769 self.in_scope_lifetimes.truncate(old_len);
773 // Same as the method above, but accepts `hir::GenericParam`s
774 // instead of `ast::GenericParam`s.
775 // This should only be used with generics that have already had their
776 // in-band lifetimes added. In practice, this means that this function is
777 // only used when lowering a child item of a trait or impl.
778 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
779 params: &HirVec<hir::GenericParam>,
782 F: FnOnce(&mut LoweringContext) -> T,
784 let old_len = self.in_scope_lifetimes.len();
785 let lt_def_names = params.iter().filter_map(|param| match param.kind {
786 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
789 self.in_scope_lifetimes.extend(lt_def_names);
793 self.in_scope_lifetimes.truncate(old_len);
797 /// Appends in-band lifetime defs and argument-position `impl
798 /// Trait` defs to the existing set of generics.
800 /// Presuming that in-band lifetimes are enabled, then
801 /// `self.anonymous_lifetime_mode` will be updated to match the
802 /// argument while `f` is running (and restored afterwards).
803 fn add_in_band_defs<F, T>(
807 anonymous_lifetime_mode: AnonymousLifetimeMode,
809 ) -> (hir::Generics, T)
811 F: FnOnce(&mut LoweringContext, &mut Vec<hir::GenericParam>) -> T,
813 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
816 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
817 let mut params = Vec::new();
818 let generics = this.lower_generics(
820 ImplTraitContext::Universal(&mut params),
822 let res = f(this, &mut params);
823 (params, (generics, res))
828 lowered_generics.params = lowered_generics
835 (lowered_generics, res)
838 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
840 F: FnOnce(&mut LoweringContext) -> T,
842 let len = self.catch_scopes.len();
843 self.catch_scopes.push(catch_id);
845 let result = f(self);
848 self.catch_scopes.len(),
849 "catch scopes should be added and removed in stack order"
852 self.catch_scopes.pop().unwrap();
859 capture_clause: CaptureBy,
860 closure_node_id: NodeId,
862 body: impl FnOnce(&mut LoweringContext) -> hir::Expr,
864 let prev_is_generator = mem::replace(&mut self.is_generator, true);
865 let body_expr = body(self);
866 let span = body_expr.span;
867 let output = match ret_ty {
868 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
869 None => FunctionRetTy::Default(span),
876 let body_id = self.record_body(body_expr, Some(&decl));
877 self.is_generator = prev_is_generator;
879 let capture_clause = self.lower_capture_clause(capture_clause);
880 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
881 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
882 let generator = hir::Expr {
884 hir_id: closure_hir_id,
885 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
886 Some(hir::GeneratorMovability::Static)),
888 attrs: ThinVec::new(),
891 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
892 let gen_future = self.expr_std_path(
893 unstable_span, &["future", "from_generator"], None, ThinVec::new());
894 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
897 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
899 F: FnOnce(&mut LoweringContext) -> hir::Expr,
901 let prev = mem::replace(&mut self.is_generator, false);
902 let result = f(self);
903 let r = self.record_body(result, decl);
904 self.is_generator = prev;
908 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
910 F: FnOnce(&mut LoweringContext) -> T,
912 // We're no longer in the base loop's condition; we're in another loop.
913 let was_in_loop_condition = self.is_in_loop_condition;
914 self.is_in_loop_condition = false;
916 let len = self.loop_scopes.len();
917 self.loop_scopes.push(loop_id);
919 let result = f(self);
922 self.loop_scopes.len(),
923 "Loop scopes should be added and removed in stack order"
926 self.loop_scopes.pop().unwrap();
928 self.is_in_loop_condition = was_in_loop_condition;
933 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
935 F: FnOnce(&mut LoweringContext) -> T,
937 let was_in_loop_condition = self.is_in_loop_condition;
938 self.is_in_loop_condition = true;
940 let result = f(self);
942 self.is_in_loop_condition = was_in_loop_condition;
947 fn with_new_scopes<T, F>(&mut self, f: F) -> T
949 F: FnOnce(&mut LoweringContext) -> T,
951 let was_in_loop_condition = self.is_in_loop_condition;
952 self.is_in_loop_condition = false;
954 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
955 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
956 let result = f(self);
957 self.catch_scopes = catch_scopes;
958 self.loop_scopes = loop_scopes;
960 self.is_in_loop_condition = was_in_loop_condition;
965 fn def_key(&mut self, id: DefId) -> DefKey {
967 self.resolver.definitions().def_key(id.index)
969 self.cstore.def_key(id)
973 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
974 label.map(|label| hir::Label {
979 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
980 let target_id = match destination {
982 if let Def::Label(loop_id) = self.expect_full_def(id) {
983 Ok(self.lower_node_id(loop_id).node_id)
985 Err(hir::LoopIdError::UnresolvedLabel)
991 .map(|innermost_loop_id| *innermost_loop_id)
992 .map(|id| Ok(self.lower_node_id(id).node_id))
993 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
998 label: self.lower_label(destination.map(|(_, label)| label)),
1003 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1006 .map(|a| self.lower_attr(a))
1007 .collect::<Vec<_>>()
1011 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1015 path: attr.path.clone(),
1016 tokens: self.lower_token_stream(attr.tokens.clone()),
1017 is_sugared_doc: attr.is_sugared_doc,
1022 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1025 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1029 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1031 TokenTree::Token(span, token) => self.lower_token(token, span),
1032 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1035 delim: delimited.delim,
1036 tts: self.lower_token_stream(delimited.tts.into()).into(),
1042 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1044 Token::Interpolated(_) => {}
1045 other => return TokenTree::Token(span, other).into(),
1048 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1049 self.lower_token_stream(tts)
1052 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1054 attrs: self.lower_attrs(&arm.attrs),
1055 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1056 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1057 body: P(self.lower_expr(&arm.body)),
1061 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1063 id: self.lower_node_id(b.id).node_id,
1065 ty: self.lower_ty(&b.ty, itctx),
1070 fn lower_generic_arg(&mut self,
1071 arg: &ast::GenericArg,
1072 itctx: ImplTraitContext)
1073 -> hir::GenericArg {
1075 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1076 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1080 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1081 P(self.lower_ty_direct(t, itctx))
1084 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext) -> hir::Ty {
1085 let kind = match t.node {
1086 TyKind::Infer => hir::TyKind::Infer,
1087 TyKind::Err => hir::TyKind::Err,
1088 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1089 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1090 TyKind::Rptr(ref region, ref mt) => {
1091 let span = t.span.shrink_to_lo();
1092 let lifetime = match *region {
1093 Some(ref lt) => self.lower_lifetime(lt),
1094 None => self.elided_ref_lifetime(span),
1096 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1098 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1101 this.with_anonymous_lifetime_mode(
1102 AnonymousLifetimeMode::PassThrough,
1104 hir::TyKind::BareFn(P(hir::BareFnTy {
1105 generic_params: this.lower_generic_params(
1108 ImplTraitContext::Disallowed,
1110 unsafety: this.lower_unsafety(f.unsafety),
1112 decl: this.lower_fn_decl(&f.decl, None, false, None),
1113 arg_names: this.lower_fn_args_to_names(&f.decl),
1119 TyKind::Never => hir::TyKind::Never,
1120 TyKind::Tup(ref tys) => {
1121 hir::TyKind::Tup(tys.iter().map(|ty| {
1122 self.lower_ty_direct(ty, itctx.reborrow())
1125 TyKind::Paren(ref ty) => {
1126 return self.lower_ty_direct(ty, itctx);
1128 TyKind::Path(ref qself, ref path) => {
1129 let id = self.lower_node_id(t.id);
1130 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1131 let ty = self.ty_path(id, t.span, qpath);
1132 if let hir::TyKind::TraitObject(..) = ty.node {
1133 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1137 TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1140 def: self.expect_full_def(t.id),
1141 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1145 TyKind::Array(ref ty, ref length) => {
1146 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1148 TyKind::Typeof(ref expr) => {
1149 hir::TyKind::Typeof(self.lower_anon_const(expr))
1151 TyKind::TraitObject(ref bounds, kind) => {
1152 let mut lifetime_bound = None;
1155 .filter_map(|bound| match *bound {
1156 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1157 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1159 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1160 GenericBound::Outlives(ref lifetime) => {
1161 if lifetime_bound.is_none() {
1162 lifetime_bound = Some(self.lower_lifetime(lifetime));
1168 let lifetime_bound =
1169 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1170 if kind != TraitObjectSyntax::Dyn {
1171 self.maybe_lint_bare_trait(t.span, t.id, false);
1173 hir::TyKind::TraitObject(bounds, lifetime_bound)
1175 TyKind::ImplTrait(def_node_id, ref bounds) => {
1178 ImplTraitContext::Existential(fn_def_id) => {
1179 self.lower_existential_impl_trait(
1180 span, fn_def_id, def_node_id,
1181 |this| this.lower_param_bounds(bounds, itctx),
1184 ImplTraitContext::Universal(in_band_ty_params) => {
1185 self.lower_node_id(def_node_id);
1186 // Add a definition for the in-band Param
1187 let def_index = self
1190 .opt_def_index(def_node_id)
1193 let hir_bounds = self.lower_param_bounds(
1195 ImplTraitContext::Universal(in_band_ty_params),
1197 // Set the name to `impl Bound1 + Bound2`
1198 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1199 in_band_ty_params.push(hir::GenericParam {
1201 name: ParamName::Plain(ident),
1202 pure_wrt_drop: false,
1206 kind: hir::GenericParamKind::Type {
1208 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1212 hir::TyKind::Path(hir::QPath::Resolved(
1216 def: Def::TyParam(DefId::local(def_index)),
1217 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1221 ImplTraitContext::Disallowed => {
1226 "`impl Trait` not allowed outside of function \
1227 and inherent method return types"
1233 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1236 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1245 fn lower_existential_impl_trait(
1249 exist_ty_node_id: NodeId,
1250 lower_bounds: impl FnOnce(&mut LoweringContext) -> hir::GenericBounds,
1252 // Make sure we know that some funky desugaring has been going on here.
1253 // This is a first: there is code in other places like for loop
1254 // desugaring that explicitly states that we don't want to track that.
1255 // Not tracking it makes lints in rustc and clippy very fragile as
1256 // frequently opened issues show.
1257 let exist_ty_span = self.allow_internal_unstable(
1258 CompilerDesugaringKind::ExistentialReturnType,
1262 let exist_ty_def_index = self
1265 .opt_def_index(exist_ty_node_id)
1269 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1271 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1273 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1279 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1280 let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1281 generics: hir::Generics {
1282 params: lifetime_defs,
1283 where_clause: hir::WhereClause {
1284 id: lctx.next_id().node_id,
1285 predicates: Vec::new().into(),
1290 impl_trait_fn: Some(fn_def_id),
1292 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1293 // Generate an `existential type Foo: Trait;` declaration
1294 trace!("creating existential type with id {:#?}", exist_ty_id);
1296 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1297 let exist_ty_item = hir::Item {
1298 id: exist_ty_id.node_id,
1299 hir_id: exist_ty_id.hir_id,
1300 name: keywords::Invalid.name(),
1301 attrs: Default::default(),
1302 node: exist_ty_item_kind,
1303 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1304 span: exist_ty_span,
1307 // Insert the item into the global list. This usually happens
1308 // automatically for all AST items. But this existential type item
1309 // does not actually exist in the AST.
1310 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1312 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1313 let path = P(hir::Path {
1314 span: exist_ty_span,
1315 def: Def::Existential(DefId::local(exist_ty_def_index)),
1316 segments: hir_vec![hir::PathSegment {
1318 ident: Ident::new(keywords::Invalid.name(), exist_ty_span),
1319 args: Some(P(hir::GenericArgs {
1320 parenthesized: false,
1321 bindings: HirVec::new(),
1326 hir::TyKind::Path(hir::QPath::Resolved(None, path))
1330 fn lifetimes_from_impl_trait_bounds(
1332 exist_ty_id: NodeId,
1333 parent_index: DefIndex,
1334 bounds: &hir::GenericBounds,
1335 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1336 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1337 // appear in the bounds, excluding lifetimes that are created within the bounds.
1338 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1339 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1340 context: &'r mut LoweringContext<'a>,
1342 exist_ty_id: NodeId,
1343 collect_elided_lifetimes: bool,
1344 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1345 already_defined_lifetimes: HashSet<hir::LifetimeName>,
1346 output_lifetimes: Vec<hir::GenericArg>,
1347 output_lifetime_params: Vec<hir::GenericParam>,
1350 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1351 fn nested_visit_map<'this>(
1353 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1354 hir::intravisit::NestedVisitorMap::None
1357 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1358 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1359 if parameters.parenthesized {
1360 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1361 self.collect_elided_lifetimes = false;
1362 hir::intravisit::walk_generic_args(self, span, parameters);
1363 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1365 hir::intravisit::walk_generic_args(self, span, parameters);
1369 fn visit_ty(&mut self, t: &'v hir::Ty) {
1370 // Don't collect elided lifetimes used inside of `fn()` syntax
1371 if let hir::TyKind::BareFn(_) = t.node {
1372 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1373 self.collect_elided_lifetimes = false;
1375 // Record the "stack height" of `for<'a>` lifetime bindings
1376 // to be able to later fully undo their introduction.
1377 let old_len = self.currently_bound_lifetimes.len();
1378 hir::intravisit::walk_ty(self, t);
1379 self.currently_bound_lifetimes.truncate(old_len);
1381 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1383 hir::intravisit::walk_ty(self, t)
1387 fn visit_poly_trait_ref(
1389 trait_ref: &'v hir::PolyTraitRef,
1390 modifier: hir::TraitBoundModifier,
1392 // Record the "stack height" of `for<'a>` lifetime bindings
1393 // to be able to later fully undo their introduction.
1394 let old_len = self.currently_bound_lifetimes.len();
1395 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1396 self.currently_bound_lifetimes.truncate(old_len);
1399 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1400 // Record the introduction of 'a in `for<'a> ...`
1401 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1402 // Introduce lifetimes one at a time so that we can handle
1403 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1404 let lt_name = hir::LifetimeName::Param(param.name);
1405 self.currently_bound_lifetimes.push(lt_name);
1408 hir::intravisit::walk_generic_param(self, param);
1411 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1412 let name = match lifetime.name {
1413 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1414 if self.collect_elided_lifetimes {
1415 // Use `'_` for both implicit and underscore lifetimes in
1416 // `abstract type Foo<'_>: SomeTrait<'_>;`
1417 hir::LifetimeName::Underscore
1422 hir::LifetimeName::Param(_) => lifetime.name,
1423 hir::LifetimeName::Static => return,
1426 if !self.currently_bound_lifetimes.contains(&name)
1427 && !self.already_defined_lifetimes.contains(&name) {
1428 self.already_defined_lifetimes.insert(name);
1430 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1431 id: self.context.next_id().node_id,
1432 span: lifetime.span,
1436 // We need to manually create the ids here, because the
1437 // definitions will go into the explicit `existential type`
1438 // declaration and thus need to have their owner set to that item
1439 let def_node_id = self.context.sess.next_node_id();
1440 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1441 self.context.resolver.definitions().create_def_with_parent(
1444 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1445 DefIndexAddressSpace::High,
1450 let name = match name {
1451 hir::LifetimeName::Underscore => {
1452 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident())
1454 hir::LifetimeName::Param(param_name) => param_name,
1455 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1458 self.output_lifetime_params.push(hir::GenericParam {
1461 span: lifetime.span,
1462 pure_wrt_drop: false,
1465 kind: hir::GenericParamKind::Lifetime {
1473 let mut lifetime_collector = ImplTraitLifetimeCollector {
1475 parent: parent_index,
1477 collect_elided_lifetimes: true,
1478 currently_bound_lifetimes: Vec::new(),
1479 already_defined_lifetimes: HashSet::new(),
1480 output_lifetimes: Vec::new(),
1481 output_lifetime_params: Vec::new(),
1484 for bound in bounds {
1485 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1489 lifetime_collector.output_lifetimes.into(),
1490 lifetime_collector.output_lifetime_params.into(),
1494 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1499 .map(|x| self.lower_foreign_item(x))
1504 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1511 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1513 node: hir::VariantKind {
1514 name: v.node.ident.name,
1515 attrs: self.lower_attrs(&v.node.attrs),
1516 data: self.lower_variant_data(&v.node.data),
1517 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1526 qself: &Option<QSelf>,
1528 param_mode: ParamMode,
1529 mut itctx: ImplTraitContext,
1531 let qself_position = qself.as_ref().map(|q| q.position);
1532 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1534 let resolution = self.resolver
1536 .unwrap_or(PathResolution::new(Def::Err));
1538 let proj_start = p.segments.len() - resolution.unresolved_segments();
1539 let path = P(hir::Path {
1540 def: resolution.base_def(),
1541 segments: p.segments[..proj_start]
1544 .map(|(i, segment)| {
1545 let param_mode = match (qself_position, param_mode) {
1546 (Some(j), ParamMode::Optional) if i < j => {
1547 // This segment is part of the trait path in a
1548 // qualified path - one of `a`, `b` or `Trait`
1549 // in `<X as a::b::Trait>::T::U::method`.
1555 // Figure out if this is a type/trait segment,
1556 // which may need lifetime elision performed.
1557 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1558 krate: def_id.krate,
1559 index: this.def_key(def_id).parent.expect("missing parent"),
1561 let type_def_id = match resolution.base_def() {
1562 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1563 Some(parent_def_id(self, def_id))
1565 Def::Variant(def_id) if i + 1 == proj_start => {
1566 Some(parent_def_id(self, def_id))
1569 | Def::Union(def_id)
1571 | Def::TyAlias(def_id)
1572 | Def::Trait(def_id) if i + 1 == proj_start =>
1578 let parenthesized_generic_args = match resolution.base_def() {
1579 // `a::b::Trait(Args)`
1580 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1581 // `a::b::Trait(Args)::TraitItem`
1582 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1583 if i + 2 == proj_start =>
1585 ParenthesizedGenericArgs::Ok
1587 // Avoid duplicated errors
1588 Def::Err => ParenthesizedGenericArgs::Ok,
1594 | Def::Variant(..) if i + 1 == proj_start =>
1596 ParenthesizedGenericArgs::Err
1598 // A warning for now, for compatibility reasons
1599 _ => ParenthesizedGenericArgs::Warn,
1602 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1603 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1606 assert!(!def_id.is_local());
1608 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1609 let n = item_generics.own_counts().lifetimes;
1610 self.type_def_lifetime_params.insert(def_id, n);
1613 self.lower_path_segment(
1618 parenthesized_generic_args,
1626 // Simple case, either no projections, or only fully-qualified.
1627 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1628 if resolution.unresolved_segments() == 0 {
1629 return hir::QPath::Resolved(qself, path);
1632 // Create the innermost type that we're projecting from.
1633 let mut ty = if path.segments.is_empty() {
1634 // If the base path is empty that means there exists a
1635 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1636 qself.expect("missing QSelf for <T>::...")
1638 // Otherwise, the base path is an implicit `Self` type path,
1639 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1640 // `<I as Iterator>::Item::default`.
1641 let new_id = self.next_id();
1642 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1645 // Anything after the base path are associated "extensions",
1646 // out of which all but the last one are associated types,
1647 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1648 // * base path is `std::vec::Vec<T>`
1649 // * "extensions" are `IntoIter`, `Item` and `clone`
1650 // * type nodes are:
1651 // 1. `std::vec::Vec<T>` (created above)
1652 // 2. `<std::vec::Vec<T>>::IntoIter`
1653 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1654 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1655 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1656 let segment = P(self.lower_path_segment(
1661 ParenthesizedGenericArgs::Warn,
1664 let qpath = hir::QPath::TypeRelative(ty, segment);
1666 // It's finished, return the extension of the right node type.
1667 if i == p.segments.len() - 1 {
1671 // Wrap the associated extension in another type node.
1672 let new_id = self.next_id();
1673 ty = P(self.ty_path(new_id, p.span, qpath));
1676 // Should've returned in the for loop above.
1679 "lower_qpath: no final extension segment in {}..{}",
1685 fn lower_path_extra(
1689 ident: Option<Ident>,
1690 param_mode: ParamMode,
1694 segments: p.segments
1697 self.lower_path_segment(
1702 ParenthesizedGenericArgs::Err,
1703 ImplTraitContext::Disallowed,
1706 .chain(ident.map(|ident| hir::PathSegment::from_ident(ident)))
1712 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1713 let def = self.expect_full_def(id);
1714 self.lower_path_extra(def, p, None, param_mode)
1717 fn lower_path_segment(
1720 segment: &PathSegment,
1721 param_mode: ParamMode,
1722 expected_lifetimes: usize,
1723 parenthesized_generic_args: ParenthesizedGenericArgs,
1724 itctx: ImplTraitContext,
1725 ) -> hir::PathSegment {
1726 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1727 let msg = "parenthesized parameters may only be used with a trait";
1728 match **generic_args {
1729 GenericArgs::AngleBracketed(ref data) => {
1730 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1732 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1733 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1734 ParenthesizedGenericArgs::Warn => {
1735 self.sess.buffer_lint(
1736 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1741 (hir::GenericArgs::none(), true)
1743 ParenthesizedGenericArgs::Err => {
1744 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1745 .span_label(data.span, "only traits may use parentheses")
1747 (hir::GenericArgs::none(), true)
1752 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1755 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1756 GenericArg::Lifetime(_) => true,
1759 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1760 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1761 if !generic_args.parenthesized && !has_lifetimes {
1763 self.elided_path_lifetimes(path_span, expected_lifetimes)
1765 .map(|lt| GenericArg::Lifetime(lt))
1766 .chain(generic_args.args.into_iter())
1768 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1769 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1770 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1771 let no_bindings = generic_args.bindings.is_empty();
1772 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1773 // If there are no (non-implicit) generic args or associated-type
1774 // bindings, our suggestion includes the angle brackets
1775 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1777 // Otherwise—sorry, this is kind of gross—we need to infer the
1778 // place to splice in the `'_, ` from the generics that do exist
1779 let first_generic_span = first_generic_span
1780 .expect("already checked that type args or bindings exist");
1781 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1783 self.sess.buffer_lint_with_diagnostic(
1784 ELIDED_LIFETIMES_IN_PATHS,
1787 "hidden lifetime parameters in types are deprecated",
1788 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1789 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1795 hir::PathSegment::new(
1802 fn lower_angle_bracketed_parameter_data(
1804 data: &AngleBracketedArgs,
1805 param_mode: ParamMode,
1806 mut itctx: ImplTraitContext,
1807 ) -> (hir::GenericArgs, bool) {
1808 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1809 let has_types = args.iter().any(|arg| match arg {
1810 ast::GenericArg::Type(_) => true,
1814 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1815 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1816 parenthesized: false,
1818 !has_types && param_mode == ParamMode::Optional)
1821 fn lower_parenthesized_parameter_data(
1823 data: &ParenthesisedArgs,
1824 ) -> (hir::GenericArgs, bool) {
1825 // Switch to `PassThrough` mode for anonymous lifetimes: this
1826 // means that we permit things like `&Ref<T>`, where `Ref` has
1827 // a hidden lifetime parameter. This is needed for backwards
1828 // compatibility, even in contexts like an impl header where
1829 // we generally don't permit such things (see #51008).
1830 self.with_anonymous_lifetime_mode(
1831 AnonymousLifetimeMode::PassThrough,
1833 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1834 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1835 let inputs = inputs.iter().map(|ty| this.lower_ty_direct(ty, DISALLOWED)).collect();
1836 let mk_tup = |this: &mut Self, tys, span| {
1837 let LoweredNodeId { node_id, hir_id } = this.next_id();
1838 hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1843 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1846 id: this.next_id().node_id,
1847 ident: Ident::from_str(FN_OUTPUT_NAME),
1850 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1851 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1852 span: output.as_ref().map_or(span, |ty| ty.span),
1855 parenthesized: true,
1863 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1864 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1870 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1871 pat: self.lower_pat(&l.pat),
1872 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1874 attrs: l.attrs.clone(),
1875 source: hir::LocalSource::Normal,
1879 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1881 Mutability::Mutable => hir::MutMutable,
1882 Mutability::Immutable => hir::MutImmutable,
1886 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1887 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1891 pat: self.lower_pat(&arg.pat),
1895 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1898 .map(|arg| match arg.pat.node {
1899 PatKind::Ident(_, ident, _) => ident,
1900 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
1905 // Lowers a function declaration.
1907 // decl: the unlowered (ast) function declaration.
1908 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1909 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1910 // make_ret_async is also `Some`.
1911 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1912 // This guards against trait declarations and implementations where impl Trait is
1914 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1915 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
1916 // return type impl Trait item.
1920 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
1921 impl_trait_return_allow: bool,
1922 make_ret_async: Option<NodeId>,
1923 ) -> P<hir::FnDecl> {
1924 let inputs = decl.inputs
1927 if let Some((_, ref mut ibty)) = in_band_ty_params {
1928 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
1930 self.lower_ty_direct(&arg.ty, ImplTraitContext::Disallowed)
1933 .collect::<HirVec<_>>();
1935 let output = if let Some(ret_id) = make_ret_async {
1936 self.lower_async_fn_ret_ty(
1939 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
1944 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
1945 Some((def_id, _)) if impl_trait_return_allow => {
1946 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1948 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1950 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1957 variadic: decl.variadic,
1958 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1959 TyKind::ImplicitSelf => true,
1960 TyKind::Rptr(_, ref mt) => mt.ty.node.is_implicit_self(),
1966 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
1968 // fn_span: the span of the async function declaration. Used for error reporting.
1969 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
1970 // output: unlowered output type (`T` in `-> T`)
1971 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
1972 fn lower_async_fn_ret_ty(
1975 output: &FunctionRetTy,
1977 return_impl_trait_id: NodeId,
1978 ) -> hir::FunctionRetTy {
1979 // Get lifetimes used in the input arguments to the function. Our output type must also
1980 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
1981 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
1982 // is a subset of the other. We really want some new lifetime that is a subset of all input
1983 // lifetimes, but that doesn't exist at the moment.
1985 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
1986 context: &'r mut LoweringContext<'a>,
1987 // Lifetimes bound by HRTB
1988 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1989 // Whether to count elided lifetimes.
1990 // Disabled inside of `Fn` or `fn` syntax.
1991 collect_elided_lifetimes: bool,
1992 // The lifetime found.
1993 // Multiple different or elided lifetimes cannot appear in async fn for now.
1994 output_lifetime: Option<(hir::LifetimeName, Span)>,
1997 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
1998 fn nested_visit_map<'this>(
2000 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
2001 hir::intravisit::NestedVisitorMap::None
2004 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
2005 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2006 if parameters.parenthesized {
2007 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2008 self.collect_elided_lifetimes = false;
2009 hir::intravisit::walk_generic_args(self, span, parameters);
2010 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2012 hir::intravisit::walk_generic_args(self, span, parameters);
2016 fn visit_ty(&mut self, t: &'v hir::Ty) {
2017 // Don't collect elided lifetimes used inside of `fn()` syntax
2018 if let &hir::TyKind::BareFn(_) = &t.node {
2019 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2020 self.collect_elided_lifetimes = false;
2022 // Record the "stack height" of `for<'a>` lifetime bindings
2023 // to be able to later fully undo their introduction.
2024 let old_len = self.currently_bound_lifetimes.len();
2025 hir::intravisit::walk_ty(self, t);
2026 self.currently_bound_lifetimes.truncate(old_len);
2028 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2030 hir::intravisit::walk_ty(self, t);
2034 fn visit_poly_trait_ref(
2036 trait_ref: &'v hir::PolyTraitRef,
2037 modifier: hir::TraitBoundModifier,
2039 // Record the "stack height" of `for<'a>` lifetime bindings
2040 // to be able to later fully undo their introduction.
2041 let old_len = self.currently_bound_lifetimes.len();
2042 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2043 self.currently_bound_lifetimes.truncate(old_len);
2046 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2047 // Record the introduction of 'a in `for<'a> ...`
2048 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2049 // Introduce lifetimes one at a time so that we can handle
2050 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2051 let lt_name = hir::LifetimeName::Param(param.name);
2052 self.currently_bound_lifetimes.push(lt_name);
2055 hir::intravisit::walk_generic_param(self, param);
2058 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2059 let name = match lifetime.name {
2060 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2061 if self.collect_elided_lifetimes {
2062 // Use `'_` for both implicit and underscore lifetimes in
2063 // `abstract type Foo<'_>: SomeTrait<'_>;`
2064 hir::LifetimeName::Underscore
2069 hir::LifetimeName::Param(_) => lifetime.name,
2070 hir::LifetimeName::Static => return,
2073 if !self.currently_bound_lifetimes.contains(&name) {
2074 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2075 // We don't currently have a reliable way to desugar `async fn` with
2076 // multiple potentially unrelated input lifetimes into
2077 // `-> impl Trait + 'lt`, so we report an error in this case.
2078 if current_lt_name != name {
2081 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2083 "multiple different lifetimes used in arguments of `async fn`",
2085 .span_label(current_lt_span, "first lifetime here")
2086 .span_label(lifetime.span, "different lifetime here")
2087 .help("`async fn` can only accept borrowed values \
2088 with identical lifetimes")
2090 } else if current_lt_name.is_elided() && name.is_elided() {
2093 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2095 "multiple elided lifetimes used in arguments of `async fn`",
2097 .span_label(current_lt_span, "first lifetime here")
2098 .span_label(lifetime.span, "different lifetime here")
2099 .help("consider giving these arguments named lifetimes")
2103 self.output_lifetime = Some((name, lifetime.span));
2109 let bound_lifetime = {
2110 let mut lifetime_collector = AsyncFnLifetimeCollector {
2112 currently_bound_lifetimes: Vec::new(),
2113 collect_elided_lifetimes: true,
2114 output_lifetime: None,
2118 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2120 lifetime_collector.output_lifetime
2123 let span = match output {
2124 FunctionRetTy::Ty(ty) => ty.span,
2125 FunctionRetTy::Default(span) => *span,
2128 let impl_trait_ty = self.lower_existential_impl_trait(
2129 span, fn_def_id, return_impl_trait_id, |this| {
2130 let output_ty = match output {
2131 FunctionRetTy::Ty(ty) =>
2132 this.lower_ty(ty, ImplTraitContext::Existential(fn_def_id)),
2133 FunctionRetTy::Default(span) => {
2134 let LoweredNodeId { node_id, hir_id } = this.next_id();
2138 node: hir::TyKind::Tup(hir_vec![]),
2145 let future_params = P(hir::GenericArgs {
2147 bindings: hir_vec![hir::TypeBinding {
2148 ident: Ident::from_str(FN_OUTPUT_NAME),
2150 id: this.next_id().node_id,
2153 parenthesized: false,
2157 this.std_path(span, &["future", "Future"], Some(future_params), false);
2159 let LoweredNodeId { node_id, hir_id } = this.next_id();
2160 let mut bounds = vec![
2161 hir::GenericBound::Trait(
2163 trait_ref: hir::TraitRef {
2168 bound_generic_params: hir_vec![],
2171 hir::TraitBoundModifier::None
2175 if let Some((name, span)) = bound_lifetime {
2176 bounds.push(hir::GenericBound::Outlives(
2177 hir::Lifetime { id: this.next_id().node_id, name, span }));
2180 hir::HirVec::from(bounds)
2183 let LoweredNodeId { node_id, hir_id } = self.next_id();
2184 let impl_trait_ty = P(hir::Ty {
2186 node: impl_trait_ty,
2191 hir::FunctionRetTy::Return(impl_trait_ty)
2194 fn lower_param_bound(
2197 itctx: ImplTraitContext,
2198 ) -> hir::GenericBound {
2200 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2201 self.lower_poly_trait_ref(ty, itctx),
2202 self.lower_trait_bound_modifier(modifier),
2204 GenericBound::Outlives(ref lifetime) => {
2205 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2210 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2211 let span = l.ident.span;
2213 ident if ident.name == keywords::StaticLifetime.name() =>
2214 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2215 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2216 match self.anonymous_lifetime_mode {
2217 AnonymousLifetimeMode::CreateParameter => {
2218 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2219 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2222 AnonymousLifetimeMode::PassThrough => {
2223 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2227 self.maybe_collect_in_band_lifetime(ident);
2228 let param_name = ParamName::Plain(ident);
2229 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2234 fn new_named_lifetime(
2238 name: hir::LifetimeName,
2239 ) -> hir::Lifetime {
2241 id: self.lower_node_id(id).node_id,
2247 fn lower_generic_params(
2249 params: &[GenericParam],
2250 add_bounds: &NodeMap<Vec<GenericBound>>,
2251 mut itctx: ImplTraitContext,
2252 ) -> hir::HirVec<hir::GenericParam> {
2253 params.iter().map(|param| {
2254 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2258 fn lower_generic_param(&mut self,
2259 param: &GenericParam,
2260 add_bounds: &NodeMap<Vec<GenericBound>>,
2261 mut itctx: ImplTraitContext)
2262 -> hir::GenericParam {
2263 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx.reborrow());
2265 GenericParamKind::Lifetime => {
2266 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2267 self.is_collecting_in_band_lifetimes = false;
2269 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
2270 let param_name = match lt.name {
2271 hir::LifetimeName::Param(param_name) => param_name,
2272 _ => hir::ParamName::Plain(lt.name.ident()),
2274 let param = hir::GenericParam {
2278 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2279 attrs: self.lower_attrs(¶m.attrs),
2281 kind: hir::GenericParamKind::Lifetime { in_band: false }
2284 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2288 GenericParamKind::Type { ref default, .. } => {
2289 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2290 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2291 // Instead, use gensym("Self") to create a distinct name that looks the same.
2292 let ident = if param.ident.name == keywords::SelfType.name() {
2293 param.ident.gensym()
2298 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2299 if !add_bounds.is_empty() {
2300 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2301 bounds = bounds.into_iter()
2307 id: self.lower_node_id(param.id).node_id,
2308 name: hir::ParamName::Plain(ident),
2309 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2310 attrs: self.lower_attrs(¶m.attrs),
2313 kind: hir::GenericParamKind::Type {
2314 default: default.as_ref().map(|x| {
2315 self.lower_ty(x, ImplTraitContext::Disallowed)
2317 synthetic: param.attrs.iter()
2318 .filter(|attr| attr.check_name("rustc_synthetic"))
2319 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2329 generics: &Generics,
2330 itctx: ImplTraitContext)
2333 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2334 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2335 // paths where report_error is called are also the only paths that advance to after
2336 // the match statement, so the error reporting could probably just be moved there.
2337 let mut add_bounds: NodeMap<Vec<_>> = NodeMap();
2338 for pred in &generics.where_clause.predicates {
2339 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2340 'next_bound: for bound in &bound_pred.bounds {
2341 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2342 let report_error = |this: &mut Self| {
2343 this.diagnostic().span_err(
2344 bound_pred.bounded_ty.span,
2345 "`?Trait` bounds are only permitted at the \
2346 point where a type parameter is declared",
2349 // Check if the where clause type is a plain type parameter.
2350 match bound_pred.bounded_ty.node {
2351 TyKind::Path(None, ref path)
2352 if path.segments.len() == 1
2353 && bound_pred.bound_generic_params.is_empty() =>
2355 if let Some(Def::TyParam(def_id)) = self.resolver
2356 .get_resolution(bound_pred.bounded_ty.id)
2357 .map(|d| d.base_def())
2359 if let Some(node_id) =
2360 self.resolver.definitions().as_local_node_id(def_id)
2362 for param in &generics.params {
2364 GenericParamKind::Type { .. } => {
2365 if node_id == param.id {
2366 add_bounds.entry(param.id)
2368 .push(bound.clone());
2369 continue 'next_bound;
2379 _ => report_error(self),
2387 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2388 where_clause: self.lower_where_clause(&generics.where_clause),
2389 span: generics.span,
2393 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2395 id: self.lower_node_id(wc.id).node_id,
2396 predicates: wc.predicates
2398 .map(|predicate| self.lower_where_predicate(predicate))
2403 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2405 WherePredicate::BoundPredicate(WhereBoundPredicate {
2406 ref bound_generic_params,
2411 self.with_in_scope_lifetime_defs(
2412 &bound_generic_params,
2414 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2415 bound_generic_params: this.lower_generic_params(
2416 bound_generic_params,
2418 ImplTraitContext::Disallowed,
2420 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2423 .filter_map(|bound| match *bound {
2424 // Ignore `?Trait` bounds.
2425 // Tthey were copied into type parameters already.
2426 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2427 _ => Some(this.lower_param_bound(
2429 ImplTraitContext::Disallowed,
2438 WherePredicate::RegionPredicate(WhereRegionPredicate {
2442 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2444 lifetime: self.lower_lifetime(lifetime),
2445 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2447 WherePredicate::EqPredicate(WhereEqPredicate {
2452 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2453 id: self.lower_node_id(id).node_id,
2454 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2455 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2461 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2463 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2467 .map(|f| self.lower_struct_field(f))
2469 self.lower_node_id(id).node_id,
2471 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2475 .map(|f| self.lower_struct_field(f))
2477 self.lower_node_id(id).node_id,
2479 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2483 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2484 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2485 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2486 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2488 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.ref_id);
2496 fn lower_poly_trait_ref(
2499 mut itctx: ImplTraitContext,
2500 ) -> hir::PolyTraitRef {
2501 let bound_generic_params =
2502 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx.reborrow());
2503 let trait_ref = self.with_parent_impl_lifetime_defs(
2504 &bound_generic_params,
2505 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2509 bound_generic_params,
2515 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2518 id: self.lower_node_id(f.id).node_id,
2519 ident: match f.ident {
2520 Some(ident) => ident,
2521 // FIXME(jseyfried) positional field hygiene
2522 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2524 vis: self.lower_visibility(&f.vis, None),
2525 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2526 attrs: self.lower_attrs(&f.attrs),
2530 fn lower_field(&mut self, f: &Field) -> hir::Field {
2532 id: self.next_id().node_id,
2534 expr: P(self.lower_expr(&f.expr)),
2536 is_shorthand: f.is_shorthand,
2540 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2542 ty: self.lower_ty(&mt.ty, itctx),
2543 mutbl: self.lower_mutability(mt.mutbl),
2547 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext)
2548 -> hir::GenericBounds {
2549 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2552 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2553 let mut expr = None;
2555 let mut stmts = vec![];
2557 for (index, stmt) in b.stmts.iter().enumerate() {
2558 if index == b.stmts.len() - 1 {
2559 if let StmtKind::Expr(ref e) = stmt.node {
2560 expr = Some(P(self.lower_expr(e)));
2562 stmts.extend(self.lower_stmt(stmt));
2565 stmts.extend(self.lower_stmt(stmt));
2569 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2574 stmts: stmts.into(),
2576 rules: self.lower_block_check_mode(&b.rules),
2579 recovered: b.recovered,
2583 fn lower_async_body(
2589 self.lower_body(Some(decl), |this| {
2590 if let IsAsync::Async { closure_id, .. } = asyncness {
2591 let async_expr = this.make_async_expr(
2592 CaptureBy::Value, closure_id, None,
2594 let body = this.lower_block(body, false);
2595 this.expr_block(body, ThinVec::new())
2597 this.expr(body.span, async_expr, ThinVec::new())
2599 let body = this.lower_block(body, false);
2600 this.expr_block(body, ThinVec::new())
2609 attrs: &hir::HirVec<Attribute>,
2610 vis: &mut hir::Visibility,
2612 ) -> hir::ItemKind {
2614 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2615 ItemKind::Use(ref use_tree) => {
2616 // Start with an empty prefix
2619 span: use_tree.span,
2622 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2624 ItemKind::Static(ref t, m, ref e) => {
2625 let value = self.lower_body(None, |this| this.lower_expr(e));
2626 hir::ItemKind::Static(
2627 self.lower_ty(t, ImplTraitContext::Disallowed),
2628 self.lower_mutability(m),
2632 ItemKind::Const(ref t, ref e) => {
2633 let value = self.lower_body(None, |this| this.lower_expr(e));
2634 hir::ItemKind::Const(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2636 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2637 let fn_def_id = self.resolver.definitions().local_def_id(id);
2639 self.with_new_scopes(|this| {
2640 // Note: we don't need to change the return type from `T` to
2641 // `impl Future<Output = T>` here because lower_body
2642 // only cares about the input argument patterns in the function
2643 // declaration (decl), not the return types.
2644 let body_id = this.lower_async_body(decl, header.asyncness, body);
2646 let (generics, fn_decl) = this.add_in_band_defs(
2649 AnonymousLifetimeMode::PassThrough,
2650 |this, idty| this.lower_fn_decl(
2651 decl, Some((fn_def_id, idty)), true, header.asyncness.opt_return_id()),
2656 this.lower_fn_header(header),
2662 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2663 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2664 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2665 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2666 self.lower_ty(t, ImplTraitContext::Disallowed),
2667 self.lower_generics(generics, ImplTraitContext::Disallowed),
2669 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2670 generics: self.lower_generics(generics, ImplTraitContext::Disallowed),
2671 bounds: self.lower_param_bounds(b, ImplTraitContext::Disallowed),
2672 impl_trait_fn: None,
2674 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2676 variants: enum_definition
2679 .map(|x| self.lower_variant(x))
2682 self.lower_generics(generics, ImplTraitContext::Disallowed),
2684 ItemKind::Struct(ref struct_def, ref generics) => {
2685 let struct_def = self.lower_variant_data(struct_def);
2686 hir::ItemKind::Struct(
2688 self.lower_generics(generics, ImplTraitContext::Disallowed),
2691 ItemKind::Union(ref vdata, ref generics) => {
2692 let vdata = self.lower_variant_data(vdata);
2693 hir::ItemKind::Union(
2695 self.lower_generics(generics, ImplTraitContext::Disallowed),
2707 let def_id = self.resolver.definitions().local_def_id(id);
2709 // Lower the "impl header" first. This ordering is important
2710 // for in-band lifetimes! Consider `'a` here:
2712 // impl Foo<'a> for u32 {
2713 // fn method(&'a self) { .. }
2716 // Because we start by lowering the `Foo<'a> for u32`
2717 // part, we will add `'a` to the list of generics on
2718 // the impl. When we then encounter it later in the
2719 // method, it will not be considered an in-band
2720 // lifetime to be added, but rather a reference to a
2722 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2725 AnonymousLifetimeMode::CreateParameter,
2727 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2728 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2731 if let Some(ref trait_ref) = trait_ref {
2732 if let Def::Trait(def_id) = trait_ref.path.def {
2733 this.trait_impls.entry(def_id).or_default().push(id);
2737 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2739 (trait_ref, lowered_ty)
2743 let new_impl_items = self.with_in_scope_lifetime_defs(
2744 &ast_generics.params,
2748 .map(|item| this.lower_impl_item_ref(item))
2753 hir::ItemKind::Impl(
2754 self.lower_unsafety(unsafety),
2755 self.lower_impl_polarity(polarity),
2756 self.lower_defaultness(defaultness, true /* [1] */),
2763 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2764 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2767 .map(|item| self.lower_trait_item_ref(item))
2769 hir::ItemKind::Trait(
2770 self.lower_is_auto(is_auto),
2771 self.lower_unsafety(unsafety),
2772 self.lower_generics(generics, ImplTraitContext::Disallowed),
2777 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
2778 self.lower_generics(generics, ImplTraitContext::Disallowed),
2779 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2781 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2784 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2785 // not cause an assertion failure inside the `lower_defaultness` function
2793 vis: &mut hir::Visibility,
2795 attrs: &hir::HirVec<Attribute>,
2796 ) -> hir::ItemKind {
2797 let path = &tree.prefix;
2800 UseTreeKind::Simple(rename, id1, id2) => {
2801 *name = tree.ident().name;
2803 // First apply the prefix to the path
2804 let mut path = Path {
2808 .chain(path.segments.iter())
2814 // Correctly resolve `self` imports
2815 if path.segments.len() > 1
2816 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2818 let _ = path.segments.pop();
2819 if rename.is_none() {
2820 *name = path.segments.last().unwrap().ident.name;
2824 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2825 let mut defs = self.expect_full_def_from_use(id);
2826 // we want to return *something* from this function, so hang onto the first item
2828 let ret_def = defs.next().unwrap_or(Def::Err);
2830 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2831 let vis = vis.clone();
2832 let name = name.clone();
2833 let span = path.span;
2834 self.resolver.definitions().create_def_with_parent(
2838 DefIndexAddressSpace::High,
2841 self.allocate_hir_id_counter(new_node_id, &path);
2843 self.with_hir_id_owner(new_node_id, |this| {
2844 let new_id = this.lower_node_id(new_node_id);
2845 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2846 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
2847 let vis_kind = match vis.node {
2848 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2849 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2850 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2851 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
2852 let id = this.next_id();
2853 hir::VisibilityKind::Restricted {
2855 // We are allocating a new NodeId here
2861 let vis = respan(vis.span, vis_kind);
2867 hir_id: new_id.hir_id,
2869 attrs: attrs.clone(),
2878 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2879 hir::ItemKind::Use(path, hir::UseKind::Single)
2881 UseTreeKind::Glob => {
2882 let path = P(self.lower_path(
2888 .chain(path.segments.iter())
2893 ParamMode::Explicit,
2895 hir::ItemKind::Use(path, hir::UseKind::Glob)
2897 UseTreeKind::Nested(ref trees) => {
2902 .chain(path.segments.iter())
2905 span: prefix.span.to(path.span),
2908 // Add all the nested PathListItems in the HIR
2909 for &(ref use_tree, id) in trees {
2910 self.allocate_hir_id_counter(id, &use_tree);
2914 } = self.lower_node_id(id);
2916 let mut vis = vis.clone();
2917 let mut name = name.clone();
2919 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2921 self.with_hir_id_owner(new_id, |this| {
2922 let vis_kind = match vis.node {
2923 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2924 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2925 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2926 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
2927 let id = this.next_id();
2928 hir::VisibilityKind::Restricted {
2930 // We are allocating a new NodeId here
2936 let vis = respan(vis.span, vis_kind);
2944 attrs: attrs.clone(),
2947 span: use_tree.span,
2953 // Privatize the degenerate import base, used only to check
2954 // the stability of `use a::{};`, to avoid it showing up as
2955 // a re-export by accident when `pub`, e.g. in documentation.
2956 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2957 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
2958 hir::ItemKind::Use(path, hir::UseKind::ListStem)
2963 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2964 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2965 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2967 let (generics, node) = match i.node {
2968 TraitItemKind::Const(ref ty, ref default) => (
2969 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2970 hir::TraitItemKind::Const(
2971 self.lower_ty(ty, ImplTraitContext::Disallowed),
2974 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2977 TraitItemKind::Method(ref sig, None) => {
2978 let names = self.lower_fn_args_to_names(&sig.decl);
2979 let (generics, sig) = self.lower_method_sig(
2986 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
2988 TraitItemKind::Method(ref sig, Some(ref body)) => {
2989 let body_id = self.lower_body(Some(&sig.decl), |this| {
2990 let body = this.lower_block(body, false);
2991 this.expr_block(body, ThinVec::new())
2994 let (generics, sig) = self.lower_method_sig(
3002 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3004 TraitItemKind::Type(ref bounds, ref default) => (
3005 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3006 hir::TraitItemKind::Type(
3007 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3010 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
3013 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3020 attrs: self.lower_attrs(&i.attrs),
3027 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3028 let (kind, has_default) = match i.node {
3029 TraitItemKind::Const(_, ref default) => {
3030 (hir::AssociatedItemKind::Const, default.is_some())
3032 TraitItemKind::Type(_, ref default) => {
3033 (hir::AssociatedItemKind::Type, default.is_some())
3035 TraitItemKind::Method(ref sig, ref default) => (
3036 hir::AssociatedItemKind::Method {
3037 has_self: sig.decl.has_self(),
3041 TraitItemKind::Macro(..) => unimplemented!(),
3044 id: hir::TraitItemId { node_id: i.id },
3047 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3052 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3053 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3054 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3056 let (generics, node) = match i.node {
3057 ImplItemKind::Const(ref ty, ref expr) => {
3058 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3060 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3061 hir::ImplItemKind::Const(
3062 self.lower_ty(ty, ImplTraitContext::Disallowed),
3067 ImplItemKind::Method(ref sig, ref body) => {
3068 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3069 let impl_trait_return_allow = !self.is_in_trait_impl;
3070 let (generics, sig) = self.lower_method_sig(
3074 impl_trait_return_allow,
3075 sig.header.asyncness.opt_return_id(),
3077 (generics, hir::ImplItemKind::Method(sig, body_id))
3079 ImplItemKind::Type(ref ty) => (
3080 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3081 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
3083 ImplItemKind::Existential(ref bounds) => (
3084 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3085 hir::ImplItemKind::Existential(
3086 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3089 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3096 attrs: self.lower_attrs(&i.attrs),
3098 vis: self.lower_visibility(&i.vis, None),
3099 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3104 // [1] since `default impl` is not yet implemented, this is always true in impls
3107 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3109 id: hir::ImplItemId { node_id: i.id },
3112 vis: self.lower_visibility(&i.vis, Some(i.id)),
3113 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3114 kind: match i.node {
3115 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3116 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3117 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3118 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3119 has_self: sig.decl.has_self(),
3121 ImplItemKind::Macro(..) => unimplemented!(),
3125 // [1] since `default impl` is not yet implemented, this is always true in impls
3128 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3131 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3135 /// Lowers `impl Trait` items and appends them to the list
3136 fn lower_impl_trait_ids(
3140 ids: &mut OneVector<hir::ItemId>,
3142 if let Some(id) = header.asyncness.opt_return_id() {
3143 ids.push(hir::ItemId { id });
3145 struct IdVisitor<'a> { ids: &'a mut OneVector<hir::ItemId> }
3146 impl<'a, 'b> Visitor<'a> for IdVisitor<'b> {
3147 fn visit_ty(&mut self, ty: &'a Ty) {
3153 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
3156 visit::walk_ty(self, ty);
3158 fn visit_path_segment(
3161 path_segment: &'v PathSegment,
3163 if let Some(ref p) = path_segment.args {
3164 if let GenericArgs::Parenthesized(_) = **p {
3168 visit::walk_path_segment(self, path_span, path_segment)
3171 let mut visitor = IdVisitor { ids };
3173 FunctionRetTy::Default(_) => {},
3174 FunctionRetTy::Ty(ref ty) => visitor.visit_ty(ty),
3178 fn lower_item_id(&mut self, i: &Item) -> OneVector<hir::ItemId> {
3180 ItemKind::Use(ref use_tree) => {
3181 let mut vec = smallvec![hir::ItemId { id: i.id }];
3182 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3185 ItemKind::MacroDef(..) => OneVector::new(),
3186 ItemKind::Fn(ref decl, ref header, ..) => {
3187 let mut ids = smallvec![hir::ItemId { id: i.id }];
3188 self.lower_impl_trait_ids(decl, header, &mut ids);
3191 ItemKind::Impl(.., None, _, ref items) => {
3192 let mut ids = smallvec![hir::ItemId { id: i.id }];
3194 if let ImplItemKind::Method(ref sig, _) = item.node {
3195 self.lower_impl_trait_ids(&sig.decl, &sig.header, &mut ids);
3200 _ => smallvec![hir::ItemId { id: i.id }],
3204 fn lower_item_id_use_tree(&mut self,
3207 vec: &mut OneVector<hir::ItemId>)
3210 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3211 vec.push(hir::ItemId { id });
3212 self.lower_item_id_use_tree(nested, id, vec);
3214 UseTreeKind::Glob => {}
3215 UseTreeKind::Simple(_, id1, id2) => {
3216 for (_, &id) in self.expect_full_def_from_use(base_id)
3218 .zip([id1, id2].iter())
3220 vec.push(hir::ItemId { id });
3226 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3227 let mut name = i.ident.name;
3228 let mut vis = self.lower_visibility(&i.vis, None);
3229 let attrs = self.lower_attrs(&i.attrs);
3230 if let ItemKind::MacroDef(ref def) = i.node {
3231 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3232 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3233 let body = self.lower_token_stream(def.stream());
3234 self.exported_macros.push(hir::MacroDef {
3247 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3249 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3262 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3263 let node_id = self.lower_node_id(i.id).node_id;
3264 let def_id = self.resolver.definitions().local_def_id(node_id);
3268 attrs: self.lower_attrs(&i.attrs),
3269 node: match i.node {
3270 ForeignItemKind::Fn(ref fdec, ref generics) => {
3271 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3274 AnonymousLifetimeMode::PassThrough,
3277 // Disallow impl Trait in foreign items
3278 this.lower_fn_decl(fdec, None, false, None),
3279 this.lower_fn_args_to_names(fdec),
3284 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3286 ForeignItemKind::Static(ref t, m) => {
3287 hir::ForeignItemKind::Static(self.lower_ty(t, ImplTraitContext::Disallowed), m)
3289 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3290 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3292 vis: self.lower_visibility(&i.vis, None),
3297 fn lower_method_sig(
3299 generics: &Generics,
3302 impl_trait_return_allow: bool,
3303 is_async: Option<NodeId>,
3304 ) -> (hir::Generics, hir::MethodSig) {
3305 let header = self.lower_fn_header(sig.header);
3306 let (generics, decl) = self.add_in_band_defs(
3309 AnonymousLifetimeMode::PassThrough,
3310 |this, idty| this.lower_fn_decl(
3312 Some((fn_def_id, idty)),
3313 impl_trait_return_allow,
3317 (generics, hir::MethodSig { header, decl })
3320 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3322 IsAuto::Yes => hir::IsAuto::Yes,
3323 IsAuto::No => hir::IsAuto::No,
3327 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3329 unsafety: self.lower_unsafety(h.unsafety),
3330 asyncness: self.lower_asyncness(h.asyncness),
3331 constness: self.lower_constness(h.constness),
3336 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3338 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3339 Unsafety::Normal => hir::Unsafety::Normal,
3343 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3345 Constness::Const => hir::Constness::Const,
3346 Constness::NotConst => hir::Constness::NotConst,
3350 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3352 IsAsync::Async { .. } => hir::IsAsync::Async,
3353 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3357 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3359 UnOp::Deref => hir::UnDeref,
3360 UnOp::Not => hir::UnNot,
3361 UnOp::Neg => hir::UnNeg,
3365 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3367 node: match b.node {
3368 BinOpKind::Add => hir::BinOpKind::Add,
3369 BinOpKind::Sub => hir::BinOpKind::Sub,
3370 BinOpKind::Mul => hir::BinOpKind::Mul,
3371 BinOpKind::Div => hir::BinOpKind::Div,
3372 BinOpKind::Rem => hir::BinOpKind::Rem,
3373 BinOpKind::And => hir::BinOpKind::And,
3374 BinOpKind::Or => hir::BinOpKind::Or,
3375 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3376 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3377 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3378 BinOpKind::Shl => hir::BinOpKind::Shl,
3379 BinOpKind::Shr => hir::BinOpKind::Shr,
3380 BinOpKind::Eq => hir::BinOpKind::Eq,
3381 BinOpKind::Lt => hir::BinOpKind::Lt,
3382 BinOpKind::Le => hir::BinOpKind::Le,
3383 BinOpKind::Ne => hir::BinOpKind::Ne,
3384 BinOpKind::Ge => hir::BinOpKind::Ge,
3385 BinOpKind::Gt => hir::BinOpKind::Gt,
3391 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3392 let node = match p.node {
3393 PatKind::Wild => hir::PatKind::Wild,
3394 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3395 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3396 // `None` can occur in body-less function signatures
3397 def @ None | def @ Some(Def::Local(_)) => {
3398 let canonical_id = match def {
3399 Some(Def::Local(id)) => id,
3402 hir::PatKind::Binding(
3403 self.lower_binding_mode(binding_mode),
3406 sub.as_ref().map(|x| self.lower_pat(x)),
3409 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3414 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3419 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3420 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3421 let qpath = self.lower_qpath(
3425 ParamMode::Optional,
3426 ImplTraitContext::Disallowed,
3428 hir::PatKind::TupleStruct(
3430 pats.iter().map(|x| self.lower_pat(x)).collect(),
3434 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3438 ParamMode::Optional,
3439 ImplTraitContext::Disallowed,
3441 PatKind::Struct(ref path, ref fields, etc) => {
3442 let qpath = self.lower_qpath(
3446 ParamMode::Optional,
3447 ImplTraitContext::Disallowed,
3454 node: hir::FieldPat {
3455 id: self.next_id().node_id,
3456 ident: f.node.ident,
3457 pat: self.lower_pat(&f.node.pat),
3458 is_shorthand: f.node.is_shorthand,
3462 hir::PatKind::Struct(qpath, fs, etc)
3464 PatKind::Tuple(ref elts, ddpos) => {
3465 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3467 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3468 PatKind::Ref(ref inner, mutbl) => {
3469 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3471 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3472 P(self.lower_expr(e1)),
3473 P(self.lower_expr(e2)),
3474 self.lower_range_end(end),
3476 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3477 before.iter().map(|x| self.lower_pat(x)).collect(),
3478 slice.as_ref().map(|x| self.lower_pat(x)),
3479 after.iter().map(|x| self.lower_pat(x)).collect(),
3481 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3482 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3485 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3494 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3496 RangeEnd::Included(_) => hir::RangeEnd::Included,
3497 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3501 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3502 self.with_new_scopes(|this| {
3503 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3507 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3512 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3513 let kind = match e.node {
3514 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3515 ExprKind::ObsoleteInPlace(..) => {
3516 self.sess.abort_if_errors();
3517 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3519 ExprKind::Array(ref exprs) => {
3520 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3522 ExprKind::Repeat(ref expr, ref count) => {
3523 let expr = P(self.lower_expr(expr));
3524 let count = self.lower_anon_const(count);
3525 hir::ExprKind::Repeat(expr, count)
3527 ExprKind::Tup(ref elts) => {
3528 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3530 ExprKind::Call(ref f, ref args) => {
3531 let f = P(self.lower_expr(f));
3532 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3534 ExprKind::MethodCall(ref seg, ref args) => {
3535 let hir_seg = self.lower_path_segment(
3538 ParamMode::Optional,
3540 ParenthesizedGenericArgs::Err,
3541 ImplTraitContext::Disallowed,
3543 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3544 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3546 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3547 let binop = self.lower_binop(binop);
3548 let lhs = P(self.lower_expr(lhs));
3549 let rhs = P(self.lower_expr(rhs));
3550 hir::ExprKind::Binary(binop, lhs, rhs)
3552 ExprKind::Unary(op, ref ohs) => {
3553 let op = self.lower_unop(op);
3554 let ohs = P(self.lower_expr(ohs));
3555 hir::ExprKind::Unary(op, ohs)
3557 ExprKind::Lit(ref l) => hir::ExprKind::Lit(P((**l).clone())),
3558 ExprKind::Cast(ref expr, ref ty) => {
3559 let expr = P(self.lower_expr(expr));
3560 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3562 ExprKind::Type(ref expr, ref ty) => {
3563 let expr = P(self.lower_expr(expr));
3564 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3566 ExprKind::AddrOf(m, ref ohs) => {
3567 let m = self.lower_mutability(m);
3568 let ohs = P(self.lower_expr(ohs));
3569 hir::ExprKind::AddrOf(m, ohs)
3571 // More complicated than you might expect because the else branch
3572 // might be `if let`.
3573 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3574 let else_opt = else_opt.as_ref().map(|els| {
3576 ExprKind::IfLet(..) => {
3577 // wrap the if-let expr in a block
3578 let span = els.span;
3579 let els = P(self.lower_expr(els));
3580 let LoweredNodeId { node_id, hir_id } = self.next_id();
3581 let blk = P(hir::Block {
3586 rules: hir::DefaultBlock,
3588 targeted_by_break: false,
3589 recovered: blk.recovered,
3591 P(self.expr_block(blk, ThinVec::new()))
3593 _ => P(self.lower_expr(els)),
3597 let then_blk = self.lower_block(blk, false);
3598 let then_expr = self.expr_block(then_blk, ThinVec::new());
3600 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3602 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3603 hir::ExprKind::While(
3604 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3605 this.lower_block(body, false),
3606 this.lower_label(opt_label),
3609 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3610 hir::ExprKind::Loop(
3611 this.lower_block(body, false),
3612 this.lower_label(opt_label),
3613 hir::LoopSource::Loop,
3616 ExprKind::TryBlock(ref body) => {
3617 self.with_catch_scope(body.id, |this| {
3619 this.allow_internal_unstable(CompilerDesugaringKind::TryBlock, body.span);
3620 let mut block = this.lower_block(body, true).into_inner();
3621 let tail = block.expr.take().map_or_else(
3623 let LoweredNodeId { node_id, hir_id } = this.next_id();
3624 let span = this.sess.source_map().end_point(unstable_span);
3628 node: hir::ExprKind::Tup(hir_vec![]),
3629 attrs: ThinVec::new(),
3633 |x: P<hir::Expr>| x.into_inner(),
3635 block.expr = Some(this.wrap_in_try_constructor(
3636 "from_ok", tail, unstable_span));
3637 hir::ExprKind::Block(P(block), None)
3640 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3641 P(self.lower_expr(expr)),
3642 arms.iter().map(|x| self.lower_arm(x)).collect(),
3643 hir::MatchSource::Normal,
3645 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3646 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3647 this.with_new_scopes(|this| {
3648 let block = this.lower_block(block, false);
3649 this.expr_block(block, ThinVec::new())
3654 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3656 if let IsAsync::Async { closure_id, .. } = asyncness {
3657 let outer_decl = FnDecl {
3658 inputs: decl.inputs.clone(),
3659 output: FunctionRetTy::Default(fn_decl_span),
3662 // We need to lower the declaration outside the new scope, because we
3663 // have to conserve the state of being inside a loop condition for the
3664 // closure argument types.
3665 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3667 self.with_new_scopes(|this| {
3668 // FIXME(cramertj) allow `async` non-`move` closures with
3669 if capture_clause == CaptureBy::Ref &&
3670 !decl.inputs.is_empty()
3676 "`async` non-`move` closures with arguments \
3677 are not currently supported",
3679 .help("consider using `let` statements to manually capture \
3680 variables by reference before entering an \
3681 `async move` closure")
3685 // Transform `async |x: u8| -> X { ... }` into
3686 // `|x: u8| future_from_generator(|| -> X { ... })`
3687 let body_id = this.lower_body(Some(&outer_decl), |this| {
3688 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3691 let async_body = this.make_async_expr(
3692 capture_clause, closure_id, async_ret_ty,
3694 this.with_new_scopes(|this| this.lower_expr(body))
3696 this.expr(fn_decl_span, async_body, ThinVec::new())
3698 hir::ExprKind::Closure(
3699 this.lower_capture_clause(capture_clause),
3707 // Lower outside new scope to preserve `is_in_loop_condition`.
3708 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3710 self.with_new_scopes(|this| {
3711 let mut is_generator = false;
3712 let body_id = this.lower_body(Some(decl), |this| {
3713 let e = this.lower_expr(body);
3714 is_generator = this.is_generator;
3717 let generator_option = if is_generator {
3718 if !decl.inputs.is_empty() {
3723 "generators cannot have explicit arguments"
3725 this.sess.abort_if_errors();
3727 Some(match movability {
3728 Movability::Movable => hir::GeneratorMovability::Movable,
3729 Movability::Static => hir::GeneratorMovability::Static,
3732 if movability == Movability::Static {
3737 "closures cannot be static"
3742 hir::ExprKind::Closure(
3743 this.lower_capture_clause(capture_clause),
3752 ExprKind::Block(ref blk, opt_label) => {
3753 hir::ExprKind::Block(self.lower_block(blk,
3754 opt_label.is_some()),
3755 self.lower_label(opt_label))
3757 ExprKind::Assign(ref el, ref er) => {
3758 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3760 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
3761 self.lower_binop(op),
3762 P(self.lower_expr(el)),
3763 P(self.lower_expr(er)),
3765 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
3766 ExprKind::Index(ref el, ref er) => {
3767 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
3769 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3770 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3771 let id = self.next_id();
3772 let e1 = self.lower_expr(e1);
3773 let e2 = self.lower_expr(e2);
3774 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
3775 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
3776 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3777 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3778 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
3779 hir::ExprKind::Call(new, hir_vec![e1, e2])
3781 ExprKind::Range(ref e1, ref e2, lims) => {
3782 use syntax::ast::RangeLimits::*;
3784 let path = match (e1, e2, lims) {
3785 (&None, &None, HalfOpen) => "RangeFull",
3786 (&Some(..), &None, HalfOpen) => "RangeFrom",
3787 (&None, &Some(..), HalfOpen) => "RangeTo",
3788 (&Some(..), &Some(..), HalfOpen) => "Range",
3789 (&None, &Some(..), Closed) => "RangeToInclusive",
3790 (&Some(..), &Some(..), Closed) => unreachable!(),
3791 (_, &None, Closed) => self.diagnostic()
3792 .span_fatal(e.span, "inclusive range with no end")
3796 let fields = e1.iter()
3797 .map(|e| ("start", e))
3798 .chain(e2.iter().map(|e| ("end", e)))
3800 let expr = P(self.lower_expr(&e));
3801 let ident = Ident::new(Symbol::intern(s), e.span);
3802 self.field(ident, expr, e.span)
3804 .collect::<P<[hir::Field]>>();
3806 let is_unit = fields.is_empty();
3807 let struct_path = iter::once("ops")
3808 .chain(iter::once(path))
3809 .collect::<Vec<_>>();
3810 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
3811 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3813 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3819 hir::ExprKind::Path(struct_path)
3821 hir::ExprKind::Struct(struct_path, fields, None)
3824 attrs: e.attrs.clone(),
3827 ExprKind::Path(ref qself, ref path) => hir::ExprKind::Path(self.lower_qpath(
3831 ParamMode::Optional,
3832 ImplTraitContext::Disallowed,
3834 ExprKind::Break(opt_label, ref opt_expr) => {
3835 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3838 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3841 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3843 hir::ExprKind::Break(
3845 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3848 ExprKind::Continue(opt_label) => {
3849 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
3852 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3855 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3858 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
3859 ExprKind::InlineAsm(ref asm) => {
3860 let hir_asm = hir::InlineAsm {
3861 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3862 outputs: asm.outputs
3864 .map(|out| hir::InlineAsmOutput {
3865 constraint: out.constraint.clone(),
3867 is_indirect: out.is_indirect,
3870 asm: asm.asm.clone(),
3871 asm_str_style: asm.asm_str_style,
3872 clobbers: asm.clobbers.clone().into(),
3873 volatile: asm.volatile,
3874 alignstack: asm.alignstack,
3875 dialect: asm.dialect,
3878 let outputs = asm.outputs
3880 .map(|out| self.lower_expr(&out.expr))
3882 let inputs = asm.inputs
3884 .map(|&(_, ref input)| self.lower_expr(input))
3886 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
3888 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
3893 ParamMode::Optional,
3894 ImplTraitContext::Disallowed,
3896 fields.iter().map(|x| self.lower_field(x)).collect(),
3897 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3899 ExprKind::Paren(ref ex) => {
3900 let mut ex = self.lower_expr(ex);
3901 // include parens in span, but only if it is a super-span.
3902 if e.span.contains(ex.span) {
3905 // merge attributes into the inner expression.
3906 let mut attrs = e.attrs.clone();
3907 attrs.extend::<Vec<_>>(ex.attrs.into());
3912 ExprKind::Yield(ref opt_expr) => {
3913 self.is_generator = true;
3916 .map(|x| self.lower_expr(x))
3918 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
3920 hir::ExprKind::Yield(P(expr))
3923 // Desugar ExprIfLet
3924 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3925 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3928 // match <sub_expr> {
3930 // _ => [<else_opt> | ()]
3933 let mut arms = vec![];
3935 // `<pat> => <body>`
3937 let body = self.lower_block(body, false);
3938 let body_expr = P(self.expr_block(body, ThinVec::new()));
3939 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3940 arms.push(self.arm(pats, body_expr));
3943 // _ => [<else_opt>|()]
3945 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3946 let wildcard_pattern = self.pat_wild(e.span);
3947 let body = if let Some(else_expr) = wildcard_arm {
3948 P(self.lower_expr(else_expr))
3950 self.expr_tuple(e.span, hir_vec![])
3952 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3955 let contains_else_clause = else_opt.is_some();
3957 let sub_expr = P(self.lower_expr(sub_expr));
3959 hir::ExprKind::Match(
3962 hir::MatchSource::IfLetDesugar {
3963 contains_else_clause,
3968 // Desugar ExprWhileLet
3969 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3970 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3973 // [opt_ident]: loop {
3974 // match <sub_expr> {
3980 // Note that the block AND the condition are evaluated in the loop scope.
3981 // This is done to allow `break` from inside the condition of the loop.
3982 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3984 this.lower_block(body, false),
3985 this.expr_break(e.span, ThinVec::new()),
3986 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3990 // `<pat> => <body>`
3992 let body_expr = P(self.expr_block(body, ThinVec::new()));
3993 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3994 self.arm(pats, body_expr)
3999 let pat_under = self.pat_wild(e.span);
4000 self.arm(hir_vec![pat_under], break_expr)
4003 // `match <sub_expr> { ... }`
4004 let arms = hir_vec![pat_arm, break_arm];
4005 let match_expr = self.expr(
4007 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4011 // `[opt_ident]: loop { ... }`
4012 let loop_block = P(self.block_expr(P(match_expr)));
4013 let loop_expr = hir::ExprKind::Loop(
4015 self.lower_label(opt_label),
4016 hir::LoopSource::WhileLet,
4018 // add attributes to the outer returned expr node
4022 // Desugar ExprForLoop
4023 // From: `[opt_ident]: for <pat> in <head> <body>`
4024 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4028 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4030 // [opt_ident]: loop {
4032 // match ::std::iter::Iterator::next(&mut iter) {
4033 // ::std::option::Option::Some(val) => __next = val,
4034 // ::std::option::Option::None => break
4036 // let <pat> = __next;
4037 // StmtKind::Expr(<body>);
4045 let head = self.lower_expr(head);
4046 let head_sp = head.span;
4048 let iter = self.str_to_ident("iter");
4050 let next_ident = self.str_to_ident("__next");
4051 let next_sp = self.allow_internal_unstable(
4052 CompilerDesugaringKind::ForLoop,
4055 let next_pat = self.pat_ident_binding_mode(
4058 hir::BindingAnnotation::Mutable,
4061 // `::std::option::Option::Some(val) => next = val`
4063 let val_ident = self.str_to_ident("val");
4064 let val_pat = self.pat_ident(pat.span, val_ident);
4065 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4066 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4067 let assign = P(self.expr(
4069 hir::ExprKind::Assign(next_expr, val_expr),
4072 let some_pat = self.pat_some(pat.span, val_pat);
4073 self.arm(hir_vec![some_pat], assign)
4076 // `::std::option::Option::None => break`
4079 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4080 let pat = self.pat_none(e.span);
4081 self.arm(hir_vec![pat], break_expr)
4086 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
4088 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4090 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4091 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4092 let next_path = &["iter", "Iterator", "next"];
4093 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4094 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4095 let arms = hir_vec![pat_arm, break_arm];
4099 hir::ExprKind::Match(
4102 hir::MatchSource::ForLoopDesugar
4107 let match_stmt = respan(
4109 hir::StmtKind::Expr(match_expr, self.next_id().node_id)
4112 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4116 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
4118 // `let <pat> = __next`
4119 let pat = self.lower_pat(pat);
4120 let pat_let = self.stmt_let_pat(
4124 hir::LocalSource::ForLoopDesugar,
4127 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4128 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4129 let body_stmt = respan(
4131 hir::StmtKind::Expr(body_expr, self.next_id().node_id)
4134 let loop_block = P(self.block_all(
4136 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4140 // `[opt_ident]: loop { ... }`
4141 let loop_expr = hir::ExprKind::Loop(
4143 self.lower_label(opt_label),
4144 hir::LoopSource::ForLoop,
4146 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4147 let loop_expr = P(hir::Expr {
4152 attrs: ThinVec::new(),
4155 // `mut iter => { ... }`
4156 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4158 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4159 let into_iter_expr = {
4160 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4161 let into_iter = P(self.expr_std_path(
4162 head_sp, into_iter_path, None, ThinVec::new()));
4163 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4166 let match_expr = P(self.expr_match(
4170 hir::MatchSource::ForLoopDesugar,
4173 // `{ let _result = ...; _result }`
4174 // underscore prevents an unused_variables lint if the head diverges
4175 let result_ident = self.str_to_ident("_result");
4176 let (let_stmt, let_stmt_binding) =
4177 self.stmt_let(e.span, false, result_ident, match_expr);
4179 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4180 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4181 // add the attributes to the outer returned expr node
4182 return self.expr_block(block, e.attrs.clone());
4185 // Desugar ExprKind::Try
4187 ExprKind::Try(ref sub_expr) => {
4190 // match Try::into_result(<expr>) {
4191 // Ok(val) => #[allow(unreachable_code)] val,
4192 // Err(err) => #[allow(unreachable_code)]
4193 // // If there is an enclosing `catch {...}`
4194 // break 'catch_target Try::from_error(From::from(err)),
4196 // return Try::from_error(From::from(err)),
4200 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4202 // Try::into_result(<expr>)
4205 let sub_expr = self.lower_expr(sub_expr);
4207 let path = &["ops", "Try", "into_result"];
4208 let path = P(self.expr_std_path(
4209 unstable_span, path, None, ThinVec::new()));
4210 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4213 // #[allow(unreachable_code)]
4215 // allow(unreachable_code)
4217 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4218 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4219 let uc_nested = attr::mk_nested_word_item(uc_ident);
4220 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4222 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4224 let attrs = vec![attr];
4226 // Ok(val) => #[allow(unreachable_code)] val,
4228 let val_ident = self.str_to_ident("val");
4229 let val_pat = self.pat_ident(e.span, val_ident);
4230 let val_expr = P(self.expr_ident_with_attrs(
4234 ThinVec::from(attrs.clone()),
4236 let ok_pat = self.pat_ok(e.span, val_pat);
4238 self.arm(hir_vec![ok_pat], val_expr)
4241 // Err(err) => #[allow(unreachable_code)]
4242 // return Try::from_error(From::from(err)),
4244 let err_ident = self.str_to_ident("err");
4245 let err_local = self.pat_ident(e.span, err_ident);
4247 let path = &["convert", "From", "from"];
4248 let from = P(self.expr_std_path(
4249 e.span, path, None, ThinVec::new()));
4250 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4252 self.expr_call(e.span, from, hir_vec![err_expr])
4255 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4256 let thin_attrs = ThinVec::from(attrs);
4257 let catch_scope = self.catch_scopes.last().map(|x| *x);
4258 let ret_expr = if let Some(catch_node) = catch_scope {
4261 hir::ExprKind::Break(
4264 target_id: Ok(catch_node),
4266 Some(from_err_expr),
4271 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4274 let err_pat = self.pat_err(e.span, err_local);
4275 self.arm(hir_vec![err_pat], ret_expr)
4278 hir::ExprKind::Match(
4280 hir_vec![err_arm, ok_arm],
4281 hir::MatchSource::TryDesugar,
4285 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4288 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4295 attrs: e.attrs.clone(),
4299 fn lower_stmt(&mut self, s: &Stmt) -> OneVector<hir::Stmt> {
4300 smallvec![match s.node {
4301 StmtKind::Local(ref l) => Spanned {
4302 node: hir::StmtKind::Decl(
4304 node: hir::DeclKind::Local(self.lower_local(l)),
4307 self.lower_node_id(s.id).node_id,
4311 StmtKind::Item(ref it) => {
4312 // Can only use the ID once.
4313 let mut id = Some(s.id);
4314 return self.lower_item_id(it)
4316 .map(|item_id| Spanned {
4317 node: hir::StmtKind::Decl(
4319 node: hir::DeclKind::Item(item_id),
4323 .map(|id| self.lower_node_id(id).node_id)
4324 .unwrap_or_else(|| self.next_id().node_id),
4330 StmtKind::Expr(ref e) => Spanned {
4331 node: hir::StmtKind::Expr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4334 StmtKind::Semi(ref e) => Spanned {
4335 node: hir::StmtKind::Semi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4338 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4342 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4344 CaptureBy::Value => hir::CaptureByValue,
4345 CaptureBy::Ref => hir::CaptureByRef,
4349 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4350 /// the address space of that item instead of the item currently being
4351 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4352 /// lower a `Visibility` value although we haven't lowered the owning
4353 /// `ImplItem` in question yet.
4354 fn lower_visibility(
4357 explicit_owner: Option<NodeId>,
4358 ) -> hir::Visibility {
4359 let node = match v.node {
4360 VisibilityKind::Public => hir::VisibilityKind::Public,
4361 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4362 VisibilityKind::Restricted { ref path, id } => {
4363 let lowered_id = if let Some(owner) = explicit_owner {
4364 self.lower_node_id_with_owner(id, owner)
4366 self.lower_node_id(id)
4368 hir::VisibilityKind::Restricted {
4369 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4370 id: lowered_id.node_id,
4371 hir_id: lowered_id.hir_id,
4374 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4376 respan(v.span, node)
4379 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4381 Defaultness::Default => hir::Defaultness::Default {
4382 has_value: has_value,
4384 Defaultness::Final => {
4386 hir::Defaultness::Final
4391 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4393 BlockCheckMode::Default => hir::DefaultBlock,
4394 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4398 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4400 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4401 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4402 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4403 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4407 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4409 CompilerGenerated => hir::CompilerGenerated,
4410 UserProvided => hir::UserProvided,
4414 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4416 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4417 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4421 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4423 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4424 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4428 // Helper methods for building HIR.
4430 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4439 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4441 id: self.next_id().node_id,
4445 is_shorthand: false,
4449 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4450 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4451 P(self.expr(span, expr_break, attrs))
4458 args: hir::HirVec<hir::Expr>,
4460 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4463 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4464 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4467 fn expr_ident_with_attrs(
4472 attrs: ThinVec<Attribute>,
4474 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4478 def: Def::Local(binding),
4479 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4483 self.expr(span, expr_path, attrs)
4486 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4487 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4493 components: &[&str],
4494 params: Option<P<hir::GenericArgs>>,
4495 attrs: ThinVec<Attribute>,
4497 let path = self.std_path(span, components, params, true);
4500 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4509 arms: hir::HirVec<hir::Arm>,
4510 source: hir::MatchSource,
4512 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4515 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4516 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4519 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4520 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4523 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4524 let LoweredNodeId { node_id, hir_id } = self.next_id();
4537 ex: Option<P<hir::Expr>>,
4539 source: hir::LocalSource,
4541 let LoweredNodeId { node_id, hir_id } = self.next_id();
4543 let local = P(hir::Local {
4550 attrs: ThinVec::new(),
4553 let decl = respan(sp, hir::DeclKind::Local(local));
4554 respan(sp, hir::StmtKind::Decl(P(decl), self.next_id().node_id))
4563 ) -> (hir::Stmt, NodeId) {
4564 let pat = if mutbl {
4565 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4567 self.pat_ident(sp, ident)
4569 let pat_id = pat.id;
4571 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4576 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4577 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4583 stmts: hir::HirVec<hir::Stmt>,
4584 expr: Option<P<hir::Expr>>,
4586 let LoweredNodeId { node_id, hir_id } = self.next_id();
4593 rules: hir::DefaultBlock,
4595 targeted_by_break: false,
4600 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4601 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4604 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4605 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4608 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4609 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4612 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4613 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4619 components: &[&str],
4620 subpats: hir::HirVec<P<hir::Pat>>,
4622 let path = self.std_path(span, components, None, true);
4623 let qpath = hir::QPath::Resolved(None, P(path));
4624 let pt = if subpats.is_empty() {
4625 hir::PatKind::Path(qpath)
4627 hir::PatKind::TupleStruct(qpath, subpats, None)
4632 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4633 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4636 fn pat_ident_binding_mode(
4640 bm: hir::BindingAnnotation,
4642 let LoweredNodeId { node_id, hir_id } = self.next_id();
4647 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4652 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4653 self.pat(span, hir::PatKind::Wild)
4656 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4657 let LoweredNodeId { node_id, hir_id } = self.next_id();
4666 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4667 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4668 /// The path is also resolved according to `is_value`.
4672 components: &[&str],
4673 params: Option<P<hir::GenericArgs>>,
4677 .resolve_str_path(span, self.crate_root, components, params, is_value)
4680 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4682 let node = match qpath {
4683 hir::QPath::Resolved(None, path) => {
4684 // Turn trait object paths into `TyKind::TraitObject` instead.
4685 if let Def::Trait(_) = path.def {
4686 let principal = hir::PolyTraitRef {
4687 bound_generic_params: hir::HirVec::new(),
4688 trait_ref: hir::TraitRef {
4689 path: path.and_then(|path| path),
4691 hir_ref_id: id.hir_id,
4696 // The original ID is taken by the `PolyTraitRef`,
4697 // so the `Ty` itself needs a different one.
4698 id = self.next_id();
4699 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4701 hir::TyKind::Path(hir::QPath::Resolved(None, path))
4704 _ => hir::TyKind::Path(qpath),
4714 /// Invoked to create the lifetime argument for a type `&T`
4715 /// with no explicit lifetime.
4716 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4717 match self.anonymous_lifetime_mode {
4718 // Intercept when we are in an impl header and introduce an in-band lifetime.
4719 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4721 AnonymousLifetimeMode::CreateParameter => {
4722 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4724 id: self.next_id().node_id,
4726 name: hir::LifetimeName::Param(fresh_name),
4730 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4734 /// Invoked to create the lifetime argument(s) for a path like
4735 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4736 /// sorts of cases are deprecated. This may therefore report a warning or an
4737 /// error, depending on the mode.
4738 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4739 match self.anonymous_lifetime_mode {
4740 // NB. We intentionally ignore the create-parameter mode here
4741 // and instead "pass through" to resolve-lifetimes, which will then
4742 // report an error. This is because we don't want to support
4743 // impl elision for deprecated forms like
4745 // impl Foo for std::cell::Ref<u32> // note lack of '_
4746 AnonymousLifetimeMode::CreateParameter => {}
4748 // This is the normal case.
4749 AnonymousLifetimeMode::PassThrough => {}
4753 .map(|_| self.new_implicit_lifetime(span))
4757 /// Invoked to create the lifetime argument(s) for an elided trait object
4758 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4759 /// when the bound is written, even if it is written with `'_` like in
4760 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4761 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4762 match self.anonymous_lifetime_mode {
4763 // NB. We intentionally ignore the create-parameter mode here.
4764 // and instead "pass through" to resolve-lifetimes, which will apply
4765 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4766 // do not act like other elided lifetimes. In other words, given this:
4768 // impl Foo for Box<dyn Debug>
4770 // we do not introduce a fresh `'_` to serve as the bound, but instead
4771 // ultimately translate to the equivalent of:
4773 // impl Foo for Box<dyn Debug + 'static>
4775 // `resolve_lifetime` has the code to make that happen.
4776 AnonymousLifetimeMode::CreateParameter => {}
4778 // This is the normal case.
4779 AnonymousLifetimeMode::PassThrough => {}
4782 self.new_implicit_lifetime(span)
4785 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4787 id: self.next_id().node_id,
4789 name: hir::LifetimeName::Implicit,
4793 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4794 self.sess.buffer_lint_with_diagnostic(
4795 builtin::BARE_TRAIT_OBJECTS,
4798 "trait objects without an explicit `dyn` are deprecated",
4799 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4803 fn wrap_in_try_constructor(
4805 method: &'static str,
4807 unstable_span: Span,
4809 let path = &["ops", "Try", method];
4810 let from_err = P(self.expr_std_path(unstable_span, path, None,
4812 P(self.expr_call(e.span, from_err, hir_vec![e]))
4816 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4817 // Sorting by span ensures that we get things in order within a
4818 // file, and also puts the files in a sensible order.
4819 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4820 body_ids.sort_by_key(|b| bodies[b].value.span);