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;
55 use util::common::FN_OUTPUT_NAME;
56 use util::nodemap::{DefIdMap, NodeMap};
58 use std::collections::{BTreeMap, HashSet};
66 use syntax::ext::hygiene::{Mark, SyntaxContext};
67 use syntax::print::pprust;
69 use syntax::codemap::{self, respan, CompilerDesugaringKind, Spanned};
70 use syntax::std_inject;
71 use syntax::symbol::{keywords, Symbol};
72 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
73 use syntax::parse::token::Token;
74 use syntax::util::small_vector::SmallVector;
75 use syntax::visit::{self, Visitor};
76 use syntax_pos::{Span, MultiSpan};
78 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
80 pub struct LoweringContext<'a> {
81 crate_root: Option<&'static str>,
83 // Use to assign ids to hir nodes that do not directly correspond to an ast node
86 cstore: &'a dyn CrateStore,
88 resolver: &'a mut dyn Resolver,
90 /// The items being lowered are collected here.
91 items: BTreeMap<NodeId, hir::Item>,
93 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
94 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
95 bodies: BTreeMap<hir::BodyId, hir::Body>,
96 exported_macros: Vec<hir::MacroDef>,
98 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
99 trait_auto_impl: BTreeMap<DefId, NodeId>,
103 catch_scopes: Vec<NodeId>,
104 loop_scopes: Vec<NodeId>,
105 is_in_loop_condition: bool,
106 is_in_trait_impl: bool,
108 /// What to do when we encounter either an "anonymous lifetime
109 /// reference". The term "anonymous" is meant to encompass both
110 /// `'_` lifetimes as well as fully elided cases where nothing is
111 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
112 anonymous_lifetime_mode: AnonymousLifetimeMode,
114 // Used to create lifetime definitions from in-band lifetime usages.
115 // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
116 // When a named lifetime is encountered in a function or impl header and
117 // has not been defined
118 // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
119 // to this list. The results of this list are then added to the list of
120 // lifetime definitions in the corresponding impl or function generics.
121 lifetimes_to_define: Vec<(Span, ParamName)>,
123 // Whether or not in-band lifetimes are being collected. This is used to
124 // indicate whether or not we're in a place where new lifetimes will result
125 // in in-band lifetime definitions, such a function or an impl header.
126 // This will always be false unless the `in_band_lifetimes` or
127 // `impl_header_lifetime_elision` feature is enabled.
128 is_collecting_in_band_lifetimes: bool,
130 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
131 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
132 // against this list to see if it is already in-scope, or if a definition
133 // needs to be created for it.
134 in_scope_lifetimes: Vec<Ident>,
136 type_def_lifetime_params: DefIdMap<usize>,
138 current_hir_id_owner: Vec<(DefIndex, u32)>,
139 item_local_id_counters: NodeMap<u32>,
140 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
144 /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
145 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
147 /// Obtain the resolution for a node id
148 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
150 /// Obtain the possible resolutions for the given `use` statement.
151 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
153 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
154 /// This should only return `None` during testing.
155 fn definitions(&mut self) -> &mut Definitions;
157 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
158 /// it based on `is_value`.
162 crate_root: Option<&str>,
164 params: Option<P<hir::GenericArgs>>,
170 enum ImplTraitContext<'a> {
171 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
172 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
173 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
175 /// Newly generated parameters should be inserted into the given `Vec`
176 Universal(&'a mut Vec<hir::GenericParam>),
178 /// Treat `impl Trait` as shorthand for a new universal existential parameter.
179 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
180 /// equivalent to a fresh existential parameter like `abstract type T; fn foo() -> T`.
182 /// We store a DefId here so we can look up necessary information later
185 /// `impl Trait` is not accepted in this position.
189 impl<'a> ImplTraitContext<'a> {
190 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
191 use self::ImplTraitContext::*;
193 Universal(params) => Universal(params),
194 Existential(did) => Existential(*did),
195 Disallowed => Disallowed,
202 cstore: &dyn CrateStore,
203 dep_graph: &DepGraph,
205 resolver: &mut dyn Resolver,
207 // We're constructing the HIR here; we don't care what we will
208 // read, since we haven't even constructed the *input* to
210 dep_graph.assert_ignored();
213 crate_root: std_inject::injected_crate_name(),
217 items: BTreeMap::new(),
218 trait_items: BTreeMap::new(),
219 impl_items: BTreeMap::new(),
220 bodies: BTreeMap::new(),
221 trait_impls: BTreeMap::new(),
222 trait_auto_impl: BTreeMap::new(),
223 exported_macros: Vec::new(),
224 catch_scopes: Vec::new(),
225 loop_scopes: Vec::new(),
226 is_in_loop_condition: false,
227 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
228 type_def_lifetime_params: DefIdMap(),
229 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
230 item_local_id_counters: NodeMap(),
231 node_id_to_hir_id: IndexVec::new(),
233 is_in_trait_impl: false,
234 lifetimes_to_define: Vec::new(),
235 is_collecting_in_band_lifetimes: false,
236 in_scope_lifetimes: Vec::new(),
240 #[derive(Copy, Clone, PartialEq)]
242 /// Any path in a type context.
244 /// The `module::Type` in `module::Type::method` in an expression.
249 struct LoweredNodeId {
254 enum ParenthesizedGenericArgs {
260 /// What to do when we encounter an **anonymous** lifetime
261 /// reference. Anonymous lifetime references come in two flavors. You
262 /// have implicit, or fully elided, references to lifetimes, like the
263 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
264 /// or `Ref<'_, T>`. These often behave the same, but not always:
266 /// - certain usages of implicit references are deprecated, like
267 /// `Ref<T>`, and we sometimes just give hard errors in those cases
269 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
270 /// the same as `Box<dyn Foo + '_>`.
272 /// We describe the effects of the various modes in terms of three cases:
274 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
275 /// of a `&` (e.g., the missing lifetime in something like `&T`)
276 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
277 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
278 /// elided bounds follow special rules. Note that this only covers
279 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
280 /// '_>` is a case of "modern" elision.
281 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
282 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
283 /// non-deprecated equivalent.
285 /// Currently, the handling of lifetime elision is somewhat spread out
286 /// between HIR lowering and -- as described below -- the
287 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
288 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
289 /// everything into HIR lowering.
290 #[derive(Copy, Clone)]
291 enum AnonymousLifetimeMode {
292 /// For **Modern** cases, create a new anonymous region parameter
293 /// and reference that.
295 /// For **Dyn Bound** cases, pass responsibility to
296 /// `resolve_lifetime` code.
298 /// For **Deprecated** cases, report an error.
301 /// Pass responsibility to `resolve_lifetime` code for all cases.
305 impl<'a> LoweringContext<'a> {
306 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
307 /// Full-crate AST visitor that inserts into a fresh
308 /// `LoweringContext` any information that may be
309 /// needed from arbitrary locations in the crate.
310 /// E.g. The number of lifetime generic parameters
311 /// declared for every type and trait definition.
312 struct MiscCollector<'lcx, 'interner: 'lcx> {
313 lctx: &'lcx mut LoweringContext<'interner>,
316 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
317 fn visit_item(&mut self, item: &'lcx Item) {
318 self.lctx.allocate_hir_id_counter(item.id, item);
321 ItemKind::Struct(_, ref generics)
322 | ItemKind::Union(_, ref generics)
323 | ItemKind::Enum(_, ref generics)
324 | ItemKind::Ty(_, ref generics)
325 | ItemKind::Existential(_, ref generics)
326 | ItemKind::Trait(_, _, ref generics, ..) => {
327 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
331 .filter(|param| match param.kind {
332 ast::GenericParamKind::Lifetime { .. } => true,
336 self.lctx.type_def_lifetime_params.insert(def_id, count);
340 visit::walk_item(self, item);
343 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
344 self.lctx.allocate_hir_id_counter(item.id, item);
345 visit::walk_trait_item(self, item);
348 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
349 self.lctx.allocate_hir_id_counter(item.id, item);
350 visit::walk_impl_item(self, item);
354 struct ItemLowerer<'lcx, 'interner: 'lcx> {
355 lctx: &'lcx mut LoweringContext<'interner>,
358 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
359 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
361 F: FnOnce(&mut Self),
363 let old = self.lctx.is_in_trait_impl;
364 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
370 self.lctx.is_in_trait_impl = old;
374 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
375 fn visit_item(&mut self, item: &'lcx Item) {
376 let mut item_lowered = true;
377 self.lctx.with_hir_id_owner(item.id, |lctx| {
378 if let Some(hir_item) = lctx.lower_item(item) {
379 lctx.items.insert(item.id, hir_item);
381 item_lowered = false;
386 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
387 hir::ItemKind::Impl(_, _, _, ref generics, ..)
388 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
389 generics.params.clone()
394 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
395 let this = &mut ItemLowerer { lctx: this };
396 if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
397 this.with_trait_impl_ref(opt_trait_ref, |this| {
398 visit::walk_item(this, item)
401 visit::walk_item(this, item);
407 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
408 self.lctx.with_hir_id_owner(item.id, |lctx| {
409 let id = hir::TraitItemId { node_id: item.id };
410 let hir_item = lctx.lower_trait_item(item);
411 lctx.trait_items.insert(id, hir_item);
414 visit::walk_trait_item(self, item);
417 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
418 self.lctx.with_hir_id_owner(item.id, |lctx| {
419 let id = hir::ImplItemId { node_id: item.id };
420 let hir_item = lctx.lower_impl_item(item);
421 lctx.impl_items.insert(id, hir_item);
423 visit::walk_impl_item(self, item);
427 self.lower_node_id(CRATE_NODE_ID);
428 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
430 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
431 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
433 let module = self.lower_mod(&c.module);
434 let attrs = self.lower_attrs(&c.attrs);
435 let body_ids = body_ids(&self.bodies);
439 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
445 exported_macros: hir::HirVec::from(self.exported_macros),
447 trait_items: self.trait_items,
448 impl_items: self.impl_items,
451 trait_impls: self.trait_impls,
452 trait_auto_impl: self.trait_auto_impl,
456 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
457 if self.item_local_id_counters.insert(owner, 0).is_some() {
459 "Tried to allocate item_local_id_counter for {:?} twice",
463 // Always allocate the first HirId for the owner itself
464 self.lower_node_id_with_owner(owner, owner)
467 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
469 F: FnOnce(&mut Self) -> hir::HirId,
471 if ast_node_id == DUMMY_NODE_ID {
472 return LoweredNodeId {
473 node_id: DUMMY_NODE_ID,
474 hir_id: hir::DUMMY_HIR_ID,
478 let min_size = ast_node_id.as_usize() + 1;
480 if min_size > self.node_id_to_hir_id.len() {
481 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
484 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
486 if existing_hir_id == hir::DUMMY_HIR_ID {
487 // Generate a new HirId
488 let hir_id = alloc_hir_id(self);
489 self.node_id_to_hir_id[ast_node_id] = hir_id;
491 node_id: ast_node_id,
496 node_id: ast_node_id,
497 hir_id: existing_hir_id,
502 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
504 F: FnOnce(&mut Self) -> T,
506 let counter = self.item_local_id_counters
507 .insert(owner, HIR_ID_COUNTER_LOCKED)
508 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
509 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
510 self.current_hir_id_owner.push((def_index, counter));
512 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
514 debug_assert!(def_index == new_def_index);
515 debug_assert!(new_counter >= counter);
517 let prev = self.item_local_id_counters
518 .insert(owner, new_counter)
520 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
524 /// This method allocates a new HirId for the given NodeId and stores it in
525 /// the LoweringContext's NodeId => HirId map.
526 /// Take care not to call this method if the resulting HirId is then not
527 /// actually used in the HIR, as that would trigger an assertion in the
528 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
529 /// properly. Calling the method twice with the same NodeId is fine though.
530 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
531 self.lower_node_id_generic(ast_node_id, |this| {
532 let &mut (def_index, ref mut local_id_counter) =
533 this.current_hir_id_owner.last_mut().unwrap();
534 let local_id = *local_id_counter;
535 *local_id_counter += 1;
538 local_id: hir::ItemLocalId(local_id),
543 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
544 self.lower_node_id_generic(ast_node_id, |this| {
545 let local_id_counter = this
546 .item_local_id_counters
548 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
549 let local_id = *local_id_counter;
551 // We want to be sure not to modify the counter in the map while it
552 // is also on the stack. Otherwise we'll get lost updates when writing
553 // back from the stack to the map.
554 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
556 *local_id_counter += 1;
560 .opt_def_index(owner)
561 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
562 that do not belong to the current owner");
566 local_id: hir::ItemLocalId(local_id),
571 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
572 let body = hir::Body {
573 arguments: decl.map_or(hir_vec![], |decl| {
574 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
576 is_generator: self.is_generator,
580 self.bodies.insert(id, body);
584 fn next_id(&mut self) -> LoweredNodeId {
585 self.lower_node_id(self.sess.next_node_id())
588 fn expect_full_def(&mut self, id: NodeId) -> Def {
589 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
590 if pr.unresolved_segments() != 0 {
591 bug!("path not fully resolved: {:?}", pr);
597 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item=Def> {
598 self.resolver.get_import(id).present_items().map(|pr| {
599 if pr.unresolved_segments() != 0 {
600 bug!("path not fully resolved: {:?}", pr);
606 fn diagnostic(&self) -> &errors::Handler {
607 self.sess.diagnostic()
610 fn str_to_ident(&self, s: &'static str) -> Ident {
611 Ident::with_empty_ctxt(Symbol::gensym(s))
614 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
615 let mark = Mark::fresh(Mark::root());
616 mark.set_expn_info(codemap::ExpnInfo {
618 def_site: Some(span),
619 format: codemap::CompilerDesugaring(reason),
620 allow_internal_unstable: true,
621 allow_internal_unsafe: false,
622 local_inner_macros: false,
623 edition: codemap::hygiene::default_edition(),
625 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
628 fn with_anonymous_lifetime_mode<R>(
630 anonymous_lifetime_mode: AnonymousLifetimeMode,
631 op: impl FnOnce(&mut Self) -> R,
633 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
634 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
635 let result = op(self);
636 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
640 /// Creates a new hir::GenericParam for every new lifetime and
641 /// type parameter encountered while evaluating `f`. Definitions
642 /// are created with the parent provided. If no `parent_id` is
643 /// provided, no definitions will be returned.
645 /// Presuming that in-band lifetimes are enabled, then
646 /// `self.anonymous_lifetime_mode` will be updated to match the
647 /// argument while `f` is running (and restored afterwards).
648 fn collect_in_band_defs<T, F>(
651 anonymous_lifetime_mode: AnonymousLifetimeMode,
653 ) -> (Vec<hir::GenericParam>, T)
655 F: FnOnce(&mut LoweringContext) -> (Vec<hir::GenericParam>, T),
657 assert!(!self.is_collecting_in_band_lifetimes);
658 assert!(self.lifetimes_to_define.is_empty());
659 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
661 if self.sess.features_untracked().impl_header_lifetime_elision {
662 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
663 self.is_collecting_in_band_lifetimes = true;
664 } else if self.sess.features_untracked().in_band_lifetimes {
665 self.is_collecting_in_band_lifetimes = true;
668 let (in_band_ty_params, res) = f(self);
670 self.is_collecting_in_band_lifetimes = false;
671 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
673 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
675 let params = lifetimes_to_define
677 .map(|(span, hir_name)| {
678 let def_node_id = self.next_id().node_id;
680 // Get the name we'll use to make the def-path. Note
681 // that collisions are ok here and this shouldn't
682 // really show up for end-user.
683 let str_name = match hir_name {
684 ParamName::Plain(ident) => ident.as_interned_str(),
685 ParamName::Fresh(_) => keywords::UnderscoreLifetime.name().as_interned_str(),
688 // Add a definition for the in-band lifetime def
689 self.resolver.definitions().create_def_with_parent(
692 DefPathData::LifetimeParam(str_name),
693 DefIndexAddressSpace::High,
704 pure_wrt_drop: false,
705 kind: hir::GenericParamKind::Lifetime { in_band: true }
708 .chain(in_band_ty_params.into_iter())
714 /// When there is a reference to some lifetime `'a`, and in-band
715 /// lifetimes are enabled, then we want to push that lifetime into
716 /// the vector of names to define later. In that case, it will get
717 /// added to the appropriate generics.
718 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
719 if !self.is_collecting_in_band_lifetimes {
723 if !self.sess.features_untracked().in_band_lifetimes {
727 if self.in_scope_lifetimes.contains(&ident.modern()) {
731 let hir_name = ParamName::Plain(ident);
733 if self.lifetimes_to_define.iter()
734 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
738 self.lifetimes_to_define.push((ident.span, hir_name));
741 /// When we have either an elided or `'_` lifetime in an impl
742 /// header, we convert it to
743 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
744 assert!(self.is_collecting_in_band_lifetimes);
745 let index = self.lifetimes_to_define.len();
746 let hir_name = ParamName::Fresh(index);
747 self.lifetimes_to_define.push((span, hir_name));
751 // Evaluates `f` with the lifetimes in `params` in-scope.
752 // This is used to track which lifetimes have already been defined, and
753 // which are new in-band lifetimes that need to have a definition created
755 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
757 F: FnOnce(&mut LoweringContext) -> T,
759 let old_len = self.in_scope_lifetimes.len();
760 let lt_def_names = params.iter().filter_map(|param| match param.kind {
761 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
764 self.in_scope_lifetimes.extend(lt_def_names);
768 self.in_scope_lifetimes.truncate(old_len);
772 // Same as the method above, but accepts `hir::GenericParam`s
773 // instead of `ast::GenericParam`s.
774 // This should only be used with generics that have already had their
775 // in-band lifetimes added. In practice, this means that this function is
776 // only used when lowering a child item of a trait or impl.
777 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
778 params: &HirVec<hir::GenericParam>,
781 F: FnOnce(&mut LoweringContext) -> T,
783 let old_len = self.in_scope_lifetimes.len();
784 let lt_def_names = params.iter().filter_map(|param| match param.kind {
785 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
788 self.in_scope_lifetimes.extend(lt_def_names);
792 self.in_scope_lifetimes.truncate(old_len);
796 /// Appends in-band lifetime defs and argument-position `impl
797 /// Trait` defs to the existing set of generics.
799 /// Presuming that in-band lifetimes are enabled, then
800 /// `self.anonymous_lifetime_mode` will be updated to match the
801 /// argument while `f` is running (and restored afterwards).
802 fn add_in_band_defs<F, T>(
806 anonymous_lifetime_mode: AnonymousLifetimeMode,
808 ) -> (hir::Generics, T)
810 F: FnOnce(&mut LoweringContext, &mut Vec<hir::GenericParam>) -> T,
812 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
815 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
816 let mut params = Vec::new();
817 let generics = this.lower_generics(
819 ImplTraitContext::Universal(&mut params),
821 let res = f(this, &mut params);
822 (params, (generics, res))
827 lowered_generics.params = lowered_generics
834 (lowered_generics, res)
837 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
839 F: FnOnce(&mut LoweringContext) -> T,
841 let len = self.catch_scopes.len();
842 self.catch_scopes.push(catch_id);
844 let result = f(self);
847 self.catch_scopes.len(),
848 "catch scopes should be added and removed in stack order"
851 self.catch_scopes.pop().unwrap();
858 capture_clause: CaptureBy,
859 closure_node_id: NodeId,
861 body: impl FnOnce(&mut LoweringContext) -> hir::Expr,
863 let prev_is_generator = mem::replace(&mut self.is_generator, true);
864 let body_expr = body(self);
865 let span = body_expr.span;
866 let output = match ret_ty {
867 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
868 None => FunctionRetTy::Default(span),
875 let body_id = self.record_body(body_expr, Some(&decl));
876 self.is_generator = prev_is_generator;
878 let capture_clause = self.lower_capture_clause(capture_clause);
879 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
880 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
881 let generator = hir::Expr {
883 hir_id: closure_hir_id,
884 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
885 Some(hir::GeneratorMovability::Static)),
887 attrs: ThinVec::new(),
890 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
891 let gen_future = self.expr_std_path(
892 unstable_span, &["future", "from_generator"], None, ThinVec::new());
893 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
896 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
898 F: FnOnce(&mut LoweringContext) -> hir::Expr,
900 let prev = mem::replace(&mut self.is_generator, false);
901 let result = f(self);
902 let r = self.record_body(result, decl);
903 self.is_generator = prev;
907 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
909 F: FnOnce(&mut LoweringContext) -> T,
911 // We're no longer in the base loop's condition; we're in another loop.
912 let was_in_loop_condition = self.is_in_loop_condition;
913 self.is_in_loop_condition = false;
915 let len = self.loop_scopes.len();
916 self.loop_scopes.push(loop_id);
918 let result = f(self);
921 self.loop_scopes.len(),
922 "Loop scopes should be added and removed in stack order"
925 self.loop_scopes.pop().unwrap();
927 self.is_in_loop_condition = was_in_loop_condition;
932 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
934 F: FnOnce(&mut LoweringContext) -> T,
936 let was_in_loop_condition = self.is_in_loop_condition;
937 self.is_in_loop_condition = true;
939 let result = f(self);
941 self.is_in_loop_condition = was_in_loop_condition;
946 fn with_new_scopes<T, F>(&mut self, f: F) -> T
948 F: FnOnce(&mut LoweringContext) -> T,
950 let was_in_loop_condition = self.is_in_loop_condition;
951 self.is_in_loop_condition = false;
953 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
954 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
955 let result = f(self);
956 self.catch_scopes = catch_scopes;
957 self.loop_scopes = loop_scopes;
959 self.is_in_loop_condition = was_in_loop_condition;
964 fn def_key(&mut self, id: DefId) -> DefKey {
966 self.resolver.definitions().def_key(id.index)
968 self.cstore.def_key(id)
972 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
973 label.map(|label| hir::Label {
978 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
979 let target_id = match destination {
981 if let Def::Label(loop_id) = self.expect_full_def(id) {
982 Ok(self.lower_node_id(loop_id).node_id)
984 Err(hir::LoopIdError::UnresolvedLabel)
990 .map(|innermost_loop_id| *innermost_loop_id)
991 .map(|id| Ok(self.lower_node_id(id).node_id))
992 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
997 label: self.lower_label(destination.map(|(_, label)| label)),
1002 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1005 .map(|a| self.lower_attr(a))
1006 .collect::<Vec<_>>()
1010 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1014 path: attr.path.clone(),
1015 tokens: self.lower_token_stream(attr.tokens.clone()),
1016 is_sugared_doc: attr.is_sugared_doc,
1021 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1024 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1028 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1030 TokenTree::Token(span, token) => self.lower_token(token, span),
1031 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1034 delim: delimited.delim,
1035 tts: self.lower_token_stream(delimited.tts.into()).into(),
1041 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1043 Token::Interpolated(_) => {}
1044 other => return TokenTree::Token(span, other).into(),
1047 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1048 self.lower_token_stream(tts)
1051 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1053 attrs: self.lower_attrs(&arm.attrs),
1054 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1055 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1056 body: P(self.lower_expr(&arm.body)),
1060 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1062 id: self.lower_node_id(b.id).node_id,
1064 ty: self.lower_ty(&b.ty, itctx),
1069 fn lower_generic_arg(&mut self,
1070 arg: &ast::GenericArg,
1071 itctx: ImplTraitContext)
1072 -> hir::GenericArg {
1074 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1075 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1079 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1080 P(self.lower_ty_direct(t, itctx))
1083 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext) -> hir::Ty {
1084 let kind = match t.node {
1085 TyKind::Infer => hir::TyKind::Infer,
1086 TyKind::Err => hir::TyKind::Err,
1087 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1088 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1089 TyKind::Rptr(ref region, ref mt) => {
1090 let span = t.span.shrink_to_lo();
1091 let lifetime = match *region {
1092 Some(ref lt) => self.lower_lifetime(lt),
1093 None => self.elided_ref_lifetime(span),
1095 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1097 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1100 this.with_anonymous_lifetime_mode(
1101 AnonymousLifetimeMode::PassThrough,
1103 hir::TyKind::BareFn(P(hir::BareFnTy {
1104 generic_params: this.lower_generic_params(
1107 ImplTraitContext::Disallowed,
1109 unsafety: this.lower_unsafety(f.unsafety),
1111 decl: this.lower_fn_decl(&f.decl, None, false, None),
1112 arg_names: this.lower_fn_args_to_names(&f.decl),
1118 TyKind::Never => hir::TyKind::Never,
1119 TyKind::Tup(ref tys) => {
1120 hir::TyKind::Tup(tys.iter().map(|ty| {
1121 self.lower_ty_direct(ty, itctx.reborrow())
1124 TyKind::Paren(ref ty) => {
1125 return self.lower_ty_direct(ty, itctx);
1127 TyKind::Path(ref qself, ref path) => {
1128 let id = self.lower_node_id(t.id);
1129 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1130 let ty = self.ty_path(id, t.span, qpath);
1131 if let hir::TyKind::TraitObject(..) = ty.node {
1132 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1136 TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1139 def: self.expect_full_def(t.id),
1140 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1144 TyKind::Array(ref ty, ref length) => {
1145 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1147 TyKind::Typeof(ref expr) => {
1148 hir::TyKind::Typeof(self.lower_anon_const(expr))
1150 TyKind::TraitObject(ref bounds, kind) => {
1151 let mut lifetime_bound = None;
1154 .filter_map(|bound| match *bound {
1155 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1156 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1158 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1159 GenericBound::Outlives(ref lifetime) => {
1160 if lifetime_bound.is_none() {
1161 lifetime_bound = Some(self.lower_lifetime(lifetime));
1167 let lifetime_bound =
1168 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1169 if kind != TraitObjectSyntax::Dyn {
1170 self.maybe_lint_bare_trait(t.span, t.id, false);
1172 hir::TyKind::TraitObject(bounds, lifetime_bound)
1174 TyKind::ImplTrait(def_node_id, ref bounds) => {
1177 ImplTraitContext::Existential(fn_def_id) => {
1178 self.lower_existential_impl_trait(
1179 span, fn_def_id, def_node_id,
1180 |this| this.lower_param_bounds(bounds, itctx),
1183 ImplTraitContext::Universal(in_band_ty_params) => {
1184 self.lower_node_id(def_node_id);
1185 // Add a definition for the in-band TyParam
1186 let def_index = self
1189 .opt_def_index(def_node_id)
1192 let hir_bounds = self.lower_param_bounds(
1194 ImplTraitContext::Universal(in_band_ty_params),
1196 // Set the name to `impl Bound1 + Bound2`
1197 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1198 in_band_ty_params.push(hir::GenericParam {
1200 name: ParamName::Plain(ident),
1201 pure_wrt_drop: false,
1205 kind: hir::GenericParamKind::Type {
1207 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1211 hir::TyKind::Path(hir::QPath::Resolved(
1215 def: Def::TyParam(DefId::local(def_index)),
1216 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1220 ImplTraitContext::Disallowed => {
1225 "`impl Trait` not allowed outside of function \
1226 and inherent method return types"
1232 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1235 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1244 fn lower_existential_impl_trait(
1248 exist_ty_node_id: NodeId,
1249 lower_bounds: impl FnOnce(&mut LoweringContext) -> hir::GenericBounds,
1251 // Make sure we know that some funky desugaring has been going on here.
1252 // This is a first: there is code in other places like for loop
1253 // desugaring that explicitly states that we don't want to track that.
1254 // Not tracking it makes lints in rustc and clippy very fragile as
1255 // frequently opened issues show.
1256 let exist_ty_span = self.allow_internal_unstable(
1257 CompilerDesugaringKind::ExistentialReturnType,
1261 let exist_ty_def_index = self
1264 .opt_def_index(exist_ty_node_id)
1268 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1270 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1272 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1278 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1279 let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1280 generics: hir::Generics {
1281 params: lifetime_defs,
1282 where_clause: hir::WhereClause {
1283 id: lctx.next_id().node_id,
1284 predicates: Vec::new().into(),
1289 impl_trait_fn: Some(fn_def_id),
1291 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1292 // Generate an `existential type Foo: Trait;` declaration
1293 trace!("creating existential type with id {:#?}", exist_ty_id);
1295 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1296 let exist_ty_item = hir::Item {
1297 id: exist_ty_id.node_id,
1298 hir_id: exist_ty_id.hir_id,
1299 name: keywords::Invalid.name(),
1300 attrs: Default::default(),
1301 node: exist_ty_item_kind,
1302 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1303 span: exist_ty_span,
1306 // Insert the item into the global list. This usually happens
1307 // automatically for all AST items. But this existential type item
1308 // does not actually exist in the AST.
1309 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1311 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1312 let path = P(hir::Path {
1313 span: exist_ty_span,
1314 def: Def::Existential(DefId::local(exist_ty_def_index)),
1315 segments: hir_vec![hir::PathSegment {
1317 ident: Ident::new(keywords::Invalid.name(), exist_ty_span),
1318 args: Some(P(hir::GenericArgs {
1319 parenthesized: false,
1320 bindings: HirVec::new(),
1325 hir::TyKind::Path(hir::QPath::Resolved(None, path))
1329 fn lifetimes_from_impl_trait_bounds(
1331 exist_ty_id: NodeId,
1332 parent_index: DefIndex,
1333 bounds: &hir::GenericBounds,
1334 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1335 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1336 // appear in the bounds, excluding lifetimes that are created within the bounds.
1337 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1338 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1339 context: &'r mut LoweringContext<'a>,
1341 exist_ty_id: NodeId,
1342 collect_elided_lifetimes: bool,
1343 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1344 already_defined_lifetimes: HashSet<hir::LifetimeName>,
1345 output_lifetimes: Vec<hir::GenericArg>,
1346 output_lifetime_params: Vec<hir::GenericParam>,
1349 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1350 fn nested_visit_map<'this>(
1352 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1353 hir::intravisit::NestedVisitorMap::None
1356 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1357 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1358 if parameters.parenthesized {
1359 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1360 self.collect_elided_lifetimes = false;
1361 hir::intravisit::walk_generic_args(self, span, parameters);
1362 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1364 hir::intravisit::walk_generic_args(self, span, parameters);
1368 fn visit_ty(&mut self, t: &'v hir::Ty) {
1369 // Don't collect elided lifetimes used inside of `fn()` syntax
1370 if let hir::TyKind::BareFn(_) = t.node {
1371 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1372 self.collect_elided_lifetimes = false;
1374 // Record the "stack height" of `for<'a>` lifetime bindings
1375 // to be able to later fully undo their introduction.
1376 let old_len = self.currently_bound_lifetimes.len();
1377 hir::intravisit::walk_ty(self, t);
1378 self.currently_bound_lifetimes.truncate(old_len);
1380 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1382 hir::intravisit::walk_ty(self, t)
1386 fn visit_poly_trait_ref(
1388 trait_ref: &'v hir::PolyTraitRef,
1389 modifier: hir::TraitBoundModifier,
1391 // Record the "stack height" of `for<'a>` lifetime bindings
1392 // to be able to later fully undo their introduction.
1393 let old_len = self.currently_bound_lifetimes.len();
1394 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1395 self.currently_bound_lifetimes.truncate(old_len);
1398 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1399 // Record the introduction of 'a in `for<'a> ...`
1400 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1401 // Introduce lifetimes one at a time so that we can handle
1402 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1403 let lt_name = hir::LifetimeName::Param(param.name);
1404 self.currently_bound_lifetimes.push(lt_name);
1407 hir::intravisit::walk_generic_param(self, param);
1410 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1411 let name = match lifetime.name {
1412 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1413 if self.collect_elided_lifetimes {
1414 // Use `'_` for both implicit and underscore lifetimes in
1415 // `abstract type Foo<'_>: SomeTrait<'_>;`
1416 hir::LifetimeName::Underscore
1421 hir::LifetimeName::Param(_) => lifetime.name,
1422 hir::LifetimeName::Static => return,
1425 if !self.currently_bound_lifetimes.contains(&name)
1426 && !self.already_defined_lifetimes.contains(&name) {
1427 self.already_defined_lifetimes.insert(name);
1429 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1430 id: self.context.next_id().node_id,
1431 span: lifetime.span,
1435 // We need to manually create the ids here, because the
1436 // definitions will go into the explicit `existential type`
1437 // declaration and thus need to have their owner set to that item
1438 let def_node_id = self.context.sess.next_node_id();
1439 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1440 self.context.resolver.definitions().create_def_with_parent(
1443 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1444 DefIndexAddressSpace::High,
1449 let name = match name {
1450 hir::LifetimeName::Underscore => {
1451 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident())
1453 hir::LifetimeName::Param(param_name) => param_name,
1454 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1457 self.output_lifetime_params.push(hir::GenericParam {
1460 span: lifetime.span,
1461 pure_wrt_drop: false,
1464 kind: hir::GenericParamKind::Lifetime {
1472 let mut lifetime_collector = ImplTraitLifetimeCollector {
1474 parent: parent_index,
1476 collect_elided_lifetimes: true,
1477 currently_bound_lifetimes: Vec::new(),
1478 already_defined_lifetimes: HashSet::new(),
1479 output_lifetimes: Vec::new(),
1480 output_lifetime_params: Vec::new(),
1483 for bound in bounds {
1484 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1488 lifetime_collector.output_lifetimes.into(),
1489 lifetime_collector.output_lifetime_params.into(),
1493 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1498 .map(|x| self.lower_foreign_item(x))
1503 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1510 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1512 node: hir::VariantKind {
1513 name: v.node.ident.name,
1514 attrs: self.lower_attrs(&v.node.attrs),
1515 data: self.lower_variant_data(&v.node.data),
1516 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1525 qself: &Option<QSelf>,
1527 param_mode: ParamMode,
1528 mut itctx: ImplTraitContext,
1530 let qself_position = qself.as_ref().map(|q| q.position);
1531 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1533 let resolution = self.resolver
1535 .unwrap_or(PathResolution::new(Def::Err));
1537 let proj_start = p.segments.len() - resolution.unresolved_segments();
1538 let path = P(hir::Path {
1539 def: resolution.base_def(),
1540 segments: p.segments[..proj_start]
1543 .map(|(i, segment)| {
1544 let param_mode = match (qself_position, param_mode) {
1545 (Some(j), ParamMode::Optional) if i < j => {
1546 // This segment is part of the trait path in a
1547 // qualified path - one of `a`, `b` or `Trait`
1548 // in `<X as a::b::Trait>::T::U::method`.
1554 // Figure out if this is a type/trait segment,
1555 // which may need lifetime elision performed.
1556 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1557 krate: def_id.krate,
1558 index: this.def_key(def_id).parent.expect("missing parent"),
1560 let type_def_id = match resolution.base_def() {
1561 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1562 Some(parent_def_id(self, def_id))
1564 Def::Variant(def_id) if i + 1 == proj_start => {
1565 Some(parent_def_id(self, def_id))
1568 | Def::Union(def_id)
1570 | Def::TyAlias(def_id)
1571 | Def::Trait(def_id) if i + 1 == proj_start =>
1577 let parenthesized_generic_args = match resolution.base_def() {
1578 // `a::b::Trait(Args)`
1579 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1580 // `a::b::Trait(Args)::TraitItem`
1581 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1582 if i + 2 == proj_start =>
1584 ParenthesizedGenericArgs::Ok
1586 // Avoid duplicated errors
1587 Def::Err => ParenthesizedGenericArgs::Ok,
1593 | Def::Variant(..) if i + 1 == proj_start =>
1595 ParenthesizedGenericArgs::Err
1597 // A warning for now, for compatibility reasons
1598 _ => ParenthesizedGenericArgs::Warn,
1601 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1602 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1605 assert!(!def_id.is_local());
1607 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1608 let n = item_generics.own_counts().lifetimes;
1609 self.type_def_lifetime_params.insert(def_id, n);
1612 self.lower_path_segment(
1617 parenthesized_generic_args,
1625 // Simple case, either no projections, or only fully-qualified.
1626 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1627 if resolution.unresolved_segments() == 0 {
1628 return hir::QPath::Resolved(qself, path);
1631 // Create the innermost type that we're projecting from.
1632 let mut ty = if path.segments.is_empty() {
1633 // If the base path is empty that means there exists a
1634 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1635 qself.expect("missing QSelf for <T>::...")
1637 // Otherwise, the base path is an implicit `Self` type path,
1638 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1639 // `<I as Iterator>::Item::default`.
1640 let new_id = self.next_id();
1641 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1644 // Anything after the base path are associated "extensions",
1645 // out of which all but the last one are associated types,
1646 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1647 // * base path is `std::vec::Vec<T>`
1648 // * "extensions" are `IntoIter`, `Item` and `clone`
1649 // * type nodes are:
1650 // 1. `std::vec::Vec<T>` (created above)
1651 // 2. `<std::vec::Vec<T>>::IntoIter`
1652 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1653 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1654 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1655 let segment = P(self.lower_path_segment(
1660 ParenthesizedGenericArgs::Warn,
1663 let qpath = hir::QPath::TypeRelative(ty, segment);
1665 // It's finished, return the extension of the right node type.
1666 if i == p.segments.len() - 1 {
1670 // Wrap the associated extension in another type node.
1671 let new_id = self.next_id();
1672 ty = P(self.ty_path(new_id, p.span, qpath));
1675 // Should've returned in the for loop above.
1678 "lower_qpath: no final extension segment in {}..{}",
1684 fn lower_path_extra(
1688 ident: Option<Ident>,
1689 param_mode: ParamMode,
1693 segments: p.segments
1696 self.lower_path_segment(
1701 ParenthesizedGenericArgs::Err,
1702 ImplTraitContext::Disallowed,
1705 .chain(ident.map(|ident| hir::PathSegment::from_ident(ident)))
1711 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1712 let def = self.expect_full_def(id);
1713 self.lower_path_extra(def, p, None, param_mode)
1716 fn lower_path_segment(
1719 segment: &PathSegment,
1720 param_mode: ParamMode,
1721 expected_lifetimes: usize,
1722 parenthesized_generic_args: ParenthesizedGenericArgs,
1723 itctx: ImplTraitContext,
1724 ) -> hir::PathSegment {
1725 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1726 let msg = "parenthesized parameters may only be used with a trait";
1727 match **generic_args {
1728 GenericArgs::AngleBracketed(ref data) => {
1729 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1731 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1732 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1733 ParenthesizedGenericArgs::Warn => {
1734 self.sess.buffer_lint(
1735 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1740 (hir::GenericArgs::none(), true)
1742 ParenthesizedGenericArgs::Err => {
1743 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1744 .span_label(data.span, "only traits may use parentheses")
1746 (hir::GenericArgs::none(), true)
1751 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1754 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1755 GenericArg::Lifetime(_) => true,
1758 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1759 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1760 if !generic_args.parenthesized && !has_lifetimes {
1762 self.elided_path_lifetimes(path_span, expected_lifetimes)
1764 .map(|lt| GenericArg::Lifetime(lt))
1765 .chain(generic_args.args.into_iter())
1767 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1768 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1769 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1770 let no_bindings = generic_args.bindings.is_empty();
1771 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1772 // If there are no (non-implicit) generic args or associated-type
1773 // bindings, our suggestion includes the angle brackets
1774 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1776 // Otherwise—sorry, this is kind of gross—we need to infer the
1777 // place to splice in the `'_, ` from the generics that do exist
1778 let first_generic_span = first_generic_span
1779 .expect("already checked that type args or bindings exist");
1780 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1782 self.sess.buffer_lint_with_diagnostic(
1783 ELIDED_LIFETIMES_IN_PATHS,
1786 "hidden lifetime parameters in types are deprecated",
1787 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1788 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1794 hir::PathSegment::new(
1801 fn lower_angle_bracketed_parameter_data(
1803 data: &AngleBracketedArgs,
1804 param_mode: ParamMode,
1805 mut itctx: ImplTraitContext,
1806 ) -> (hir::GenericArgs, bool) {
1807 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1808 let has_types = args.iter().any(|arg| match arg {
1809 ast::GenericArg::Type(_) => true,
1813 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1814 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1815 parenthesized: false,
1817 !has_types && param_mode == ParamMode::Optional)
1820 fn lower_parenthesized_parameter_data(
1822 data: &ParenthesisedArgs,
1823 ) -> (hir::GenericArgs, bool) {
1824 // Switch to `PassThrough` mode for anonymous lifetimes: this
1825 // means that we permit things like `&Ref<T>`, where `Ref` has
1826 // a hidden lifetime parameter. This is needed for backwards
1827 // compatibility, even in contexts like an impl header where
1828 // we generally don't permit such things (see #51008).
1829 self.with_anonymous_lifetime_mode(
1830 AnonymousLifetimeMode::PassThrough,
1832 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1833 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1834 let inputs = inputs.iter().map(|ty| this.lower_ty_direct(ty, DISALLOWED)).collect();
1835 let mk_tup = |this: &mut Self, tys, span| {
1836 let LoweredNodeId { node_id, hir_id } = this.next_id();
1837 hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1842 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1845 id: this.next_id().node_id,
1846 ident: Ident::from_str(FN_OUTPUT_NAME),
1849 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1850 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1851 span: output.as_ref().map_or(span, |ty| ty.span),
1854 parenthesized: true,
1862 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1863 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1869 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1870 pat: self.lower_pat(&l.pat),
1871 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1873 attrs: l.attrs.clone(),
1874 source: hir::LocalSource::Normal,
1878 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1880 Mutability::Mutable => hir::MutMutable,
1881 Mutability::Immutable => hir::MutImmutable,
1885 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1886 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1890 pat: self.lower_pat(&arg.pat),
1894 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1897 .map(|arg| match arg.pat.node {
1898 PatKind::Ident(_, ident, _) => ident,
1899 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
1904 // Lowers a function declaration.
1906 // decl: the unlowered (ast) function declaration.
1907 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1908 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1909 // make_ret_async is also `Some`.
1910 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1911 // This guards against trait declarations and implementations where impl Trait is
1913 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1914 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
1915 // return type impl Trait item.
1919 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
1920 impl_trait_return_allow: bool,
1921 make_ret_async: Option<NodeId>,
1922 ) -> P<hir::FnDecl> {
1923 let inputs = decl.inputs
1926 if let Some((_, ref mut ibty)) = in_band_ty_params {
1927 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
1929 self.lower_ty_direct(&arg.ty, ImplTraitContext::Disallowed)
1932 .collect::<HirVec<_>>();
1934 let output = if let Some(ret_id) = make_ret_async {
1935 self.lower_async_fn_ret_ty(
1938 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
1943 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
1944 Some((def_id, _)) if impl_trait_return_allow => {
1945 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1947 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1949 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1956 variadic: decl.variadic,
1957 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1958 TyKind::ImplicitSelf => true,
1959 TyKind::Rptr(_, ref mt) => mt.ty.node.is_implicit_self(),
1965 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
1967 // fn_span: the span of the async function declaration. Used for error reporting.
1968 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
1969 // output: unlowered output type (`T` in `-> T`)
1970 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
1971 fn lower_async_fn_ret_ty(
1974 output: &FunctionRetTy,
1976 return_impl_trait_id: NodeId,
1977 ) -> hir::FunctionRetTy {
1978 // Get lifetimes used in the input arguments to the function. Our output type must also
1979 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
1980 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
1981 // is a subset of the other. We really want some new lifetime that is a subset of all input
1982 // lifetimes, but that doesn't exist at the moment.
1984 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
1985 context: &'r mut LoweringContext<'a>,
1986 // Lifetimes bound by HRTB
1987 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1988 // Whether to count elided lifetimes.
1989 // Disabled inside of `Fn` or `fn` syntax.
1990 collect_elided_lifetimes: bool,
1991 // The lifetime found.
1992 // Multiple different or elided lifetimes cannot appear in async fn for now.
1993 output_lifetime: Option<(hir::LifetimeName, Span)>,
1996 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
1997 fn nested_visit_map<'this>(
1999 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
2000 hir::intravisit::NestedVisitorMap::None
2003 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
2004 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2005 if parameters.parenthesized {
2006 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2007 self.collect_elided_lifetimes = false;
2008 hir::intravisit::walk_generic_args(self, span, parameters);
2009 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2011 hir::intravisit::walk_generic_args(self, span, parameters);
2015 fn visit_ty(&mut self, t: &'v hir::Ty) {
2016 // Don't collect elided lifetimes used inside of `fn()` syntax
2017 if let &hir::TyKind::BareFn(_) = &t.node {
2018 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2019 self.collect_elided_lifetimes = false;
2021 // Record the "stack height" of `for<'a>` lifetime bindings
2022 // to be able to later fully undo their introduction.
2023 let old_len = self.currently_bound_lifetimes.len();
2024 hir::intravisit::walk_ty(self, t);
2025 self.currently_bound_lifetimes.truncate(old_len);
2027 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2029 hir::intravisit::walk_ty(self, t);
2033 fn visit_poly_trait_ref(
2035 trait_ref: &'v hir::PolyTraitRef,
2036 modifier: hir::TraitBoundModifier,
2038 // Record the "stack height" of `for<'a>` lifetime bindings
2039 // to be able to later fully undo their introduction.
2040 let old_len = self.currently_bound_lifetimes.len();
2041 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2042 self.currently_bound_lifetimes.truncate(old_len);
2045 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2046 // Record the introduction of 'a in `for<'a> ...`
2047 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2048 // Introduce lifetimes one at a time so that we can handle
2049 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2050 let lt_name = hir::LifetimeName::Param(param.name);
2051 self.currently_bound_lifetimes.push(lt_name);
2054 hir::intravisit::walk_generic_param(self, param);
2057 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2058 let name = match lifetime.name {
2059 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2060 if self.collect_elided_lifetimes {
2061 // Use `'_` for both implicit and underscore lifetimes in
2062 // `abstract type Foo<'_>: SomeTrait<'_>;`
2063 hir::LifetimeName::Underscore
2068 hir::LifetimeName::Param(_) => lifetime.name,
2069 hir::LifetimeName::Static => return,
2072 if !self.currently_bound_lifetimes.contains(&name) {
2073 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2074 // We don't currently have a reliable way to desugar `async fn` with
2075 // multiple potentially unrelated input lifetimes into
2076 // `-> impl Trait + 'lt`, so we report an error in this case.
2077 if current_lt_name != name {
2080 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2082 "multiple different lifetimes used in arguments of `async fn`",
2084 .span_label(current_lt_span, "first lifetime here")
2085 .span_label(lifetime.span, "different lifetime here")
2086 .help("`async fn` can only accept borrowed values \
2087 with identical lifetimes")
2089 } else if current_lt_name.is_elided() && name.is_elided() {
2092 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2094 "multiple elided lifetimes used in arguments of `async fn`",
2096 .span_label(current_lt_span, "first lifetime here")
2097 .span_label(lifetime.span, "different lifetime here")
2098 .help("consider giving these arguments named lifetimes")
2102 self.output_lifetime = Some((name, lifetime.span));
2108 let bound_lifetime = {
2109 let mut lifetime_collector = AsyncFnLifetimeCollector {
2111 currently_bound_lifetimes: Vec::new(),
2112 collect_elided_lifetimes: true,
2113 output_lifetime: None,
2117 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2119 lifetime_collector.output_lifetime
2122 let span = match output {
2123 FunctionRetTy::Ty(ty) => ty.span,
2124 FunctionRetTy::Default(span) => *span,
2127 let impl_trait_ty = self.lower_existential_impl_trait(
2128 span, fn_def_id, return_impl_trait_id, |this| {
2129 let output_ty = match output {
2130 FunctionRetTy::Ty(ty) =>
2131 this.lower_ty(ty, ImplTraitContext::Existential(fn_def_id)),
2132 FunctionRetTy::Default(span) => {
2133 let LoweredNodeId { node_id, hir_id } = this.next_id();
2137 node: hir::TyKind::Tup(hir_vec![]),
2144 let future_params = P(hir::GenericArgs {
2146 bindings: hir_vec![hir::TypeBinding {
2147 ident: Ident::from_str(FN_OUTPUT_NAME),
2149 id: this.next_id().node_id,
2152 parenthesized: false,
2156 this.std_path(span, &["future", "Future"], Some(future_params), false);
2158 let LoweredNodeId { node_id, hir_id } = this.next_id();
2159 let mut bounds = vec![
2160 hir::GenericBound::Trait(
2162 trait_ref: hir::TraitRef {
2167 bound_generic_params: hir_vec![],
2170 hir::TraitBoundModifier::None
2174 if let Some((name, span)) = bound_lifetime {
2175 bounds.push(hir::GenericBound::Outlives(
2176 hir::Lifetime { id: this.next_id().node_id, name, span }));
2179 hir::HirVec::from(bounds)
2182 let LoweredNodeId { node_id, hir_id } = self.next_id();
2183 let impl_trait_ty = P(hir::Ty {
2185 node: impl_trait_ty,
2190 hir::FunctionRetTy::Return(impl_trait_ty)
2193 fn lower_param_bound(
2196 itctx: ImplTraitContext,
2197 ) -> hir::GenericBound {
2199 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2200 self.lower_poly_trait_ref(ty, itctx),
2201 self.lower_trait_bound_modifier(modifier),
2203 GenericBound::Outlives(ref lifetime) => {
2204 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2209 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2210 let span = l.ident.span;
2212 ident if ident.name == keywords::StaticLifetime.name() =>
2213 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2214 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2215 match self.anonymous_lifetime_mode {
2216 AnonymousLifetimeMode::CreateParameter => {
2217 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2218 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2221 AnonymousLifetimeMode::PassThrough => {
2222 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2226 self.maybe_collect_in_band_lifetime(ident);
2227 let param_name = ParamName::Plain(ident);
2228 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2233 fn new_named_lifetime(
2237 name: hir::LifetimeName,
2238 ) -> hir::Lifetime {
2240 id: self.lower_node_id(id).node_id,
2246 fn lower_generic_params(
2248 params: &[GenericParam],
2249 add_bounds: &NodeMap<Vec<GenericBound>>,
2250 mut itctx: ImplTraitContext,
2251 ) -> hir::HirVec<hir::GenericParam> {
2252 params.iter().map(|param| {
2253 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2257 fn lower_generic_param(&mut self,
2258 param: &GenericParam,
2259 add_bounds: &NodeMap<Vec<GenericBound>>,
2260 mut itctx: ImplTraitContext)
2261 -> hir::GenericParam {
2262 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx.reborrow());
2264 GenericParamKind::Lifetime => {
2265 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2266 self.is_collecting_in_band_lifetimes = false;
2268 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
2269 let param_name = match lt.name {
2270 hir::LifetimeName::Param(param_name) => param_name,
2271 _ => hir::ParamName::Plain(lt.name.ident()),
2273 let param = hir::GenericParam {
2277 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2278 attrs: self.lower_attrs(¶m.attrs),
2280 kind: hir::GenericParamKind::Lifetime { in_band: false }
2283 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2287 GenericParamKind::Type { ref default, .. } => {
2288 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2289 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2290 // Instead, use gensym("Self") to create a distinct name that looks the same.
2291 let ident = if param.ident.name == keywords::SelfType.name() {
2292 param.ident.gensym()
2297 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2298 if !add_bounds.is_empty() {
2299 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2300 bounds = bounds.into_iter()
2306 id: self.lower_node_id(param.id).node_id,
2307 name: hir::ParamName::Plain(ident),
2308 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2309 attrs: self.lower_attrs(¶m.attrs),
2312 kind: hir::GenericParamKind::Type {
2313 default: default.as_ref().map(|x| {
2314 self.lower_ty(x, ImplTraitContext::Disallowed)
2316 synthetic: param.attrs.iter()
2317 .filter(|attr| attr.check_name("rustc_synthetic"))
2318 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2328 generics: &Generics,
2329 itctx: ImplTraitContext)
2332 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2333 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2334 // paths where report_error is called are also the only paths that advance to after
2335 // the match statement, so the error reporting could probably just be moved there.
2336 let mut add_bounds = NodeMap();
2337 for pred in &generics.where_clause.predicates {
2338 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2339 'next_bound: for bound in &bound_pred.bounds {
2340 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2341 let report_error = |this: &mut Self| {
2342 this.diagnostic().span_err(
2343 bound_pred.bounded_ty.span,
2344 "`?Trait` bounds are only permitted at the \
2345 point where a type parameter is declared",
2348 // Check if the where clause type is a plain type parameter.
2349 match bound_pred.bounded_ty.node {
2350 TyKind::Path(None, ref path)
2351 if path.segments.len() == 1
2352 && bound_pred.bound_generic_params.is_empty() =>
2354 if let Some(Def::TyParam(def_id)) = self.resolver
2355 .get_resolution(bound_pred.bounded_ty.id)
2356 .map(|d| d.base_def())
2358 if let Some(node_id) =
2359 self.resolver.definitions().as_local_node_id(def_id)
2361 for param in &generics.params {
2363 GenericParamKind::Type { .. } => {
2364 if node_id == param.id {
2365 add_bounds.entry(param.id)
2366 .or_insert(Vec::new())
2367 .push(bound.clone());
2368 continue 'next_bound;
2378 _ => report_error(self),
2386 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2387 where_clause: self.lower_where_clause(&generics.where_clause),
2388 span: generics.span,
2392 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2394 id: self.lower_node_id(wc.id).node_id,
2395 predicates: wc.predicates
2397 .map(|predicate| self.lower_where_predicate(predicate))
2402 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2404 WherePredicate::BoundPredicate(WhereBoundPredicate {
2405 ref bound_generic_params,
2410 self.with_in_scope_lifetime_defs(
2411 &bound_generic_params,
2413 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2414 bound_generic_params: this.lower_generic_params(
2415 bound_generic_params,
2417 ImplTraitContext::Disallowed,
2419 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2422 .filter_map(|bound| match *bound {
2423 // Ignore `?Trait` bounds.
2424 // Tthey were copied into type parameters already.
2425 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2426 _ => Some(this.lower_param_bound(
2428 ImplTraitContext::Disallowed,
2437 WherePredicate::RegionPredicate(WhereRegionPredicate {
2441 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2443 lifetime: self.lower_lifetime(lifetime),
2444 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2446 WherePredicate::EqPredicate(WhereEqPredicate {
2451 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2452 id: self.lower_node_id(id).node_id,
2453 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2454 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2460 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2462 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2466 .map(|f| self.lower_struct_field(f))
2468 self.lower_node_id(id).node_id,
2470 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2474 .map(|f| self.lower_struct_field(f))
2476 self.lower_node_id(id).node_id,
2478 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2482 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2483 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2484 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2485 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2487 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.ref_id);
2495 fn lower_poly_trait_ref(
2498 mut itctx: ImplTraitContext,
2499 ) -> hir::PolyTraitRef {
2500 let bound_generic_params =
2501 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx.reborrow());
2502 let trait_ref = self.with_parent_impl_lifetime_defs(
2503 &bound_generic_params,
2504 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2508 bound_generic_params,
2514 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2517 id: self.lower_node_id(f.id).node_id,
2518 ident: match f.ident {
2519 Some(ident) => ident,
2520 // FIXME(jseyfried) positional field hygiene
2521 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2523 vis: self.lower_visibility(&f.vis, None),
2524 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2525 attrs: self.lower_attrs(&f.attrs),
2529 fn lower_field(&mut self, f: &Field) -> hir::Field {
2531 id: self.next_id().node_id,
2533 expr: P(self.lower_expr(&f.expr)),
2535 is_shorthand: f.is_shorthand,
2539 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2541 ty: self.lower_ty(&mt.ty, itctx),
2542 mutbl: self.lower_mutability(mt.mutbl),
2546 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext)
2547 -> hir::GenericBounds {
2548 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2551 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2552 let mut expr = None;
2554 let mut stmts = vec![];
2556 for (index, stmt) in b.stmts.iter().enumerate() {
2557 if index == b.stmts.len() - 1 {
2558 if let StmtKind::Expr(ref e) = stmt.node {
2559 expr = Some(P(self.lower_expr(e)));
2561 stmts.extend(self.lower_stmt(stmt));
2564 stmts.extend(self.lower_stmt(stmt));
2568 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2573 stmts: stmts.into(),
2575 rules: self.lower_block_check_mode(&b.rules),
2578 recovered: b.recovered,
2582 fn lower_async_body(
2588 self.lower_body(Some(decl), |this| {
2589 if let IsAsync::Async { closure_id, .. } = asyncness {
2590 let async_expr = this.make_async_expr(
2591 CaptureBy::Value, closure_id, None,
2593 let body = this.lower_block(body, false);
2594 this.expr_block(body, ThinVec::new())
2596 this.expr(body.span, async_expr, ThinVec::new())
2598 let body = this.lower_block(body, false);
2599 this.expr_block(body, ThinVec::new())
2608 attrs: &hir::HirVec<Attribute>,
2609 vis: &mut hir::Visibility,
2611 ) -> hir::ItemKind {
2613 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2614 ItemKind::Use(ref use_tree) => {
2615 // Start with an empty prefix
2618 span: use_tree.span,
2621 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2623 ItemKind::Static(ref t, m, ref e) => {
2624 let value = self.lower_body(None, |this| this.lower_expr(e));
2625 hir::ItemKind::Static(
2626 self.lower_ty(t, ImplTraitContext::Disallowed),
2627 self.lower_mutability(m),
2631 ItemKind::Const(ref t, ref e) => {
2632 let value = self.lower_body(None, |this| this.lower_expr(e));
2633 hir::ItemKind::Const(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2635 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2636 let fn_def_id = self.resolver.definitions().local_def_id(id);
2638 self.with_new_scopes(|this| {
2639 // Note: we don't need to change the return type from `T` to
2640 // `impl Future<Output = T>` here because lower_body
2641 // only cares about the input argument patterns in the function
2642 // declaration (decl), not the return types.
2643 let body_id = this.lower_async_body(decl, header.asyncness, body);
2645 let (generics, fn_decl) = this.add_in_band_defs(
2648 AnonymousLifetimeMode::PassThrough,
2649 |this, idty| this.lower_fn_decl(
2650 decl, Some((fn_def_id, idty)), true, header.asyncness.opt_return_id()),
2655 this.lower_fn_header(header),
2661 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2662 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2663 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2664 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2665 self.lower_ty(t, ImplTraitContext::Disallowed),
2666 self.lower_generics(generics, ImplTraitContext::Disallowed),
2668 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2669 generics: self.lower_generics(generics, ImplTraitContext::Disallowed),
2670 bounds: self.lower_param_bounds(b, ImplTraitContext::Disallowed),
2671 impl_trait_fn: None,
2673 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2675 variants: enum_definition
2678 .map(|x| self.lower_variant(x))
2681 self.lower_generics(generics, ImplTraitContext::Disallowed),
2683 ItemKind::Struct(ref struct_def, ref generics) => {
2684 let struct_def = self.lower_variant_data(struct_def);
2685 hir::ItemKind::Struct(
2687 self.lower_generics(generics, ImplTraitContext::Disallowed),
2690 ItemKind::Union(ref vdata, ref generics) => {
2691 let vdata = self.lower_variant_data(vdata);
2692 hir::ItemKind::Union(
2694 self.lower_generics(generics, ImplTraitContext::Disallowed),
2706 let def_id = self.resolver.definitions().local_def_id(id);
2708 // Lower the "impl header" first. This ordering is important
2709 // for in-band lifetimes! Consider `'a` here:
2711 // impl Foo<'a> for u32 {
2712 // fn method(&'a self) { .. }
2715 // Because we start by lowering the `Foo<'a> for u32`
2716 // part, we will add `'a` to the list of generics on
2717 // the impl. When we then encounter it later in the
2718 // method, it will not be considered an in-band
2719 // lifetime to be added, but rather a reference to a
2721 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2724 AnonymousLifetimeMode::CreateParameter,
2726 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2727 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2730 if let Some(ref trait_ref) = trait_ref {
2731 if let Def::Trait(def_id) = trait_ref.path.def {
2732 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2736 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2738 (trait_ref, lowered_ty)
2742 let new_impl_items = self.with_in_scope_lifetime_defs(
2743 &ast_generics.params,
2747 .map(|item| this.lower_impl_item_ref(item))
2752 hir::ItemKind::Impl(
2753 self.lower_unsafety(unsafety),
2754 self.lower_impl_polarity(polarity),
2755 self.lower_defaultness(defaultness, true /* [1] */),
2762 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2763 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2766 .map(|item| self.lower_trait_item_ref(item))
2768 hir::ItemKind::Trait(
2769 self.lower_is_auto(is_auto),
2770 self.lower_unsafety(unsafety),
2771 self.lower_generics(generics, ImplTraitContext::Disallowed),
2776 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
2777 self.lower_generics(generics, ImplTraitContext::Disallowed),
2778 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2780 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2783 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2784 // not cause an assertion failure inside the `lower_defaultness` function
2792 vis: &mut hir::Visibility,
2794 attrs: &hir::HirVec<Attribute>,
2795 ) -> hir::ItemKind {
2796 let path = &tree.prefix;
2799 UseTreeKind::Simple(rename, id1, id2) => {
2800 *name = tree.ident().name;
2802 // First apply the prefix to the path
2803 let mut path = Path {
2807 .chain(path.segments.iter())
2813 // Correctly resolve `self` imports
2814 if path.segments.len() > 1
2815 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2817 let _ = path.segments.pop();
2818 if rename.is_none() {
2819 *name = path.segments.last().unwrap().ident.name;
2823 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2824 let mut defs = self.expect_full_def_from_use(id);
2825 // we want to return *something* from this function, so hang onto the first item
2827 let ret_def = defs.next().unwrap_or(Def::Err);
2829 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2830 let vis = vis.clone();
2831 let name = name.clone();
2832 let span = path.span;
2833 self.resolver.definitions().create_def_with_parent(
2837 DefIndexAddressSpace::High,
2840 self.allocate_hir_id_counter(new_node_id, &path);
2842 self.with_hir_id_owner(new_node_id, |this| {
2843 let new_id = this.lower_node_id(new_node_id);
2844 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2845 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
2846 let vis_kind = match vis.node {
2847 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2848 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2849 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2850 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
2851 let id = this.next_id();
2852 hir::VisibilityKind::Restricted {
2854 // We are allocating a new NodeId here
2860 let vis = respan(vis.span, vis_kind);
2866 hir_id: new_id.hir_id,
2868 attrs: attrs.clone(),
2877 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2878 hir::ItemKind::Use(path, hir::UseKind::Single)
2880 UseTreeKind::Glob => {
2881 let path = P(self.lower_path(
2887 .chain(path.segments.iter())
2892 ParamMode::Explicit,
2894 hir::ItemKind::Use(path, hir::UseKind::Glob)
2896 UseTreeKind::Nested(ref trees) => {
2901 .chain(path.segments.iter())
2904 span: prefix.span.to(path.span),
2907 // Add all the nested PathListItems in the HIR
2908 for &(ref use_tree, id) in trees {
2909 self.allocate_hir_id_counter(id, &use_tree);
2913 } = self.lower_node_id(id);
2915 let mut vis = vis.clone();
2916 let mut name = name.clone();
2918 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2920 self.with_hir_id_owner(new_id, |this| {
2921 let vis_kind = match vis.node {
2922 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2923 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2924 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2925 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
2926 let id = this.next_id();
2927 hir::VisibilityKind::Restricted {
2929 // We are allocating a new NodeId here
2935 let vis = respan(vis.span, vis_kind);
2943 attrs: attrs.clone(),
2946 span: use_tree.span,
2952 // Privatize the degenerate import base, used only to check
2953 // the stability of `use a::{};`, to avoid it showing up as
2954 // a re-export by accident when `pub`, e.g. in documentation.
2955 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2956 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
2957 hir::ItemKind::Use(path, hir::UseKind::ListStem)
2962 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2963 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2964 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2966 let (generics, node) = match i.node {
2967 TraitItemKind::Const(ref ty, ref default) => (
2968 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2969 hir::TraitItemKind::Const(
2970 self.lower_ty(ty, ImplTraitContext::Disallowed),
2973 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2976 TraitItemKind::Method(ref sig, None) => {
2977 let names = self.lower_fn_args_to_names(&sig.decl);
2978 let (generics, sig) = self.lower_method_sig(
2985 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
2987 TraitItemKind::Method(ref sig, Some(ref body)) => {
2988 let body_id = self.lower_body(Some(&sig.decl), |this| {
2989 let body = this.lower_block(body, false);
2990 this.expr_block(body, ThinVec::new())
2993 let (generics, sig) = self.lower_method_sig(
3001 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3003 TraitItemKind::Type(ref bounds, ref default) => (
3004 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3005 hir::TraitItemKind::Type(
3006 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3009 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
3012 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3019 attrs: self.lower_attrs(&i.attrs),
3026 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3027 let (kind, has_default) = match i.node {
3028 TraitItemKind::Const(_, ref default) => {
3029 (hir::AssociatedItemKind::Const, default.is_some())
3031 TraitItemKind::Type(_, ref default) => {
3032 (hir::AssociatedItemKind::Type, default.is_some())
3034 TraitItemKind::Method(ref sig, ref default) => (
3035 hir::AssociatedItemKind::Method {
3036 has_self: sig.decl.has_self(),
3040 TraitItemKind::Macro(..) => unimplemented!(),
3043 id: hir::TraitItemId { node_id: i.id },
3046 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3051 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3052 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3053 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3055 let (generics, node) = match i.node {
3056 ImplItemKind::Const(ref ty, ref expr) => {
3057 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3059 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3060 hir::ImplItemKind::Const(
3061 self.lower_ty(ty, ImplTraitContext::Disallowed),
3066 ImplItemKind::Method(ref sig, ref body) => {
3067 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3068 let impl_trait_return_allow = !self.is_in_trait_impl;
3069 let (generics, sig) = self.lower_method_sig(
3073 impl_trait_return_allow,
3074 sig.header.asyncness.opt_return_id(),
3076 (generics, hir::ImplItemKind::Method(sig, body_id))
3078 ImplItemKind::Type(ref ty) => (
3079 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3080 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
3082 ImplItemKind::Existential(ref bounds) => (
3083 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3084 hir::ImplItemKind::Existential(
3085 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3088 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3095 attrs: self.lower_attrs(&i.attrs),
3097 vis: self.lower_visibility(&i.vis, None),
3098 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3103 // [1] since `default impl` is not yet implemented, this is always true in impls
3106 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3108 id: hir::ImplItemId { node_id: i.id },
3111 vis: self.lower_visibility(&i.vis, Some(i.id)),
3112 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3113 kind: match i.node {
3114 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3115 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3116 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3117 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3118 has_self: sig.decl.has_self(),
3120 ImplItemKind::Macro(..) => unimplemented!(),
3124 // [1] since `default impl` is not yet implemented, this is always true in impls
3127 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3130 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3134 /// Lowers `impl Trait` items and appends them to the list
3135 fn lower_impl_trait_ids(
3139 ids: &mut SmallVector<hir::ItemId>,
3141 if let Some(id) = header.asyncness.opt_return_id() {
3142 ids.push(hir::ItemId { id });
3144 struct IdVisitor<'a> { ids: &'a mut SmallVector<hir::ItemId> }
3145 impl<'a, 'b> Visitor<'a> for IdVisitor<'b> {
3146 fn visit_ty(&mut self, ty: &'a Ty) {
3152 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
3155 visit::walk_ty(self, ty);
3157 fn visit_path_segment(
3160 path_segment: &'v PathSegment,
3162 if let Some(ref p) = path_segment.args {
3163 if let GenericArgs::Parenthesized(_) = **p {
3167 visit::walk_path_segment(self, path_span, path_segment)
3170 let mut visitor = IdVisitor { ids };
3172 FunctionRetTy::Default(_) => {},
3173 FunctionRetTy::Ty(ref ty) => visitor.visit_ty(ty),
3177 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
3179 ItemKind::Use(ref use_tree) => {
3180 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
3181 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3184 ItemKind::MacroDef(..) => SmallVector::new(),
3185 ItemKind::Fn(ref decl, ref header, ..) => {
3186 let mut ids = SmallVector::one(hir::ItemId { id: i.id });
3187 self.lower_impl_trait_ids(decl, header, &mut ids);
3190 ItemKind::Impl(.., None, _, ref items) => {
3191 let mut ids = SmallVector::one(hir::ItemId { id: i.id });
3193 if let ImplItemKind::Method(ref sig, _) = item.node {
3194 self.lower_impl_trait_ids(&sig.decl, &sig.header, &mut ids);
3199 _ => SmallVector::one(hir::ItemId { id: i.id }),
3203 fn lower_item_id_use_tree(&mut self,
3206 vec: &mut SmallVector<hir::ItemId>)
3209 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3210 vec.push(hir::ItemId { id });
3211 self.lower_item_id_use_tree(nested, id, vec);
3213 UseTreeKind::Glob => {}
3214 UseTreeKind::Simple(_, id1, id2) => {
3215 for (_, &id) in self.expect_full_def_from_use(base_id)
3217 .zip([id1, id2].iter())
3219 vec.push(hir::ItemId { id });
3225 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3226 let mut name = i.ident.name;
3227 let mut vis = self.lower_visibility(&i.vis, None);
3228 let attrs = self.lower_attrs(&i.attrs);
3229 if let ItemKind::MacroDef(ref def) = i.node {
3230 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3231 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3232 let body = self.lower_token_stream(def.stream());
3233 self.exported_macros.push(hir::MacroDef {
3246 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3248 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3261 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3262 let node_id = self.lower_node_id(i.id).node_id;
3263 let def_id = self.resolver.definitions().local_def_id(node_id);
3267 attrs: self.lower_attrs(&i.attrs),
3268 node: match i.node {
3269 ForeignItemKind::Fn(ref fdec, ref generics) => {
3270 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3273 AnonymousLifetimeMode::PassThrough,
3276 // Disallow impl Trait in foreign items
3277 this.lower_fn_decl(fdec, None, false, None),
3278 this.lower_fn_args_to_names(fdec),
3283 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3285 ForeignItemKind::Static(ref t, m) => {
3286 hir::ForeignItemKind::Static(self.lower_ty(t, ImplTraitContext::Disallowed), m)
3288 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3289 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3291 vis: self.lower_visibility(&i.vis, None),
3296 fn lower_method_sig(
3298 generics: &Generics,
3301 impl_trait_return_allow: bool,
3302 is_async: Option<NodeId>,
3303 ) -> (hir::Generics, hir::MethodSig) {
3304 let header = self.lower_fn_header(sig.header);
3305 let (generics, decl) = self.add_in_band_defs(
3308 AnonymousLifetimeMode::PassThrough,
3309 |this, idty| this.lower_fn_decl(
3311 Some((fn_def_id, idty)),
3312 impl_trait_return_allow,
3316 (generics, hir::MethodSig { header, decl })
3319 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3321 IsAuto::Yes => hir::IsAuto::Yes,
3322 IsAuto::No => hir::IsAuto::No,
3326 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3328 unsafety: self.lower_unsafety(h.unsafety),
3329 asyncness: self.lower_asyncness(h.asyncness),
3330 constness: self.lower_constness(h.constness),
3335 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3337 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3338 Unsafety::Normal => hir::Unsafety::Normal,
3342 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3344 Constness::Const => hir::Constness::Const,
3345 Constness::NotConst => hir::Constness::NotConst,
3349 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3351 IsAsync::Async { .. } => hir::IsAsync::Async,
3352 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3356 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3358 UnOp::Deref => hir::UnDeref,
3359 UnOp::Not => hir::UnNot,
3360 UnOp::Neg => hir::UnNeg,
3364 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3366 node: match b.node {
3367 BinOpKind::Add => hir::BinOpKind::Add,
3368 BinOpKind::Sub => hir::BinOpKind::Sub,
3369 BinOpKind::Mul => hir::BinOpKind::Mul,
3370 BinOpKind::Div => hir::BinOpKind::Div,
3371 BinOpKind::Rem => hir::BinOpKind::Rem,
3372 BinOpKind::And => hir::BinOpKind::And,
3373 BinOpKind::Or => hir::BinOpKind::Or,
3374 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3375 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3376 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3377 BinOpKind::Shl => hir::BinOpKind::Shl,
3378 BinOpKind::Shr => hir::BinOpKind::Shr,
3379 BinOpKind::Eq => hir::BinOpKind::Eq,
3380 BinOpKind::Lt => hir::BinOpKind::Lt,
3381 BinOpKind::Le => hir::BinOpKind::Le,
3382 BinOpKind::Ne => hir::BinOpKind::Ne,
3383 BinOpKind::Ge => hir::BinOpKind::Ge,
3384 BinOpKind::Gt => hir::BinOpKind::Gt,
3390 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3391 let node = match p.node {
3392 PatKind::Wild => hir::PatKind::Wild,
3393 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3394 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3395 // `None` can occur in body-less function signatures
3396 def @ None | def @ Some(Def::Local(_)) => {
3397 let canonical_id = match def {
3398 Some(Def::Local(id)) => id,
3401 hir::PatKind::Binding(
3402 self.lower_binding_mode(binding_mode),
3405 sub.as_ref().map(|x| self.lower_pat(x)),
3408 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3413 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3418 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3419 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3420 let qpath = self.lower_qpath(
3424 ParamMode::Optional,
3425 ImplTraitContext::Disallowed,
3427 hir::PatKind::TupleStruct(
3429 pats.iter().map(|x| self.lower_pat(x)).collect(),
3433 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3437 ParamMode::Optional,
3438 ImplTraitContext::Disallowed,
3440 PatKind::Struct(ref path, ref fields, etc) => {
3441 let qpath = self.lower_qpath(
3445 ParamMode::Optional,
3446 ImplTraitContext::Disallowed,
3453 node: hir::FieldPat {
3454 id: self.next_id().node_id,
3455 ident: f.node.ident,
3456 pat: self.lower_pat(&f.node.pat),
3457 is_shorthand: f.node.is_shorthand,
3461 hir::PatKind::Struct(qpath, fs, etc)
3463 PatKind::Tuple(ref elts, ddpos) => {
3464 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3466 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3467 PatKind::Ref(ref inner, mutbl) => {
3468 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3470 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3471 P(self.lower_expr(e1)),
3472 P(self.lower_expr(e2)),
3473 self.lower_range_end(end),
3475 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3476 before.iter().map(|x| self.lower_pat(x)).collect(),
3477 slice.as_ref().map(|x| self.lower_pat(x)),
3478 after.iter().map(|x| self.lower_pat(x)).collect(),
3480 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3481 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3484 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3493 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3495 RangeEnd::Included(_) => hir::RangeEnd::Included,
3496 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3500 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3501 self.with_new_scopes(|this| {
3502 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3506 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3511 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3512 let kind = match e.node {
3513 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3514 ExprKind::ObsoleteInPlace(..) => {
3515 self.sess.abort_if_errors();
3516 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3518 ExprKind::Array(ref exprs) => {
3519 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3521 ExprKind::Repeat(ref expr, ref count) => {
3522 let expr = P(self.lower_expr(expr));
3523 let count = self.lower_anon_const(count);
3524 hir::ExprKind::Repeat(expr, count)
3526 ExprKind::Tup(ref elts) => {
3527 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3529 ExprKind::Call(ref f, ref args) => {
3530 let f = P(self.lower_expr(f));
3531 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3533 ExprKind::MethodCall(ref seg, ref args) => {
3534 let hir_seg = self.lower_path_segment(
3537 ParamMode::Optional,
3539 ParenthesizedGenericArgs::Err,
3540 ImplTraitContext::Disallowed,
3542 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3543 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3545 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3546 let binop = self.lower_binop(binop);
3547 let lhs = P(self.lower_expr(lhs));
3548 let rhs = P(self.lower_expr(rhs));
3549 hir::ExprKind::Binary(binop, lhs, rhs)
3551 ExprKind::Unary(op, ref ohs) => {
3552 let op = self.lower_unop(op);
3553 let ohs = P(self.lower_expr(ohs));
3554 hir::ExprKind::Unary(op, ohs)
3556 ExprKind::Lit(ref l) => hir::ExprKind::Lit(P((**l).clone())),
3557 ExprKind::Cast(ref expr, ref ty) => {
3558 let expr = P(self.lower_expr(expr));
3559 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3561 ExprKind::Type(ref expr, ref ty) => {
3562 let expr = P(self.lower_expr(expr));
3563 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3565 ExprKind::AddrOf(m, ref ohs) => {
3566 let m = self.lower_mutability(m);
3567 let ohs = P(self.lower_expr(ohs));
3568 hir::ExprKind::AddrOf(m, ohs)
3570 // More complicated than you might expect because the else branch
3571 // might be `if let`.
3572 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3573 let else_opt = else_opt.as_ref().map(|els| {
3575 ExprKind::IfLet(..) => {
3576 // wrap the if-let expr in a block
3577 let span = els.span;
3578 let els = P(self.lower_expr(els));
3579 let LoweredNodeId { node_id, hir_id } = self.next_id();
3580 let blk = P(hir::Block {
3585 rules: hir::DefaultBlock,
3587 targeted_by_break: false,
3588 recovered: blk.recovered,
3590 P(self.expr_block(blk, ThinVec::new()))
3592 _ => P(self.lower_expr(els)),
3596 let then_blk = self.lower_block(blk, false);
3597 let then_expr = self.expr_block(then_blk, ThinVec::new());
3599 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3601 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3602 hir::ExprKind::While(
3603 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3604 this.lower_block(body, false),
3605 this.lower_label(opt_label),
3608 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3609 hir::ExprKind::Loop(
3610 this.lower_block(body, false),
3611 this.lower_label(opt_label),
3612 hir::LoopSource::Loop,
3615 ExprKind::Catch(ref body) => {
3616 self.with_catch_scope(body.id, |this| {
3618 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3619 let mut block = this.lower_block(body, true).into_inner();
3620 let tail = block.expr.take().map_or_else(
3622 let LoweredNodeId { node_id, hir_id } = this.next_id();
3623 let span = this.sess.codemap().end_point(unstable_span);
3627 node: hir::ExprKind::Tup(hir_vec![]),
3628 attrs: ThinVec::new(),
3632 |x: P<hir::Expr>| x.into_inner(),
3634 block.expr = Some(this.wrap_in_try_constructor(
3635 "from_ok", tail, unstable_span));
3636 hir::ExprKind::Block(P(block), None)
3639 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3640 P(self.lower_expr(expr)),
3641 arms.iter().map(|x| self.lower_arm(x)).collect(),
3642 hir::MatchSource::Normal,
3644 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3645 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3646 this.with_new_scopes(|this| {
3647 let block = this.lower_block(block, false);
3648 this.expr_block(block, ThinVec::new())
3653 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3655 if let IsAsync::Async { closure_id, .. } = asyncness {
3656 let outer_decl = FnDecl {
3657 inputs: decl.inputs.clone(),
3658 output: FunctionRetTy::Default(fn_decl_span),
3661 // We need to lower the declaration outside the new scope, because we
3662 // have to conserve the state of being inside a loop condition for the
3663 // closure argument types.
3664 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3666 self.with_new_scopes(|this| {
3667 // FIXME(cramertj) allow `async` non-`move` closures with
3668 if capture_clause == CaptureBy::Ref &&
3669 !decl.inputs.is_empty()
3675 "`async` non-`move` closures with arguments \
3676 are not currently supported",
3678 .help("consider using `let` statements to manually capture \
3679 variables by reference before entering an \
3680 `async move` closure")
3684 // Transform `async |x: u8| -> X { ... }` into
3685 // `|x: u8| future_from_generator(|| -> X { ... })`
3686 let body_id = this.lower_body(Some(&outer_decl), |this| {
3687 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3690 let async_body = this.make_async_expr(
3691 capture_clause, closure_id, async_ret_ty,
3693 this.with_new_scopes(|this| this.lower_expr(body))
3695 this.expr(fn_decl_span, async_body, ThinVec::new())
3697 hir::ExprKind::Closure(
3698 this.lower_capture_clause(capture_clause),
3706 // Lower outside new scope to preserve `is_in_loop_condition`.
3707 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3709 self.with_new_scopes(|this| {
3710 let mut is_generator = false;
3711 let body_id = this.lower_body(Some(decl), |this| {
3712 let e = this.lower_expr(body);
3713 is_generator = this.is_generator;
3716 let generator_option = if is_generator {
3717 if !decl.inputs.is_empty() {
3722 "generators cannot have explicit arguments"
3724 this.sess.abort_if_errors();
3726 Some(match movability {
3727 Movability::Movable => hir::GeneratorMovability::Movable,
3728 Movability::Static => hir::GeneratorMovability::Static,
3731 if movability == Movability::Static {
3736 "closures cannot be static"
3741 hir::ExprKind::Closure(
3742 this.lower_capture_clause(capture_clause),
3751 ExprKind::Block(ref blk, opt_label) => {
3752 hir::ExprKind::Block(self.lower_block(blk,
3753 opt_label.is_some()),
3754 self.lower_label(opt_label))
3756 ExprKind::Assign(ref el, ref er) => {
3757 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3759 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
3760 self.lower_binop(op),
3761 P(self.lower_expr(el)),
3762 P(self.lower_expr(er)),
3764 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
3765 ExprKind::Index(ref el, ref er) => {
3766 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
3768 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3769 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3770 let id = self.next_id();
3771 let e1 = self.lower_expr(e1);
3772 let e2 = self.lower_expr(e2);
3773 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
3774 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
3775 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3776 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3777 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
3778 hir::ExprKind::Call(new, hir_vec![e1, e2])
3780 ExprKind::Range(ref e1, ref e2, lims) => {
3781 use syntax::ast::RangeLimits::*;
3783 let path = match (e1, e2, lims) {
3784 (&None, &None, HalfOpen) => "RangeFull",
3785 (&Some(..), &None, HalfOpen) => "RangeFrom",
3786 (&None, &Some(..), HalfOpen) => "RangeTo",
3787 (&Some(..), &Some(..), HalfOpen) => "Range",
3788 (&None, &Some(..), Closed) => "RangeToInclusive",
3789 (&Some(..), &Some(..), Closed) => unreachable!(),
3790 (_, &None, Closed) => self.diagnostic()
3791 .span_fatal(e.span, "inclusive range with no end")
3795 let fields = e1.iter()
3796 .map(|e| ("start", e))
3797 .chain(e2.iter().map(|e| ("end", e)))
3799 let expr = P(self.lower_expr(&e));
3800 let ident = Ident::new(Symbol::intern(s), e.span);
3801 self.field(ident, expr, e.span)
3803 .collect::<P<[hir::Field]>>();
3805 let is_unit = fields.is_empty();
3806 let struct_path = iter::once("ops")
3807 .chain(iter::once(path))
3808 .collect::<Vec<_>>();
3809 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
3810 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3812 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3818 hir::ExprKind::Path(struct_path)
3820 hir::ExprKind::Struct(struct_path, fields, None)
3823 attrs: e.attrs.clone(),
3826 ExprKind::Path(ref qself, ref path) => hir::ExprKind::Path(self.lower_qpath(
3830 ParamMode::Optional,
3831 ImplTraitContext::Disallowed,
3833 ExprKind::Break(opt_label, ref opt_expr) => {
3834 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3837 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3840 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3842 hir::ExprKind::Break(
3844 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3847 ExprKind::Continue(opt_label) => {
3848 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
3851 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3854 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3857 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
3858 ExprKind::InlineAsm(ref asm) => {
3859 let hir_asm = hir::InlineAsm {
3860 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3861 outputs: asm.outputs
3863 .map(|out| hir::InlineAsmOutput {
3864 constraint: out.constraint.clone(),
3866 is_indirect: out.is_indirect,
3869 asm: asm.asm.clone(),
3870 asm_str_style: asm.asm_str_style,
3871 clobbers: asm.clobbers.clone().into(),
3872 volatile: asm.volatile,
3873 alignstack: asm.alignstack,
3874 dialect: asm.dialect,
3877 let outputs = asm.outputs
3879 .map(|out| self.lower_expr(&out.expr))
3881 let inputs = asm.inputs
3883 .map(|&(_, ref input)| self.lower_expr(input))
3885 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
3887 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
3892 ParamMode::Optional,
3893 ImplTraitContext::Disallowed,
3895 fields.iter().map(|x| self.lower_field(x)).collect(),
3896 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3898 ExprKind::Paren(ref ex) => {
3899 let mut ex = self.lower_expr(ex);
3900 // include parens in span, but only if it is a super-span.
3901 if e.span.contains(ex.span) {
3904 // merge attributes into the inner expression.
3905 let mut attrs = e.attrs.clone();
3906 attrs.extend::<Vec<_>>(ex.attrs.into());
3911 ExprKind::Yield(ref opt_expr) => {
3912 self.is_generator = true;
3915 .map(|x| self.lower_expr(x))
3917 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
3919 hir::ExprKind::Yield(P(expr))
3922 // Desugar ExprIfLet
3923 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3924 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3927 // match <sub_expr> {
3929 // _ => [<else_opt> | ()]
3932 let mut arms = vec![];
3934 // `<pat> => <body>`
3936 let body = self.lower_block(body, false);
3937 let body_expr = P(self.expr_block(body, ThinVec::new()));
3938 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3939 arms.push(self.arm(pats, body_expr));
3942 // _ => [<else_opt>|()]
3944 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3945 let wildcard_pattern = self.pat_wild(e.span);
3946 let body = if let Some(else_expr) = wildcard_arm {
3947 P(self.lower_expr(else_expr))
3949 self.expr_tuple(e.span, hir_vec![])
3951 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3954 let contains_else_clause = else_opt.is_some();
3956 let sub_expr = P(self.lower_expr(sub_expr));
3958 hir::ExprKind::Match(
3961 hir::MatchSource::IfLetDesugar {
3962 contains_else_clause,
3967 // Desugar ExprWhileLet
3968 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3969 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3972 // [opt_ident]: loop {
3973 // match <sub_expr> {
3979 // Note that the block AND the condition are evaluated in the loop scope.
3980 // This is done to allow `break` from inside the condition of the loop.
3981 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3983 this.lower_block(body, false),
3984 this.expr_break(e.span, ThinVec::new()),
3985 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3989 // `<pat> => <body>`
3991 let body_expr = P(self.expr_block(body, ThinVec::new()));
3992 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3993 self.arm(pats, body_expr)
3998 let pat_under = self.pat_wild(e.span);
3999 self.arm(hir_vec![pat_under], break_expr)
4002 // `match <sub_expr> { ... }`
4003 let arms = hir_vec![pat_arm, break_arm];
4004 let match_expr = self.expr(
4006 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4010 // `[opt_ident]: loop { ... }`
4011 let loop_block = P(self.block_expr(P(match_expr)));
4012 let loop_expr = hir::ExprKind::Loop(
4014 self.lower_label(opt_label),
4015 hir::LoopSource::WhileLet,
4017 // add attributes to the outer returned expr node
4021 // Desugar ExprForLoop
4022 // From: `[opt_ident]: for <pat> in <head> <body>`
4023 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4027 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4029 // [opt_ident]: loop {
4031 // match ::std::iter::Iterator::next(&mut iter) {
4032 // ::std::option::Option::Some(val) => __next = val,
4033 // ::std::option::Option::None => break
4035 // let <pat> = __next;
4036 // StmtKind::Expr(<body>);
4044 let head = self.lower_expr(head);
4045 let head_sp = head.span;
4047 let iter = self.str_to_ident("iter");
4049 let next_ident = self.str_to_ident("__next");
4050 let next_sp = self.allow_internal_unstable(
4051 CompilerDesugaringKind::ForLoop,
4054 let next_pat = self.pat_ident_binding_mode(
4057 hir::BindingAnnotation::Mutable,
4060 // `::std::option::Option::Some(val) => next = val`
4062 let val_ident = self.str_to_ident("val");
4063 let val_pat = self.pat_ident(pat.span, val_ident);
4064 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4065 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4066 let assign = P(self.expr(
4068 hir::ExprKind::Assign(next_expr, val_expr),
4071 let some_pat = self.pat_some(pat.span, val_pat);
4072 self.arm(hir_vec![some_pat], assign)
4075 // `::std::option::Option::None => break`
4078 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4079 let pat = self.pat_none(e.span);
4080 self.arm(hir_vec![pat], break_expr)
4085 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
4087 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4089 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4090 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4091 let next_path = &["iter", "Iterator", "next"];
4092 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4093 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4094 let arms = hir_vec![pat_arm, break_arm];
4098 hir::ExprKind::Match(
4101 hir::MatchSource::ForLoopDesugar
4106 let match_stmt = respan(
4108 hir::StmtKind::Expr(match_expr, self.next_id().node_id)
4111 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4115 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
4117 // `let <pat> = __next`
4118 let pat = self.lower_pat(pat);
4119 let pat_let = self.stmt_let_pat(
4123 hir::LocalSource::ForLoopDesugar,
4126 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4127 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4128 let body_stmt = respan(
4130 hir::StmtKind::Expr(body_expr, self.next_id().node_id)
4133 let loop_block = P(self.block_all(
4135 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4139 // `[opt_ident]: loop { ... }`
4140 let loop_expr = hir::ExprKind::Loop(
4142 self.lower_label(opt_label),
4143 hir::LoopSource::ForLoop,
4145 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4146 let loop_expr = P(hir::Expr {
4151 attrs: ThinVec::new(),
4154 // `mut iter => { ... }`
4155 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4157 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4158 let into_iter_expr = {
4159 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4160 let into_iter = P(self.expr_std_path(
4161 head_sp, into_iter_path, None, ThinVec::new()));
4162 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4165 let match_expr = P(self.expr_match(
4169 hir::MatchSource::ForLoopDesugar,
4172 // `{ let _result = ...; _result }`
4173 // underscore prevents an unused_variables lint if the head diverges
4174 let result_ident = self.str_to_ident("_result");
4175 let (let_stmt, let_stmt_binding) =
4176 self.stmt_let(e.span, false, result_ident, match_expr);
4178 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4179 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4180 // add the attributes to the outer returned expr node
4181 return self.expr_block(block, e.attrs.clone());
4184 // Desugar ExprKind::Try
4186 ExprKind::Try(ref sub_expr) => {
4189 // match Try::into_result(<expr>) {
4190 // Ok(val) => #[allow(unreachable_code)] val,
4191 // Err(err) => #[allow(unreachable_code)]
4192 // // If there is an enclosing `catch {...}`
4193 // break 'catch_target Try::from_error(From::from(err)),
4195 // return Try::from_error(From::from(err)),
4199 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4201 // Try::into_result(<expr>)
4204 let sub_expr = self.lower_expr(sub_expr);
4206 let path = &["ops", "Try", "into_result"];
4207 let path = P(self.expr_std_path(
4208 unstable_span, path, None, ThinVec::new()));
4209 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4212 // #[allow(unreachable_code)]
4214 // allow(unreachable_code)
4216 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4217 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4218 let uc_nested = attr::mk_nested_word_item(uc_ident);
4219 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4221 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4223 let attrs = vec![attr];
4225 // Ok(val) => #[allow(unreachable_code)] val,
4227 let val_ident = self.str_to_ident("val");
4228 let val_pat = self.pat_ident(e.span, val_ident);
4229 let val_expr = P(self.expr_ident_with_attrs(
4233 ThinVec::from(attrs.clone()),
4235 let ok_pat = self.pat_ok(e.span, val_pat);
4237 self.arm(hir_vec![ok_pat], val_expr)
4240 // Err(err) => #[allow(unreachable_code)]
4241 // return Try::from_error(From::from(err)),
4243 let err_ident = self.str_to_ident("err");
4244 let err_local = self.pat_ident(e.span, err_ident);
4246 let path = &["convert", "From", "from"];
4247 let from = P(self.expr_std_path(
4248 e.span, path, None, ThinVec::new()));
4249 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4251 self.expr_call(e.span, from, hir_vec![err_expr])
4254 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4255 let thin_attrs = ThinVec::from(attrs);
4256 let catch_scope = self.catch_scopes.last().map(|x| *x);
4257 let ret_expr = if let Some(catch_node) = catch_scope {
4260 hir::ExprKind::Break(
4263 target_id: Ok(catch_node),
4265 Some(from_err_expr),
4270 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4273 let err_pat = self.pat_err(e.span, err_local);
4274 self.arm(hir_vec![err_pat], ret_expr)
4277 hir::ExprKind::Match(
4279 hir_vec![err_arm, ok_arm],
4280 hir::MatchSource::TryDesugar,
4284 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4287 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4294 attrs: e.attrs.clone(),
4298 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
4299 SmallVector::one(match s.node {
4300 StmtKind::Local(ref l) => Spanned {
4301 node: hir::StmtKind::Decl(
4303 node: hir::DeclKind::Local(self.lower_local(l)),
4306 self.lower_node_id(s.id).node_id,
4310 StmtKind::Item(ref it) => {
4311 // Can only use the ID once.
4312 let mut id = Some(s.id);
4313 return self.lower_item_id(it)
4315 .map(|item_id| Spanned {
4316 node: hir::StmtKind::Decl(
4318 node: hir::DeclKind::Item(item_id),
4322 .map(|id| self.lower_node_id(id).node_id)
4323 .unwrap_or_else(|| self.next_id().node_id),
4329 StmtKind::Expr(ref e) => Spanned {
4330 node: hir::StmtKind::Expr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4333 StmtKind::Semi(ref e) => Spanned {
4334 node: hir::StmtKind::Semi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4337 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4341 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4343 CaptureBy::Value => hir::CaptureByValue,
4344 CaptureBy::Ref => hir::CaptureByRef,
4348 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4349 /// the address space of that item instead of the item currently being
4350 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4351 /// lower a `Visibility` value although we haven't lowered the owning
4352 /// `ImplItem` in question yet.
4353 fn lower_visibility(
4356 explicit_owner: Option<NodeId>,
4357 ) -> hir::Visibility {
4358 let node = match v.node {
4359 VisibilityKind::Public => hir::VisibilityKind::Public,
4360 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4361 VisibilityKind::Restricted { ref path, id } => {
4362 let lowered_id = if let Some(owner) = explicit_owner {
4363 self.lower_node_id_with_owner(id, owner)
4365 self.lower_node_id(id)
4367 hir::VisibilityKind::Restricted {
4368 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4369 id: lowered_id.node_id,
4370 hir_id: lowered_id.hir_id,
4373 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4375 respan(v.span, node)
4378 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4380 Defaultness::Default => hir::Defaultness::Default {
4381 has_value: has_value,
4383 Defaultness::Final => {
4385 hir::Defaultness::Final
4390 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4392 BlockCheckMode::Default => hir::DefaultBlock,
4393 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4397 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4399 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4400 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4401 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4402 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4406 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4408 CompilerGenerated => hir::CompilerGenerated,
4409 UserProvided => hir::UserProvided,
4413 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4415 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4416 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4420 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4422 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4423 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4427 // Helper methods for building HIR.
4429 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4438 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4440 id: self.next_id().node_id,
4444 is_shorthand: false,
4448 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4449 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4450 P(self.expr(span, expr_break, attrs))
4457 args: hir::HirVec<hir::Expr>,
4459 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4462 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4463 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4466 fn expr_ident_with_attrs(
4471 attrs: ThinVec<Attribute>,
4473 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4477 def: Def::Local(binding),
4478 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4482 self.expr(span, expr_path, attrs)
4485 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4486 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4492 components: &[&str],
4493 params: Option<P<hir::GenericArgs>>,
4494 attrs: ThinVec<Attribute>,
4496 let path = self.std_path(span, components, params, true);
4499 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4508 arms: hir::HirVec<hir::Arm>,
4509 source: hir::MatchSource,
4511 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4514 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4515 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4518 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4519 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4522 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4523 let LoweredNodeId { node_id, hir_id } = self.next_id();
4536 ex: Option<P<hir::Expr>>,
4538 source: hir::LocalSource,
4540 let LoweredNodeId { node_id, hir_id } = self.next_id();
4542 let local = P(hir::Local {
4549 attrs: ThinVec::new(),
4552 let decl = respan(sp, hir::DeclKind::Local(local));
4553 respan(sp, hir::StmtKind::Decl(P(decl), self.next_id().node_id))
4562 ) -> (hir::Stmt, NodeId) {
4563 let pat = if mutbl {
4564 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4566 self.pat_ident(sp, ident)
4568 let pat_id = pat.id;
4570 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4575 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4576 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4582 stmts: hir::HirVec<hir::Stmt>,
4583 expr: Option<P<hir::Expr>>,
4585 let LoweredNodeId { node_id, hir_id } = self.next_id();
4592 rules: hir::DefaultBlock,
4594 targeted_by_break: false,
4599 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4600 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4603 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4604 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4607 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4608 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4611 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4612 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4618 components: &[&str],
4619 subpats: hir::HirVec<P<hir::Pat>>,
4621 let path = self.std_path(span, components, None, true);
4622 let qpath = hir::QPath::Resolved(None, P(path));
4623 let pt = if subpats.is_empty() {
4624 hir::PatKind::Path(qpath)
4626 hir::PatKind::TupleStruct(qpath, subpats, None)
4631 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4632 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4635 fn pat_ident_binding_mode(
4639 bm: hir::BindingAnnotation,
4641 let LoweredNodeId { node_id, hir_id } = self.next_id();
4646 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4651 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4652 self.pat(span, hir::PatKind::Wild)
4655 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4656 let LoweredNodeId { node_id, hir_id } = self.next_id();
4665 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4666 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4667 /// The path is also resolved according to `is_value`.
4671 components: &[&str],
4672 params: Option<P<hir::GenericArgs>>,
4676 .resolve_str_path(span, self.crate_root, components, params, is_value)
4679 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4681 let node = match qpath {
4682 hir::QPath::Resolved(None, path) => {
4683 // Turn trait object paths into `TyKind::TraitObject` instead.
4684 if let Def::Trait(_) = path.def {
4685 let principal = hir::PolyTraitRef {
4686 bound_generic_params: hir::HirVec::new(),
4687 trait_ref: hir::TraitRef {
4688 path: path.and_then(|path| path),
4690 hir_ref_id: id.hir_id,
4695 // The original ID is taken by the `PolyTraitRef`,
4696 // so the `Ty` itself needs a different one.
4697 id = self.next_id();
4698 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4700 hir::TyKind::Path(hir::QPath::Resolved(None, path))
4703 _ => hir::TyKind::Path(qpath),
4713 /// Invoked to create the lifetime argument for a type `&T`
4714 /// with no explicit lifetime.
4715 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4716 match self.anonymous_lifetime_mode {
4717 // Intercept when we are in an impl header and introduce an in-band lifetime.
4718 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4720 AnonymousLifetimeMode::CreateParameter => {
4721 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4723 id: self.next_id().node_id,
4725 name: hir::LifetimeName::Param(fresh_name),
4729 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4733 /// Invoked to create the lifetime argument(s) for a path like
4734 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4735 /// sorts of cases are deprecated. This may therefore report a warning or an
4736 /// error, depending on the mode.
4737 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4738 match self.anonymous_lifetime_mode {
4739 // NB. We intentionally ignore the create-parameter mode here
4740 // and instead "pass through" to resolve-lifetimes, which will then
4741 // report an error. This is because we don't want to support
4742 // impl elision for deprecated forms like
4744 // impl Foo for std::cell::Ref<u32> // note lack of '_
4745 AnonymousLifetimeMode::CreateParameter => {}
4747 // This is the normal case.
4748 AnonymousLifetimeMode::PassThrough => {}
4752 .map(|_| self.new_implicit_lifetime(span))
4756 /// Invoked to create the lifetime argument(s) for an elided trait object
4757 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4758 /// when the bound is written, even if it is written with `'_` like in
4759 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4760 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4761 match self.anonymous_lifetime_mode {
4762 // NB. We intentionally ignore the create-parameter mode here.
4763 // and instead "pass through" to resolve-lifetimes, which will apply
4764 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4765 // do not act like other elided lifetimes. In other words, given this:
4767 // impl Foo for Box<dyn Debug>
4769 // we do not introduce a fresh `'_` to serve as the bound, but instead
4770 // ultimately translate to the equivalent of:
4772 // impl Foo for Box<dyn Debug + 'static>
4774 // `resolve_lifetime` has the code to make that happen.
4775 AnonymousLifetimeMode::CreateParameter => {}
4777 // This is the normal case.
4778 AnonymousLifetimeMode::PassThrough => {}
4781 self.new_implicit_lifetime(span)
4784 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4786 id: self.next_id().node_id,
4788 name: hir::LifetimeName::Implicit,
4792 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4793 self.sess.buffer_lint_with_diagnostic(
4794 builtin::BARE_TRAIT_OBJECTS,
4797 "trait objects without an explicit `dyn` are deprecated",
4798 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4802 fn wrap_in_try_constructor(
4804 method: &'static str,
4806 unstable_span: Span,
4808 let path = &["ops", "Try", method];
4809 let from_err = P(self.expr_std_path(unstable_span, path, None,
4811 P(self.expr_call(e.span, from_err, hir_vec![e]))
4815 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4816 // Sorting by span ensures that we get things in order within a
4817 // file, and also puts the files in a sensible order.
4818 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4819 body_ids.sort_by_key(|b| bodies[b].value.span);