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};
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,
107 is_in_anon_const: bool,
109 /// What to do when we encounter either an "anonymous lifetime
110 /// reference". The term "anonymous" is meant to encompass both
111 /// `'_` lifetimes as well as fully elided cases where nothing is
112 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
113 anonymous_lifetime_mode: AnonymousLifetimeMode,
115 // Used to create lifetime definitions from in-band lifetime usages.
116 // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
117 // When a named lifetime is encountered in a function or impl header and
118 // has not been defined
119 // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
120 // to this list. The results of this list are then added to the list of
121 // lifetime definitions in the corresponding impl or function generics.
122 lifetimes_to_define: Vec<(Span, ParamName)>,
124 // Whether or not in-band lifetimes are being collected. This is used to
125 // indicate whether or not we're in a place where new lifetimes will result
126 // in in-band lifetime definitions, such a function or an impl header.
127 // This will always be false unless the `in_band_lifetimes` feature is
129 is_collecting_in_band_lifetimes: bool,
131 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
132 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
133 // against this list to see if it is already in-scope, or if a definition
134 // needs to be created for it.
135 in_scope_lifetimes: Vec<Ident>,
137 type_def_lifetime_params: DefIdMap<usize>,
139 current_hir_id_owner: Vec<(DefIndex, u32)>,
140 item_local_id_counters: NodeMap<u32>,
141 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
145 /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
146 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
148 /// Obtain the resolution for a node id
149 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
151 /// Obtain the possible resolutions for the given `use` statement.
152 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
154 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
155 /// This should only return `None` during testing.
156 fn definitions(&mut self) -> &mut Definitions;
158 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
159 /// it based on `is_value`.
163 crate_root: Option<&str>,
165 params: Option<P<hir::GenericArgs>>,
171 enum ImplTraitContext<'a> {
172 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
173 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
174 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
176 /// Newly generated parameters should be inserted into the given `Vec`
177 Universal(&'a mut Vec<hir::GenericParam>),
179 /// Treat `impl Trait` as shorthand for a new universal existential parameter.
180 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
181 /// equivalent to a fresh existential parameter like `abstract type T; fn foo() -> T`.
183 /// We store a DefId here so we can look up necessary information later
186 /// `impl Trait` is not accepted in this position.
190 impl<'a> ImplTraitContext<'a> {
191 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
192 use self::ImplTraitContext::*;
194 Universal(params) => Universal(params),
195 Existential(did) => Existential(*did),
196 Disallowed => Disallowed,
203 cstore: &dyn CrateStore,
204 dep_graph: &DepGraph,
206 resolver: &mut dyn Resolver,
208 // We're constructing the HIR here; we don't care what we will
209 // read, since we haven't even constructed the *input* to
211 dep_graph.assert_ignored();
214 crate_root: std_inject::injected_crate_name(),
218 items: BTreeMap::new(),
219 trait_items: BTreeMap::new(),
220 impl_items: BTreeMap::new(),
221 bodies: BTreeMap::new(),
222 trait_impls: BTreeMap::new(),
223 trait_auto_impl: BTreeMap::new(),
224 exported_macros: Vec::new(),
225 catch_scopes: Vec::new(),
226 loop_scopes: Vec::new(),
227 is_in_loop_condition: false,
228 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
229 type_def_lifetime_params: DefIdMap(),
230 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
231 item_local_id_counters: NodeMap(),
232 node_id_to_hir_id: IndexVec::new(),
234 is_in_trait_impl: false,
235 is_in_anon_const: false,
236 lifetimes_to_define: Vec::new(),
237 is_collecting_in_band_lifetimes: false,
238 in_scope_lifetimes: Vec::new(),
242 #[derive(Copy, Clone, PartialEq)]
244 /// Any path in a type context.
246 /// The `module::Type` in `module::Type::method` in an expression.
251 struct LoweredNodeId {
256 enum ParenthesizedGenericArgs {
262 /// What to do when we encounter an **anonymous** lifetime
263 /// reference. Anonymous lifetime references come in two flavors. You
264 /// have implicit, or fully elided, references to lifetimes, like the
265 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
266 /// or `Ref<'_, T>`. These often behave the same, but not always:
268 /// - certain usages of implicit references are deprecated, like
269 /// `Ref<T>`, and we sometimes just give hard errors in those cases
271 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
272 /// the same as `Box<dyn Foo + '_>`.
274 /// We describe the effects of the various modes in terms of three cases:
276 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
277 /// of a `&` (e.g., the missing lifetime in something like `&T`)
278 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
279 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
280 /// elided bounds follow special rules. Note that this only covers
281 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
282 /// '_>` is a case of "modern" elision.
283 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
284 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
285 /// non-deprecated equivalent.
287 /// Currently, the handling of lifetime elision is somewhat spread out
288 /// between HIR lowering and -- as described below -- the
289 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
290 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
291 /// everything into HIR lowering.
292 #[derive(Copy, Clone)]
293 enum AnonymousLifetimeMode {
294 /// For **Modern** cases, create a new anonymous region parameter
295 /// and reference that.
297 /// For **Dyn Bound** cases, pass responsibility to
298 /// `resolve_lifetime` code.
300 /// For **Deprecated** cases, report an error.
303 /// Pass responsibility to `resolve_lifetime` code for all cases.
307 impl<'a> LoweringContext<'a> {
308 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
309 /// Full-crate AST visitor that inserts into a fresh
310 /// `LoweringContext` any information that may be
311 /// needed from arbitrary locations in the crate.
312 /// E.g. The number of lifetime generic parameters
313 /// declared for every type and trait definition.
314 struct MiscCollector<'lcx, 'interner: 'lcx> {
315 lctx: &'lcx mut LoweringContext<'interner>,
318 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
319 fn visit_item(&mut self, item: &'lcx Item) {
320 self.lctx.allocate_hir_id_counter(item.id, item);
323 ItemKind::Struct(_, ref generics)
324 | ItemKind::Union(_, ref generics)
325 | ItemKind::Enum(_, ref generics)
326 | ItemKind::Ty(_, ref generics)
327 | ItemKind::Existential(_, ref generics)
328 | ItemKind::Trait(_, _, ref generics, ..) => {
329 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
333 .filter(|param| match param.kind {
334 ast::GenericParamKind::Lifetime { .. } => true,
338 self.lctx.type_def_lifetime_params.insert(def_id, count);
342 visit::walk_item(self, item);
345 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
346 self.lctx.allocate_hir_id_counter(item.id, item);
347 visit::walk_trait_item(self, item);
350 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
351 self.lctx.allocate_hir_id_counter(item.id, item);
352 visit::walk_impl_item(self, item);
356 struct ItemLowerer<'lcx, 'interner: 'lcx> {
357 lctx: &'lcx mut LoweringContext<'interner>,
360 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
361 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
363 F: FnOnce(&mut Self),
365 let old = self.lctx.is_in_trait_impl;
366 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
372 self.lctx.is_in_trait_impl = old;
376 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
377 fn visit_item(&mut self, item: &'lcx Item) {
378 let mut item_lowered = true;
379 self.lctx.with_hir_id_owner(item.id, |lctx| {
380 if let Some(hir_item) = lctx.lower_item(item) {
381 lctx.items.insert(item.id, hir_item);
383 item_lowered = false;
388 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
389 hir::ItemKind::Impl(_, _, _, ref generics, ..)
390 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
391 generics.params.clone()
396 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
397 let this = &mut ItemLowerer { lctx: this };
398 if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
399 this.with_trait_impl_ref(opt_trait_ref, |this| {
400 visit::walk_item(this, item)
403 visit::walk_item(this, item);
409 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
410 self.lctx.with_hir_id_owner(item.id, |lctx| {
411 let id = hir::TraitItemId { node_id: item.id };
412 let hir_item = lctx.lower_trait_item(item);
413 lctx.trait_items.insert(id, hir_item);
416 visit::walk_trait_item(self, item);
419 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
420 self.lctx.with_hir_id_owner(item.id, |lctx| {
421 let id = hir::ImplItemId { node_id: item.id };
422 let hir_item = lctx.lower_impl_item(item);
423 lctx.impl_items.insert(id, hir_item);
425 visit::walk_impl_item(self, item);
429 self.lower_node_id(CRATE_NODE_ID);
430 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
432 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
433 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
435 let module = self.lower_mod(&c.module);
436 let attrs = self.lower_attrs(&c.attrs);
437 let body_ids = body_ids(&self.bodies);
441 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
447 exported_macros: hir::HirVec::from(self.exported_macros),
449 trait_items: self.trait_items,
450 impl_items: self.impl_items,
453 trait_impls: self.trait_impls,
454 trait_auto_impl: self.trait_auto_impl,
458 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
459 if self.item_local_id_counters.insert(owner, 0).is_some() {
461 "Tried to allocate item_local_id_counter for {:?} twice",
465 // Always allocate the first HirId for the owner itself
466 self.lower_node_id_with_owner(owner, owner)
469 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
471 F: FnOnce(&mut Self) -> hir::HirId,
473 if ast_node_id == DUMMY_NODE_ID {
474 return LoweredNodeId {
475 node_id: DUMMY_NODE_ID,
476 hir_id: hir::DUMMY_HIR_ID,
480 let min_size = ast_node_id.as_usize() + 1;
482 if min_size > self.node_id_to_hir_id.len() {
483 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
486 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
488 if existing_hir_id == hir::DUMMY_HIR_ID {
489 // Generate a new HirId
490 let hir_id = alloc_hir_id(self);
491 self.node_id_to_hir_id[ast_node_id] = hir_id;
493 node_id: ast_node_id,
498 node_id: ast_node_id,
499 hir_id: existing_hir_id,
504 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
506 F: FnOnce(&mut Self) -> T,
508 let counter = self.item_local_id_counters
509 .insert(owner, HIR_ID_COUNTER_LOCKED)
510 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
511 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
512 self.current_hir_id_owner.push((def_index, counter));
514 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
516 debug_assert!(def_index == new_def_index);
517 debug_assert!(new_counter >= counter);
519 let prev = self.item_local_id_counters
520 .insert(owner, new_counter)
522 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
526 /// This method allocates a new HirId for the given NodeId and stores it in
527 /// the LoweringContext's NodeId => HirId map.
528 /// Take care not to call this method if the resulting HirId is then not
529 /// actually used in the HIR, as that would trigger an assertion in the
530 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
531 /// properly. Calling the method twice with the same NodeId is fine though.
532 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
533 self.lower_node_id_generic(ast_node_id, |this| {
534 let &mut (def_index, ref mut local_id_counter) =
535 this.current_hir_id_owner.last_mut().unwrap();
536 let local_id = *local_id_counter;
537 *local_id_counter += 1;
540 local_id: hir::ItemLocalId(local_id),
545 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
546 self.lower_node_id_generic(ast_node_id, |this| {
547 let local_id_counter = this
548 .item_local_id_counters
550 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
551 let local_id = *local_id_counter;
553 // We want to be sure not to modify the counter in the map while it
554 // is also on the stack. Otherwise we'll get lost updates when writing
555 // back from the stack to the map.
556 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
558 *local_id_counter += 1;
562 .opt_def_index(owner)
563 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
564 that do not belong to the current owner");
568 local_id: hir::ItemLocalId(local_id),
573 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
574 let body = hir::Body {
575 arguments: decl.map_or(hir_vec![], |decl| {
576 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
578 is_generator: self.is_generator,
582 self.bodies.insert(id, body);
586 fn next_id(&mut self) -> LoweredNodeId {
587 self.lower_node_id(self.sess.next_node_id())
590 fn expect_full_def(&mut self, id: NodeId) -> Def {
591 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
592 if pr.unresolved_segments() != 0 {
593 bug!("path not fully resolved: {:?}", pr);
599 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item=Def> {
600 self.resolver.get_import(id).present_items().map(|pr| {
601 if pr.unresolved_segments() != 0 {
602 bug!("path not fully resolved: {:?}", pr);
608 fn diagnostic(&self) -> &errors::Handler {
609 self.sess.diagnostic()
612 fn str_to_ident(&self, s: &'static str) -> Ident {
613 Ident::with_empty_ctxt(Symbol::gensym(s))
616 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
617 let mark = Mark::fresh(Mark::root());
618 mark.set_expn_info(codemap::ExpnInfo {
620 def_site: Some(span),
621 format: codemap::CompilerDesugaring(reason),
622 allow_internal_unstable: true,
623 allow_internal_unsafe: false,
624 local_inner_macros: false,
625 edition: codemap::hygiene::default_edition(),
627 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
630 fn with_anonymous_lifetime_mode<R>(
632 anonymous_lifetime_mode: AnonymousLifetimeMode,
633 op: impl FnOnce(&mut Self) -> R,
635 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
636 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
637 let result = op(self);
638 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
642 /// Creates a new hir::GenericParam for every new lifetime and
643 /// type parameter encountered while evaluating `f`. Definitions
644 /// are created with the parent provided. If no `parent_id` is
645 /// provided, no definitions will be returned.
647 /// Presuming that in-band lifetimes are enabled, then
648 /// `self.anonymous_lifetime_mode` will be updated to match the
649 /// argument while `f` is running (and restored afterwards).
650 fn collect_in_band_defs<T, F>(
653 anonymous_lifetime_mode: AnonymousLifetimeMode,
655 ) -> (Vec<hir::GenericParam>, T)
657 F: FnOnce(&mut LoweringContext) -> (Vec<hir::GenericParam>, T),
659 assert!(!self.is_collecting_in_band_lifetimes);
660 assert!(self.lifetimes_to_define.is_empty());
661 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
663 self.is_collecting_in_band_lifetimes = self.sess.features_untracked().in_band_lifetimes;
664 if self.is_collecting_in_band_lifetimes {
665 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
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.in_scope_lifetimes.contains(&ident.modern()) {
727 let hir_name = ParamName::Plain(ident);
729 if self.lifetimes_to_define.iter()
730 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
734 self.lifetimes_to_define.push((ident.span, hir_name));
737 /// When we have either an elided or `'_` lifetime in an impl
738 /// header, we convert it to
739 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
740 assert!(self.is_collecting_in_band_lifetimes);
741 let index = self.lifetimes_to_define.len();
742 let hir_name = ParamName::Fresh(index);
743 self.lifetimes_to_define.push((span, hir_name));
747 // Evaluates `f` with the lifetimes in `params` in-scope.
748 // This is used to track which lifetimes have already been defined, and
749 // which are new in-band lifetimes that need to have a definition created
751 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &Vec<GenericParam>, f: F) -> T
753 F: FnOnce(&mut LoweringContext) -> T,
755 let old_len = self.in_scope_lifetimes.len();
756 let lt_def_names = params.iter().filter_map(|param| match param.kind {
757 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
760 self.in_scope_lifetimes.extend(lt_def_names);
764 self.in_scope_lifetimes.truncate(old_len);
768 // Same as the method above, but accepts `hir::GenericParam`s
769 // instead of `ast::GenericParam`s.
770 // This should only be used with generics that have already had their
771 // in-band lifetimes added. In practice, this means that this function is
772 // only used when lowering a child item of a trait or impl.
773 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
774 params: &HirVec<hir::GenericParam>,
777 F: FnOnce(&mut LoweringContext) -> T,
779 let old_len = self.in_scope_lifetimes.len();
780 let lt_def_names = params.iter().filter_map(|param| match param.kind {
781 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
784 self.in_scope_lifetimes.extend(lt_def_names);
788 self.in_scope_lifetimes.truncate(old_len);
792 /// Appends in-band lifetime defs and argument-position `impl
793 /// Trait` defs to the existing set of generics.
795 /// Presuming that in-band lifetimes are enabled, then
796 /// `self.anonymous_lifetime_mode` will be updated to match the
797 /// argument while `f` is running (and restored afterwards).
798 fn add_in_band_defs<F, T>(
802 anonymous_lifetime_mode: AnonymousLifetimeMode,
804 ) -> (hir::Generics, T)
806 F: FnOnce(&mut LoweringContext, &mut Vec<hir::GenericParam>) -> T,
808 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
811 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
812 let mut params = Vec::new();
813 let generics = this.lower_generics(
815 ImplTraitContext::Universal(&mut params),
817 let res = f(this, &mut params);
818 (params, (generics, res))
823 lowered_generics.params = lowered_generics
830 (lowered_generics, res)
833 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
835 F: FnOnce(&mut LoweringContext) -> T,
837 let len = self.catch_scopes.len();
838 self.catch_scopes.push(catch_id);
840 let result = f(self);
843 self.catch_scopes.len(),
844 "catch scopes should be added and removed in stack order"
847 self.catch_scopes.pop().unwrap();
854 capture_clause: CaptureBy,
855 closure_node_id: NodeId,
857 body: impl FnOnce(&mut LoweringContext) -> hir::Expr,
859 let prev_is_generator = mem::replace(&mut self.is_generator, true);
860 let body_expr = body(self);
861 let span = body_expr.span;
862 let output = match ret_ty {
863 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
864 None => FunctionRetTy::Default(span),
871 let body_id = self.record_body(body_expr, Some(&decl));
872 self.is_generator = prev_is_generator;
874 let capture_clause = self.lower_capture_clause(capture_clause);
875 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
876 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
877 let generator = hir::Expr {
879 hir_id: closure_hir_id,
880 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
881 Some(hir::GeneratorMovability::Static)),
883 attrs: ThinVec::new(),
886 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
887 let gen_future = self.expr_std_path(
888 unstable_span, &["future", "from_generator"], None, ThinVec::new());
889 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
892 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
894 F: FnOnce(&mut LoweringContext) -> hir::Expr,
896 let prev = mem::replace(&mut self.is_generator, false);
897 let result = f(self);
898 let r = self.record_body(result, decl);
899 self.is_generator = prev;
903 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
905 F: FnOnce(&mut LoweringContext) -> T,
907 // We're no longer in the base loop's condition; we're in another loop.
908 let was_in_loop_condition = self.is_in_loop_condition;
909 self.is_in_loop_condition = false;
911 let len = self.loop_scopes.len();
912 self.loop_scopes.push(loop_id);
914 let result = f(self);
917 self.loop_scopes.len(),
918 "Loop scopes should be added and removed in stack order"
921 self.loop_scopes.pop().unwrap();
923 self.is_in_loop_condition = was_in_loop_condition;
928 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
930 F: FnOnce(&mut LoweringContext) -> T,
932 let was_in_loop_condition = self.is_in_loop_condition;
933 self.is_in_loop_condition = true;
935 let result = f(self);
937 self.is_in_loop_condition = was_in_loop_condition;
942 fn with_new_scopes<T, F>(&mut self, f: F) -> T
944 F: FnOnce(&mut LoweringContext) -> T,
946 let was_in_loop_condition = self.is_in_loop_condition;
947 self.is_in_loop_condition = false;
949 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
950 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
951 let result = f(self);
952 self.catch_scopes = catch_scopes;
953 self.loop_scopes = loop_scopes;
955 self.is_in_loop_condition = was_in_loop_condition;
960 fn def_key(&mut self, id: DefId) -> DefKey {
962 self.resolver.definitions().def_key(id.index)
964 self.cstore.def_key(id)
968 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
969 label.map(|label| hir::Label {
974 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
975 let target_id = if self.is_in_anon_const {
976 Err(hir::LoopIdError::OutsideLoopScope)
980 if let Def::Label(loop_id) = self.expect_full_def(id) {
981 Ok(self.lower_node_id(loop_id).node_id)
983 Err(hir::LoopIdError::UnresolvedLabel)
989 .map(|innermost_loop_id| *innermost_loop_id)
990 .map(|id| Ok(self.lower_node_id(id).node_id))
991 .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 current_lt_span.between(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 current_lt_span.between(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 mut bounds = vec![
2159 hir::GenericBound::Trait(
2161 trait_ref: hir::TraitRef {
2163 ref_id: this.next_id().node_id,
2165 bound_generic_params: hir_vec![],
2168 hir::TraitBoundModifier::None
2172 if let Some((name, span)) = bound_lifetime {
2173 bounds.push(hir::GenericBound::Outlives(
2174 hir::Lifetime { id: this.next_id().node_id, name, span }));
2177 hir::HirVec::from(bounds)
2180 let LoweredNodeId { node_id, hir_id } = self.next_id();
2181 let impl_trait_ty = P(hir::Ty {
2183 node: impl_trait_ty,
2188 hir::FunctionRetTy::Return(impl_trait_ty)
2191 fn lower_param_bound(
2194 itctx: ImplTraitContext,
2195 ) -> hir::GenericBound {
2197 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2198 self.lower_poly_trait_ref(ty, itctx),
2199 self.lower_trait_bound_modifier(modifier),
2201 GenericBound::Outlives(ref lifetime) => {
2202 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2207 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2208 let span = l.ident.span;
2210 ident if ident.name == keywords::StaticLifetime.name() =>
2211 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2212 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2213 match self.anonymous_lifetime_mode {
2214 AnonymousLifetimeMode::CreateParameter => {
2215 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2216 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2219 AnonymousLifetimeMode::PassThrough => {
2220 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2224 self.maybe_collect_in_band_lifetime(ident);
2225 let param_name = ParamName::Plain(ident);
2226 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2231 fn new_named_lifetime(
2235 name: hir::LifetimeName,
2236 ) -> hir::Lifetime {
2238 id: self.lower_node_id(id).node_id,
2244 fn lower_generic_params(
2246 params: &Vec<GenericParam>,
2247 add_bounds: &NodeMap<Vec<GenericBound>>,
2248 mut itctx: ImplTraitContext,
2249 ) -> hir::HirVec<hir::GenericParam> {
2250 params.iter().map(|param| {
2251 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2255 fn lower_generic_param(&mut self,
2256 param: &GenericParam,
2257 add_bounds: &NodeMap<Vec<GenericBound>>,
2258 mut itctx: ImplTraitContext)
2259 -> hir::GenericParam {
2260 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx.reborrow());
2262 GenericParamKind::Lifetime => {
2263 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2264 self.is_collecting_in_band_lifetimes = false;
2266 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
2267 let param_name = match lt.name {
2268 hir::LifetimeName::Param(param_name) => param_name,
2269 _ => hir::ParamName::Plain(lt.name.ident()),
2271 let param = hir::GenericParam {
2275 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2276 attrs: self.lower_attrs(¶m.attrs),
2278 kind: hir::GenericParamKind::Lifetime { in_band: false }
2281 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2285 GenericParamKind::Type { ref default, .. } => {
2286 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2287 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2288 // Instead, use gensym("Self") to create a distinct name that looks the same.
2289 let ident = if param.ident.name == keywords::SelfType.name() {
2290 param.ident.gensym()
2295 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2296 if !add_bounds.is_empty() {
2297 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2298 bounds = bounds.into_iter()
2304 id: self.lower_node_id(param.id).node_id,
2305 name: hir::ParamName::Plain(ident),
2306 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2307 attrs: self.lower_attrs(¶m.attrs),
2310 kind: hir::GenericParamKind::Type {
2311 default: default.as_ref().map(|x| {
2312 self.lower_ty(x, ImplTraitContext::Disallowed)
2314 synthetic: param.attrs.iter()
2315 .filter(|attr| attr.check_name("rustc_synthetic"))
2316 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2326 generics: &Generics,
2327 itctx: ImplTraitContext)
2330 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2331 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2332 // paths where report_error is called are also the only paths that advance to after
2333 // the match statement, so the error reporting could probably just be moved there.
2334 let mut add_bounds = NodeMap();
2335 for pred in &generics.where_clause.predicates {
2336 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2337 'next_bound: for bound in &bound_pred.bounds {
2338 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2339 let report_error = |this: &mut Self| {
2340 this.diagnostic().span_err(
2341 bound_pred.bounded_ty.span,
2342 "`?Trait` bounds are only permitted at the \
2343 point where a type parameter is declared",
2346 // Check if the where clause type is a plain type parameter.
2347 match bound_pred.bounded_ty.node {
2348 TyKind::Path(None, ref path)
2349 if path.segments.len() == 1
2350 && bound_pred.bound_generic_params.is_empty() =>
2352 if let Some(Def::TyParam(def_id)) = self.resolver
2353 .get_resolution(bound_pred.bounded_ty.id)
2354 .map(|d| d.base_def())
2356 if let Some(node_id) =
2357 self.resolver.definitions().as_local_node_id(def_id)
2359 for param in &generics.params {
2361 GenericParamKind::Type { .. } => {
2362 if node_id == param.id {
2363 add_bounds.entry(param.id)
2364 .or_insert(Vec::new())
2365 .push(bound.clone());
2366 continue 'next_bound;
2376 _ => report_error(self),
2384 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2385 where_clause: self.lower_where_clause(&generics.where_clause),
2386 span: generics.span,
2390 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2392 id: self.lower_node_id(wc.id).node_id,
2393 predicates: wc.predicates
2395 .map(|predicate| self.lower_where_predicate(predicate))
2400 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2402 WherePredicate::BoundPredicate(WhereBoundPredicate {
2403 ref bound_generic_params,
2408 self.with_in_scope_lifetime_defs(
2409 &bound_generic_params,
2411 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2412 bound_generic_params: this.lower_generic_params(
2413 bound_generic_params,
2415 ImplTraitContext::Disallowed,
2417 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2420 .filter_map(|bound| match *bound {
2421 // Ignore `?Trait` bounds.
2422 // Tthey were copied into type parameters already.
2423 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2424 _ => Some(this.lower_param_bound(
2426 ImplTraitContext::Disallowed,
2435 WherePredicate::RegionPredicate(WhereRegionPredicate {
2439 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2441 lifetime: self.lower_lifetime(lifetime),
2442 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2444 WherePredicate::EqPredicate(WhereEqPredicate {
2449 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2450 id: self.lower_node_id(id).node_id,
2451 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2452 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2458 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2460 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2464 .map(|f| self.lower_struct_field(f))
2466 self.lower_node_id(id).node_id,
2468 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2472 .map(|f| self.lower_struct_field(f))
2474 self.lower_node_id(id).node_id,
2476 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2480 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2481 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2482 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2483 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2487 ref_id: self.lower_node_id(p.ref_id).node_id,
2491 fn lower_poly_trait_ref(
2494 mut itctx: ImplTraitContext,
2495 ) -> hir::PolyTraitRef {
2496 let bound_generic_params =
2497 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx.reborrow());
2498 let trait_ref = self.with_parent_impl_lifetime_defs(
2499 &bound_generic_params,
2500 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2504 bound_generic_params,
2510 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2513 id: self.lower_node_id(f.id).node_id,
2514 ident: match f.ident {
2515 Some(ident) => ident,
2516 // FIXME(jseyfried) positional field hygiene
2517 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2519 vis: self.lower_visibility(&f.vis, None),
2520 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2521 attrs: self.lower_attrs(&f.attrs),
2525 fn lower_field(&mut self, f: &Field) -> hir::Field {
2527 id: self.next_id().node_id,
2529 expr: P(self.lower_expr(&f.expr)),
2531 is_shorthand: f.is_shorthand,
2535 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2537 ty: self.lower_ty(&mt.ty, itctx),
2538 mutbl: self.lower_mutability(mt.mutbl),
2542 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext)
2543 -> hir::GenericBounds {
2544 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2547 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2548 let mut expr = None;
2550 let mut stmts = vec![];
2552 for (index, stmt) in b.stmts.iter().enumerate() {
2553 if index == b.stmts.len() - 1 {
2554 if let StmtKind::Expr(ref e) = stmt.node {
2555 expr = Some(P(self.lower_expr(e)));
2557 stmts.extend(self.lower_stmt(stmt));
2560 stmts.extend(self.lower_stmt(stmt));
2564 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2569 stmts: stmts.into(),
2571 rules: self.lower_block_check_mode(&b.rules),
2574 recovered: b.recovered,
2578 fn lower_async_body(
2584 self.lower_body(Some(decl), |this| {
2585 if let IsAsync::Async { closure_id, .. } = asyncness {
2586 let async_expr = this.make_async_expr(
2587 CaptureBy::Value, closure_id, None,
2589 let body = this.lower_block(body, false);
2590 this.expr_block(body, ThinVec::new())
2592 this.expr(body.span, async_expr, ThinVec::new())
2594 let body = this.lower_block(body, false);
2595 this.expr_block(body, ThinVec::new())
2604 attrs: &hir::HirVec<Attribute>,
2605 vis: &mut hir::Visibility,
2607 ) -> hir::ItemKind {
2609 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2610 ItemKind::Use(ref use_tree) => {
2611 // Start with an empty prefix
2614 span: use_tree.span,
2617 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2619 ItemKind::Static(ref t, m, ref e) => {
2620 let value = self.lower_body(None, |this| this.lower_expr(e));
2621 hir::ItemKind::Static(
2622 self.lower_ty(t, ImplTraitContext::Disallowed),
2623 self.lower_mutability(m),
2627 ItemKind::Const(ref t, ref e) => {
2628 let value = self.lower_body(None, |this| this.lower_expr(e));
2629 hir::ItemKind::Const(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2631 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2632 let fn_def_id = self.resolver.definitions().local_def_id(id);
2634 self.with_new_scopes(|this| {
2635 // Note: we don't need to change the return type from `T` to
2636 // `impl Future<Output = T>` here because lower_body
2637 // only cares about the input argument patterns in the function
2638 // declaration (decl), not the return types.
2639 let body_id = this.lower_async_body(decl, header.asyncness, body);
2641 let (generics, fn_decl) = this.add_in_band_defs(
2644 AnonymousLifetimeMode::PassThrough,
2645 |this, idty| this.lower_fn_decl(
2646 decl, Some((fn_def_id, idty)), true, header.asyncness.opt_return_id()),
2651 this.lower_fn_header(header),
2657 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2658 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2659 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2660 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2661 self.lower_ty(t, ImplTraitContext::Disallowed),
2662 self.lower_generics(generics, ImplTraitContext::Disallowed),
2664 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2665 generics: self.lower_generics(generics, ImplTraitContext::Disallowed),
2666 bounds: self.lower_param_bounds(b, ImplTraitContext::Disallowed),
2667 impl_trait_fn: None,
2669 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2671 variants: enum_definition
2674 .map(|x| self.lower_variant(x))
2677 self.lower_generics(generics, ImplTraitContext::Disallowed),
2679 ItemKind::Struct(ref struct_def, ref generics) => {
2680 let struct_def = self.lower_variant_data(struct_def);
2681 hir::ItemKind::Struct(
2683 self.lower_generics(generics, ImplTraitContext::Disallowed),
2686 ItemKind::Union(ref vdata, ref generics) => {
2687 let vdata = self.lower_variant_data(vdata);
2688 hir::ItemKind::Union(
2690 self.lower_generics(generics, ImplTraitContext::Disallowed),
2702 let def_id = self.resolver.definitions().local_def_id(id);
2704 // Lower the "impl header" first. This ordering is important
2705 // for in-band lifetimes! Consider `'a` here:
2707 // impl Foo<'a> for u32 {
2708 // fn method(&'a self) { .. }
2711 // Because we start by lowering the `Foo<'a> for u32`
2712 // part, we will add `'a` to the list of generics on
2713 // the impl. When we then encounter it later in the
2714 // method, it will not be considered an in-band
2715 // lifetime to be added, but rather a reference to a
2717 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2720 AnonymousLifetimeMode::CreateParameter,
2722 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2723 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2726 if let Some(ref trait_ref) = trait_ref {
2727 if let Def::Trait(def_id) = trait_ref.path.def {
2728 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2732 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2734 (trait_ref, lowered_ty)
2738 let new_impl_items = self.with_in_scope_lifetime_defs(
2739 &ast_generics.params,
2743 .map(|item| this.lower_impl_item_ref(item))
2748 hir::ItemKind::Impl(
2749 self.lower_unsafety(unsafety),
2750 self.lower_impl_polarity(polarity),
2751 self.lower_defaultness(defaultness, true /* [1] */),
2758 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2759 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2762 .map(|item| self.lower_trait_item_ref(item))
2764 hir::ItemKind::Trait(
2765 self.lower_is_auto(is_auto),
2766 self.lower_unsafety(unsafety),
2767 self.lower_generics(generics, ImplTraitContext::Disallowed),
2772 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
2773 self.lower_generics(generics, ImplTraitContext::Disallowed),
2774 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2776 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2779 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2780 // not cause an assertion failure inside the `lower_defaultness` function
2788 vis: &mut hir::Visibility,
2790 attrs: &hir::HirVec<Attribute>,
2791 ) -> hir::ItemKind {
2792 let path = &tree.prefix;
2795 UseTreeKind::Simple(rename, id1, id2) => {
2796 *name = tree.ident().name;
2798 // First apply the prefix to the path
2799 let mut path = Path {
2803 .chain(path.segments.iter())
2809 // Correctly resolve `self` imports
2810 if path.segments.len() > 1
2811 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2813 let _ = path.segments.pop();
2814 if rename.is_none() {
2815 *name = path.segments.last().unwrap().ident.name;
2819 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2820 let mut defs = self.expect_full_def_from_use(id);
2821 // we want to return *something* from this function, so hang onto the first item
2823 let mut ret_def = defs.next().unwrap_or(Def::Err);
2825 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2826 let vis = vis.clone();
2827 let name = name.clone();
2828 let span = path.span;
2829 self.resolver.definitions().create_def_with_parent(
2833 DefIndexAddressSpace::High,
2836 self.allocate_hir_id_counter(new_node_id, &path);
2838 self.with_hir_id_owner(new_node_id, |this| {
2839 let new_id = this.lower_node_id(new_node_id);
2840 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2841 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
2842 let vis_kind = match vis.node {
2843 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2844 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2845 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2846 hir::VisibilityKind::Restricted { ref path, id: _ } => {
2847 hir::VisibilityKind::Restricted {
2849 // We are allocating a new NodeId here
2850 id: this.next_id().node_id,
2854 let vis = respan(vis.span, vis_kind);
2860 hir_id: new_id.hir_id,
2862 attrs: attrs.clone(),
2871 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2872 hir::ItemKind::Use(path, hir::UseKind::Single)
2874 UseTreeKind::Glob => {
2875 let path = P(self.lower_path(
2881 .chain(path.segments.iter())
2886 ParamMode::Explicit,
2888 hir::ItemKind::Use(path, hir::UseKind::Glob)
2890 UseTreeKind::Nested(ref trees) => {
2895 .chain(path.segments.iter())
2898 span: prefix.span.to(path.span),
2901 // Add all the nested PathListItems in the HIR
2902 for &(ref use_tree, id) in trees {
2903 self.allocate_hir_id_counter(id, &use_tree);
2907 } = self.lower_node_id(id);
2909 let mut vis = vis.clone();
2910 let mut name = name.clone();
2912 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2914 self.with_hir_id_owner(new_id, |this| {
2915 let vis_kind = match vis.node {
2916 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2917 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2918 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2919 hir::VisibilityKind::Restricted { ref path, id: _ } => {
2920 hir::VisibilityKind::Restricted {
2922 // We are allocating a new NodeId here
2923 id: this.next_id().node_id,
2927 let vis = respan(vis.span, vis_kind);
2935 attrs: attrs.clone(),
2938 span: use_tree.span,
2944 // Privatize the degenerate import base, used only to check
2945 // the stability of `use a::{};`, to avoid it showing up as
2946 // a re-export by accident when `pub`, e.g. in documentation.
2947 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2948 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
2949 hir::ItemKind::Use(path, hir::UseKind::ListStem)
2954 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2955 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2956 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2958 let (generics, node) = match i.node {
2959 TraitItemKind::Const(ref ty, ref default) => (
2960 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2961 hir::TraitItemKind::Const(
2962 self.lower_ty(ty, ImplTraitContext::Disallowed),
2965 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2968 TraitItemKind::Method(ref sig, None) => {
2969 let names = self.lower_fn_args_to_names(&sig.decl);
2970 let (generics, sig) = self.lower_method_sig(
2977 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
2979 TraitItemKind::Method(ref sig, Some(ref body)) => {
2980 let body_id = self.lower_body(Some(&sig.decl), |this| {
2981 let body = this.lower_block(body, false);
2982 this.expr_block(body, ThinVec::new())
2985 let (generics, sig) = self.lower_method_sig(
2993 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
2995 TraitItemKind::Type(ref bounds, ref default) => (
2996 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2997 hir::TraitItemKind::Type(
2998 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3001 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
3004 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3011 attrs: self.lower_attrs(&i.attrs),
3018 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3019 let (kind, has_default) = match i.node {
3020 TraitItemKind::Const(_, ref default) => {
3021 (hir::AssociatedItemKind::Const, default.is_some())
3023 TraitItemKind::Type(_, ref default) => {
3024 (hir::AssociatedItemKind::Type, default.is_some())
3026 TraitItemKind::Method(ref sig, ref default) => (
3027 hir::AssociatedItemKind::Method {
3028 has_self: sig.decl.has_self(),
3032 TraitItemKind::Macro(..) => unimplemented!(),
3035 id: hir::TraitItemId { node_id: i.id },
3038 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3043 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3044 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3045 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3047 let (generics, node) = match i.node {
3048 ImplItemKind::Const(ref ty, ref expr) => {
3049 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3051 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3052 hir::ImplItemKind::Const(
3053 self.lower_ty(ty, ImplTraitContext::Disallowed),
3058 ImplItemKind::Method(ref sig, ref body) => {
3059 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3060 let impl_trait_return_allow = !self.is_in_trait_impl;
3061 let (generics, sig) = self.lower_method_sig(
3065 impl_trait_return_allow,
3066 sig.header.asyncness.opt_return_id(),
3068 (generics, hir::ImplItemKind::Method(sig, body_id))
3070 ImplItemKind::Type(ref ty) => (
3071 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3072 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
3074 ImplItemKind::Existential(ref bounds) => (
3075 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3076 hir::ImplItemKind::Existential(
3077 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3080 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3087 attrs: self.lower_attrs(&i.attrs),
3089 vis: self.lower_visibility(&i.vis, None),
3090 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3095 // [1] since `default impl` is not yet implemented, this is always true in impls
3098 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3100 id: hir::ImplItemId { node_id: i.id },
3103 vis: self.lower_visibility(&i.vis, Some(i.id)),
3104 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3105 kind: match i.node {
3106 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3107 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3108 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3109 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3110 has_self: sig.decl.has_self(),
3112 ImplItemKind::Macro(..) => unimplemented!(),
3116 // [1] since `default impl` is not yet implemented, this is always true in impls
3119 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3122 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3126 /// Lowers `impl Trait` items and appends them to the list
3127 fn lower_impl_trait_ids(
3131 ids: &mut SmallVector<hir::ItemId>,
3133 if let Some(id) = header.asyncness.opt_return_id() {
3134 ids.push(hir::ItemId { id });
3136 struct IdVisitor<'a> { ids: &'a mut SmallVector<hir::ItemId> }
3137 impl<'a, 'b> Visitor<'a> for IdVisitor<'b> {
3138 fn visit_ty(&mut self, ty: &'a Ty) {
3144 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
3147 visit::walk_ty(self, ty);
3149 fn visit_path_segment(
3152 path_segment: &'v PathSegment,
3154 if let Some(ref p) = path_segment.args {
3155 if let GenericArgs::Parenthesized(_) = **p {
3159 visit::walk_path_segment(self, path_span, path_segment)
3162 let mut visitor = IdVisitor { ids };
3164 FunctionRetTy::Default(_) => {},
3165 FunctionRetTy::Ty(ref ty) => visitor.visit_ty(ty),
3169 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
3171 ItemKind::Use(ref use_tree) => {
3172 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
3173 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3176 ItemKind::MacroDef(..) => SmallVector::new(),
3177 ItemKind::Fn(ref decl, ref header, ..) => {
3178 let mut ids = SmallVector::one(hir::ItemId { id: i.id });
3179 self.lower_impl_trait_ids(decl, header, &mut ids);
3182 ItemKind::Impl(.., None, _, ref items) => {
3183 let mut ids = SmallVector::one(hir::ItemId { id: i.id });
3185 if let ImplItemKind::Method(ref sig, _) = item.node {
3186 self.lower_impl_trait_ids(&sig.decl, &sig.header, &mut ids);
3191 _ => SmallVector::one(hir::ItemId { id: i.id }),
3195 fn lower_item_id_use_tree(&mut self,
3198 vec: &mut SmallVector<hir::ItemId>)
3201 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3202 vec.push(hir::ItemId { id });
3203 self.lower_item_id_use_tree(nested, id, vec);
3205 UseTreeKind::Glob => {}
3206 UseTreeKind::Simple(_, id1, id2) => {
3207 for (_, &id) in self.expect_full_def_from_use(base_id)
3209 .zip([id1, id2].iter())
3211 vec.push(hir::ItemId { id });
3217 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3218 let mut name = i.ident.name;
3219 let mut vis = self.lower_visibility(&i.vis, None);
3220 let attrs = self.lower_attrs(&i.attrs);
3221 if let ItemKind::MacroDef(ref def) = i.node {
3222 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
3223 let body = self.lower_token_stream(def.stream());
3224 self.exported_macros.push(hir::MacroDef {
3237 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3239 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3252 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3253 let node_id = self.lower_node_id(i.id).node_id;
3254 let def_id = self.resolver.definitions().local_def_id(node_id);
3258 attrs: self.lower_attrs(&i.attrs),
3259 node: match i.node {
3260 ForeignItemKind::Fn(ref fdec, ref generics) => {
3261 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3264 AnonymousLifetimeMode::PassThrough,
3267 // Disallow impl Trait in foreign items
3268 this.lower_fn_decl(fdec, None, false, None),
3269 this.lower_fn_args_to_names(fdec),
3274 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3276 ForeignItemKind::Static(ref t, m) => {
3277 hir::ForeignItemKind::Static(self.lower_ty(t, ImplTraitContext::Disallowed), m)
3279 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3280 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3282 vis: self.lower_visibility(&i.vis, None),
3287 fn lower_method_sig(
3289 generics: &Generics,
3292 impl_trait_return_allow: bool,
3293 is_async: Option<NodeId>,
3294 ) -> (hir::Generics, hir::MethodSig) {
3295 let header = self.lower_fn_header(sig.header);
3296 let (generics, decl) = self.add_in_band_defs(
3299 AnonymousLifetimeMode::PassThrough,
3300 |this, idty| this.lower_fn_decl(
3302 Some((fn_def_id, idty)),
3303 impl_trait_return_allow,
3307 (generics, hir::MethodSig { header, decl })
3310 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3312 IsAuto::Yes => hir::IsAuto::Yes,
3313 IsAuto::No => hir::IsAuto::No,
3317 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3319 unsafety: self.lower_unsafety(h.unsafety),
3320 asyncness: self.lower_asyncness(h.asyncness),
3321 constness: self.lower_constness(h.constness),
3326 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3328 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3329 Unsafety::Normal => hir::Unsafety::Normal,
3333 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3335 Constness::Const => hir::Constness::Const,
3336 Constness::NotConst => hir::Constness::NotConst,
3340 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3342 IsAsync::Async { .. } => hir::IsAsync::Async,
3343 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3347 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3349 UnOp::Deref => hir::UnDeref,
3350 UnOp::Not => hir::UnNot,
3351 UnOp::Neg => hir::UnNeg,
3355 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3357 node: match b.node {
3358 BinOpKind::Add => hir::BinOpKind::Add,
3359 BinOpKind::Sub => hir::BinOpKind::Sub,
3360 BinOpKind::Mul => hir::BinOpKind::Mul,
3361 BinOpKind::Div => hir::BinOpKind::Div,
3362 BinOpKind::Rem => hir::BinOpKind::Rem,
3363 BinOpKind::And => hir::BinOpKind::And,
3364 BinOpKind::Or => hir::BinOpKind::Or,
3365 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3366 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3367 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3368 BinOpKind::Shl => hir::BinOpKind::Shl,
3369 BinOpKind::Shr => hir::BinOpKind::Shr,
3370 BinOpKind::Eq => hir::BinOpKind::Eq,
3371 BinOpKind::Lt => hir::BinOpKind::Lt,
3372 BinOpKind::Le => hir::BinOpKind::Le,
3373 BinOpKind::Ne => hir::BinOpKind::Ne,
3374 BinOpKind::Ge => hir::BinOpKind::Ge,
3375 BinOpKind::Gt => hir::BinOpKind::Gt,
3381 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3382 let node = match p.node {
3383 PatKind::Wild => hir::PatKind::Wild,
3384 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3385 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3386 // `None` can occur in body-less function signatures
3387 def @ None | def @ Some(Def::Local(_)) => {
3388 let canonical_id = match def {
3389 Some(Def::Local(id)) => id,
3392 hir::PatKind::Binding(
3393 self.lower_binding_mode(binding_mode),
3396 sub.as_ref().map(|x| self.lower_pat(x)),
3399 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3404 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3409 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3410 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3411 let qpath = self.lower_qpath(
3415 ParamMode::Optional,
3416 ImplTraitContext::Disallowed,
3418 hir::PatKind::TupleStruct(
3420 pats.iter().map(|x| self.lower_pat(x)).collect(),
3424 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3428 ParamMode::Optional,
3429 ImplTraitContext::Disallowed,
3431 PatKind::Struct(ref path, ref fields, etc) => {
3432 let qpath = self.lower_qpath(
3436 ParamMode::Optional,
3437 ImplTraitContext::Disallowed,
3444 node: hir::FieldPat {
3445 id: self.next_id().node_id,
3446 ident: f.node.ident,
3447 pat: self.lower_pat(&f.node.pat),
3448 is_shorthand: f.node.is_shorthand,
3452 hir::PatKind::Struct(qpath, fs, etc)
3454 PatKind::Tuple(ref elts, ddpos) => {
3455 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3457 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3458 PatKind::Ref(ref inner, mutbl) => {
3459 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3461 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3462 P(self.lower_expr(e1)),
3463 P(self.lower_expr(e2)),
3464 self.lower_range_end(end),
3466 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3467 before.iter().map(|x| self.lower_pat(x)).collect(),
3468 slice.as_ref().map(|x| self.lower_pat(x)),
3469 after.iter().map(|x| self.lower_pat(x)).collect(),
3471 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3472 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3475 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3484 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3486 RangeEnd::Included(_) => hir::RangeEnd::Included,
3487 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3491 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3492 let was_in_loop_condition = self.is_in_loop_condition;
3493 self.is_in_loop_condition = false;
3494 let was_in_anon_const = self.is_in_anon_const;
3495 self.is_in_anon_const = true;
3497 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3498 let anon_const = hir::AnonConst {
3501 body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3504 self.is_in_anon_const = was_in_anon_const;
3505 self.is_in_loop_condition = was_in_loop_condition;
3510 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3511 let kind = match e.node {
3512 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3513 ExprKind::ObsoleteInPlace(..) => {
3514 self.sess.abort_if_errors();
3515 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3517 ExprKind::Array(ref exprs) => {
3518 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3520 ExprKind::Repeat(ref expr, ref count) => {
3521 let expr = P(self.lower_expr(expr));
3522 let count = self.lower_anon_const(count);
3523 hir::ExprKind::Repeat(expr, count)
3525 ExprKind::Tup(ref elts) => {
3526 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3528 ExprKind::Call(ref f, ref args) => {
3529 let f = P(self.lower_expr(f));
3530 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3532 ExprKind::MethodCall(ref seg, ref args) => {
3533 let hir_seg = self.lower_path_segment(
3536 ParamMode::Optional,
3538 ParenthesizedGenericArgs::Err,
3539 ImplTraitContext::Disallowed,
3541 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3542 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3544 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3545 let binop = self.lower_binop(binop);
3546 let lhs = P(self.lower_expr(lhs));
3547 let rhs = P(self.lower_expr(rhs));
3548 hir::ExprKind::Binary(binop, lhs, rhs)
3550 ExprKind::Unary(op, ref ohs) => {
3551 let op = self.lower_unop(op);
3552 let ohs = P(self.lower_expr(ohs));
3553 hir::ExprKind::Unary(op, ohs)
3555 ExprKind::Lit(ref l) => hir::ExprKind::Lit(P((**l).clone())),
3556 ExprKind::Cast(ref expr, ref ty) => {
3557 let expr = P(self.lower_expr(expr));
3558 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3560 ExprKind::Type(ref expr, ref ty) => {
3561 let expr = P(self.lower_expr(expr));
3562 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3564 ExprKind::AddrOf(m, ref ohs) => {
3565 let m = self.lower_mutability(m);
3566 let ohs = P(self.lower_expr(ohs));
3567 hir::ExprKind::AddrOf(m, ohs)
3569 // More complicated than you might expect because the else branch
3570 // might be `if let`.
3571 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3572 let else_opt = else_opt.as_ref().map(|els| {
3574 ExprKind::IfLet(..) => {
3575 // wrap the if-let expr in a block
3576 let span = els.span;
3577 let els = P(self.lower_expr(els));
3578 let LoweredNodeId { node_id, hir_id } = self.next_id();
3579 let blk = P(hir::Block {
3584 rules: hir::DefaultBlock,
3586 targeted_by_break: false,
3587 recovered: blk.recovered,
3589 P(self.expr_block(blk, ThinVec::new()))
3591 _ => P(self.lower_expr(els)),
3595 let then_blk = self.lower_block(blk, false);
3596 let then_expr = self.expr_block(then_blk, ThinVec::new());
3598 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3600 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3601 hir::ExprKind::While(
3602 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3603 this.lower_block(body, false),
3604 this.lower_label(opt_label),
3607 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3608 hir::ExprKind::Loop(
3609 this.lower_block(body, false),
3610 this.lower_label(opt_label),
3611 hir::LoopSource::Loop,
3614 ExprKind::Catch(ref body) => {
3615 self.with_catch_scope(body.id, |this| {
3617 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3618 let mut block = this.lower_block(body, true).into_inner();
3619 let tail = block.expr.take().map_or_else(
3621 let LoweredNodeId { node_id, hir_id } = this.next_id();
3622 let span = this.sess.codemap().end_point(unstable_span);
3626 node: hir::ExprKind::Tup(hir_vec![]),
3627 attrs: ThinVec::new(),
3631 |x: P<hir::Expr>| x.into_inner(),
3633 block.expr = Some(this.wrap_in_try_constructor(
3634 "from_ok", tail, unstable_span));
3635 hir::ExprKind::Block(P(block), None)
3638 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3639 P(self.lower_expr(expr)),
3640 arms.iter().map(|x| self.lower_arm(x)).collect(),
3641 hir::MatchSource::Normal,
3643 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3644 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3645 this.with_new_scopes(|this| {
3646 let block = this.lower_block(block, false);
3647 this.expr_block(block, ThinVec::new())
3652 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3654 if let IsAsync::Async { closure_id, .. } = asyncness {
3655 let outer_decl = FnDecl {
3656 inputs: decl.inputs.clone(),
3657 output: FunctionRetTy::Default(fn_decl_span),
3660 // We need to lower the declaration outside the new scope, because we
3661 // have to conserve the state of being inside a loop condition for the
3662 // closure argument types.
3663 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3665 self.with_new_scopes(|this| {
3666 // FIXME(cramertj) allow `async` non-`move` closures with
3667 if capture_clause == CaptureBy::Ref &&
3668 !decl.inputs.is_empty()
3674 "`async` non-`move` closures with arguments \
3675 are not currently supported",
3677 .help("consider using `let` statements to manually capture \
3678 variables by reference before entering an \
3679 `async move` closure")
3683 // Transform `async |x: u8| -> X { ... }` into
3684 // `|x: u8| future_from_generator(|| -> X { ... })`
3685 let body_id = this.lower_body(Some(&outer_decl), |this| {
3686 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3689 let async_body = this.make_async_expr(
3690 capture_clause, closure_id, async_ret_ty,
3692 this.with_new_scopes(|this| this.lower_expr(body))
3694 this.expr(fn_decl_span, async_body, ThinVec::new())
3696 hir::ExprKind::Closure(
3697 this.lower_capture_clause(capture_clause),
3705 // Lower outside new scope to preserve `is_in_loop_condition`.
3706 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3708 self.with_new_scopes(|this| {
3709 let mut is_generator = false;
3710 let body_id = this.lower_body(Some(decl), |this| {
3711 let e = this.lower_expr(body);
3712 is_generator = this.is_generator;
3715 let generator_option = if is_generator {
3716 if !decl.inputs.is_empty() {
3721 "generators cannot have explicit arguments"
3723 this.sess.abort_if_errors();
3725 Some(match movability {
3726 Movability::Movable => hir::GeneratorMovability::Movable,
3727 Movability::Static => hir::GeneratorMovability::Static,
3730 if movability == Movability::Static {
3735 "closures cannot be static"
3740 hir::ExprKind::Closure(
3741 this.lower_capture_clause(capture_clause),
3750 ExprKind::Block(ref blk, opt_label) => {
3751 hir::ExprKind::Block(self.lower_block(blk,
3752 opt_label.is_some()),
3753 self.lower_label(opt_label))
3755 ExprKind::Assign(ref el, ref er) => {
3756 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3758 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
3759 self.lower_binop(op),
3760 P(self.lower_expr(el)),
3761 P(self.lower_expr(er)),
3763 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
3764 ExprKind::Index(ref el, ref er) => {
3765 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
3767 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3768 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3769 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3770 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3771 let id = self.next_id();
3772 let e1 = self.lower_expr(e1);
3773 let e2 = self.lower_expr(e2);
3774 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], None, false));
3775 let ty = P(self.ty_path(id, span, hir::QPath::Resolved(None, ty_path)));
3776 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3777 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3778 let new = P(self.expr(span, hir::ExprKind::Path(new_path), ThinVec::new()));
3779 hir::ExprKind::Call(new, hir_vec![e1, e2])
3781 ExprKind::Range(ref e1, ref e2, lims) => {
3782 use syntax::ast::RangeLimits::*;
3784 let path = match (e1, e2, lims) {
3785 (&None, &None, HalfOpen) => "RangeFull",
3786 (&Some(..), &None, HalfOpen) => "RangeFrom",
3787 (&None, &Some(..), HalfOpen) => "RangeTo",
3788 (&Some(..), &Some(..), HalfOpen) => "Range",
3789 (&None, &Some(..), Closed) => "RangeToInclusive",
3790 (&Some(..), &Some(..), Closed) => unreachable!(),
3791 (_, &None, Closed) => self.diagnostic()
3792 .span_fatal(e.span, "inclusive range with no end")
3796 let fields = e1.iter()
3797 .map(|e| ("start", e))
3798 .chain(e2.iter().map(|e| ("end", e)))
3800 let expr = P(self.lower_expr(&e));
3802 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3803 let ident = Ident::new(Symbol::intern(s), unstable_span);
3804 self.field(ident, expr, unstable_span)
3806 .collect::<P<[hir::Field]>>();
3808 let is_unit = fields.is_empty();
3810 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3811 let struct_path = iter::once("ops")
3812 .chain(iter::once(path))
3813 .collect::<Vec<_>>();
3814 let struct_path = self.std_path(unstable_span, &struct_path, None, is_unit);
3815 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3817 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3823 hir::ExprKind::Path(struct_path)
3825 hir::ExprKind::Struct(struct_path, fields, None)
3827 span: unstable_span,
3828 attrs: e.attrs.clone(),
3831 ExprKind::Path(ref qself, ref path) => hir::ExprKind::Path(self.lower_qpath(
3835 ParamMode::Optional,
3836 ImplTraitContext::Disallowed,
3838 ExprKind::Break(opt_label, ref opt_expr) => {
3839 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3842 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3845 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3847 hir::ExprKind::Break(
3849 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3852 ExprKind::Continue(opt_label) => {
3853 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
3856 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3859 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3862 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
3863 ExprKind::InlineAsm(ref asm) => {
3864 let hir_asm = hir::InlineAsm {
3865 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3866 outputs: asm.outputs
3868 .map(|out| hir::InlineAsmOutput {
3869 constraint: out.constraint.clone(),
3871 is_indirect: out.is_indirect,
3874 asm: asm.asm.clone(),
3875 asm_str_style: asm.asm_str_style,
3876 clobbers: asm.clobbers.clone().into(),
3877 volatile: asm.volatile,
3878 alignstack: asm.alignstack,
3879 dialect: asm.dialect,
3882 let outputs = asm.outputs
3884 .map(|out| self.lower_expr(&out.expr))
3886 let inputs = asm.inputs
3888 .map(|&(_, ref input)| self.lower_expr(input))
3890 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
3892 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
3897 ParamMode::Optional,
3898 ImplTraitContext::Disallowed,
3900 fields.iter().map(|x| self.lower_field(x)).collect(),
3901 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3903 ExprKind::Paren(ref ex) => {
3904 let mut ex = self.lower_expr(ex);
3905 // include parens in span, but only if it is a super-span.
3906 if e.span.contains(ex.span) {
3909 // merge attributes into the inner expression.
3910 let mut attrs = e.attrs.clone();
3911 attrs.extend::<Vec<_>>(ex.attrs.into());
3916 ExprKind::Yield(ref opt_expr) => {
3917 self.is_generator = true;
3920 .map(|x| self.lower_expr(x))
3922 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
3924 hir::ExprKind::Yield(P(expr))
3927 // Desugar ExprIfLet
3928 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3929 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3932 // match <sub_expr> {
3934 // _ => [<else_opt> | ()]
3937 let mut arms = vec![];
3939 // `<pat> => <body>`
3941 let body = self.lower_block(body, false);
3942 let body_expr = P(self.expr_block(body, ThinVec::new()));
3943 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3944 arms.push(self.arm(pats, body_expr));
3947 // _ => [<else_opt>|()]
3949 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3950 let wildcard_pattern = self.pat_wild(e.span);
3951 let body = if let Some(else_expr) = wildcard_arm {
3952 P(self.lower_expr(else_expr))
3954 self.expr_tuple(e.span, hir_vec![])
3956 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3959 let contains_else_clause = else_opt.is_some();
3961 let sub_expr = P(self.lower_expr(sub_expr));
3963 hir::ExprKind::Match(
3966 hir::MatchSource::IfLetDesugar {
3967 contains_else_clause,
3972 // Desugar ExprWhileLet
3973 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3974 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3977 // [opt_ident]: loop {
3978 // match <sub_expr> {
3984 // Note that the block AND the condition are evaluated in the loop scope.
3985 // This is done to allow `break` from inside the condition of the loop.
3986 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3988 this.lower_block(body, false),
3989 this.expr_break(e.span, ThinVec::new()),
3990 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3994 // `<pat> => <body>`
3996 let body_expr = P(self.expr_block(body, ThinVec::new()));
3997 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3998 self.arm(pats, body_expr)
4003 let pat_under = self.pat_wild(e.span);
4004 self.arm(hir_vec![pat_under], break_expr)
4007 // `match <sub_expr> { ... }`
4008 let arms = hir_vec![pat_arm, break_arm];
4009 let match_expr = self.expr(
4011 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4015 // `[opt_ident]: loop { ... }`
4016 let loop_block = P(self.block_expr(P(match_expr)));
4017 let loop_expr = hir::ExprKind::Loop(
4019 self.lower_label(opt_label),
4020 hir::LoopSource::WhileLet,
4022 // add attributes to the outer returned expr node
4026 // Desugar ExprForLoop
4027 // From: `[opt_ident]: for <pat> in <head> <body>`
4028 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4032 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4034 // [opt_ident]: loop {
4036 // match ::std::iter::Iterator::next(&mut iter) {
4037 // ::std::option::Option::Some(val) => __next = val,
4038 // ::std::option::Option::None => break
4040 // let <pat> = __next;
4041 // StmtKind::Expr(<body>);
4049 let head = self.lower_expr(head);
4050 let head_sp = head.span;
4052 let iter = self.str_to_ident("iter");
4054 let next_ident = self.str_to_ident("__next");
4055 let next_sp = self.allow_internal_unstable(
4056 CompilerDesugaringKind::ForLoop,
4059 let next_pat = self.pat_ident_binding_mode(
4062 hir::BindingAnnotation::Mutable,
4065 // `::std::option::Option::Some(val) => next = val`
4067 let val_ident = self.str_to_ident("val");
4068 let val_pat = self.pat_ident(pat.span, val_ident);
4069 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4070 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4071 let assign = P(self.expr(
4073 hir::ExprKind::Assign(next_expr, val_expr),
4076 let some_pat = self.pat_some(pat.span, val_pat);
4077 self.arm(hir_vec![some_pat], assign)
4080 // `::std::option::Option::None => break`
4083 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4084 let pat = self.pat_none(e.span);
4085 self.arm(hir_vec![pat], break_expr)
4090 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
4092 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4094 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4095 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4096 let next_path = &["iter", "Iterator", "next"];
4097 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4098 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4099 let arms = hir_vec![pat_arm, break_arm];
4103 hir::ExprKind::Match(
4106 hir::MatchSource::ForLoopDesugar
4111 let match_stmt = respan(
4113 hir::StmtKind::Expr(match_expr, self.next_id().node_id)
4116 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4120 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
4122 // `let <pat> = __next`
4123 let pat = self.lower_pat(pat);
4124 let pat_let = self.stmt_let_pat(
4128 hir::LocalSource::ForLoopDesugar,
4131 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4132 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4133 let body_stmt = respan(
4135 hir::StmtKind::Expr(body_expr, self.next_id().node_id)
4138 let loop_block = P(self.block_all(
4140 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4144 // `[opt_ident]: loop { ... }`
4145 let loop_expr = hir::ExprKind::Loop(
4147 self.lower_label(opt_label),
4148 hir::LoopSource::ForLoop,
4150 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4151 let loop_expr = P(hir::Expr {
4156 attrs: ThinVec::new(),
4159 // `mut iter => { ... }`
4160 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4162 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4163 let into_iter_expr = {
4164 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4165 let into_iter = P(self.expr_std_path(
4166 head_sp, into_iter_path, None, ThinVec::new()));
4167 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4170 let match_expr = P(self.expr_match(
4174 hir::MatchSource::ForLoopDesugar,
4177 // `{ let _result = ...; _result }`
4178 // underscore prevents an unused_variables lint if the head diverges
4179 let result_ident = self.str_to_ident("_result");
4180 let (let_stmt, let_stmt_binding) =
4181 self.stmt_let(e.span, false, result_ident, match_expr);
4183 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4184 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4185 // add the attributes to the outer returned expr node
4186 return self.expr_block(block, e.attrs.clone());
4189 // Desugar ExprKind::Try
4191 ExprKind::Try(ref sub_expr) => {
4194 // match Try::into_result(<expr>) {
4195 // Ok(val) => #[allow(unreachable_code)] val,
4196 // Err(err) => #[allow(unreachable_code)]
4197 // // If there is an enclosing `catch {...}`
4198 // break 'catch_target Try::from_error(From::from(err)),
4200 // return Try::from_error(From::from(err)),
4204 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4206 // Try::into_result(<expr>)
4209 let sub_expr = self.lower_expr(sub_expr);
4211 let path = &["ops", "Try", "into_result"];
4212 let path = P(self.expr_std_path(
4213 unstable_span, path, None, ThinVec::new()));
4214 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4217 // #[allow(unreachable_code)]
4219 // allow(unreachable_code)
4221 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4222 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4223 let uc_nested = attr::mk_nested_word_item(uc_ident);
4224 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4226 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4228 let attrs = vec![attr];
4230 // Ok(val) => #[allow(unreachable_code)] val,
4232 let val_ident = self.str_to_ident("val");
4233 let val_pat = self.pat_ident(e.span, val_ident);
4234 let val_expr = P(self.expr_ident_with_attrs(
4238 ThinVec::from(attrs.clone()),
4240 let ok_pat = self.pat_ok(e.span, val_pat);
4242 self.arm(hir_vec![ok_pat], val_expr)
4245 // Err(err) => #[allow(unreachable_code)]
4246 // return Try::from_error(From::from(err)),
4248 let err_ident = self.str_to_ident("err");
4249 let err_local = self.pat_ident(e.span, err_ident);
4251 let path = &["convert", "From", "from"];
4252 let from = P(self.expr_std_path(
4253 e.span, path, None, ThinVec::new()));
4254 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4256 self.expr_call(e.span, from, hir_vec![err_expr])
4259 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4260 let thin_attrs = ThinVec::from(attrs);
4261 let catch_scope = self.catch_scopes.last().map(|x| *x);
4262 let ret_expr = if let Some(catch_node) = catch_scope {
4265 hir::ExprKind::Break(
4268 target_id: Ok(catch_node),
4270 Some(from_err_expr),
4275 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4278 let err_pat = self.pat_err(e.span, err_local);
4279 self.arm(hir_vec![err_pat], ret_expr)
4282 hir::ExprKind::Match(
4284 hir_vec![err_arm, ok_arm],
4285 hir::MatchSource::TryDesugar,
4289 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4292 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4299 attrs: e.attrs.clone(),
4303 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
4304 SmallVector::one(match s.node {
4305 StmtKind::Local(ref l) => Spanned {
4306 node: hir::StmtKind::Decl(
4308 node: hir::DeclKind::Local(self.lower_local(l)),
4311 self.lower_node_id(s.id).node_id,
4315 StmtKind::Item(ref it) => {
4316 // Can only use the ID once.
4317 let mut id = Some(s.id);
4318 return self.lower_item_id(it)
4320 .map(|item_id| Spanned {
4321 node: hir::StmtKind::Decl(
4323 node: hir::DeclKind::Item(item_id),
4327 .map(|id| self.lower_node_id(id).node_id)
4328 .unwrap_or_else(|| self.next_id().node_id),
4334 StmtKind::Expr(ref e) => Spanned {
4335 node: hir::StmtKind::Expr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4338 StmtKind::Semi(ref e) => Spanned {
4339 node: hir::StmtKind::Semi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4342 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4346 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4348 CaptureBy::Value => hir::CaptureByValue,
4349 CaptureBy::Ref => hir::CaptureByRef,
4353 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4354 /// the address space of that item instead of the item currently being
4355 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4356 /// lower a `Visibility` value although we haven't lowered the owning
4357 /// `ImplItem` in question yet.
4358 fn lower_visibility(
4361 explicit_owner: Option<NodeId>,
4362 ) -> hir::Visibility {
4363 let node = match v.node {
4364 VisibilityKind::Public => hir::VisibilityKind::Public,
4365 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4366 VisibilityKind::Restricted { ref path, id } => hir::VisibilityKind::Restricted {
4367 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4368 id: if let Some(owner) = explicit_owner {
4369 self.lower_node_id_with_owner(id, owner).node_id
4371 self.lower_node_id(id).node_id
4374 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4376 respan(v.span, node)
4379 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4381 Defaultness::Default => hir::Defaultness::Default {
4382 has_value: has_value,
4384 Defaultness::Final => {
4386 hir::Defaultness::Final
4391 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4393 BlockCheckMode::Default => hir::DefaultBlock,
4394 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4398 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4400 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4401 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4402 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4403 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4407 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4409 CompilerGenerated => hir::CompilerGenerated,
4410 UserProvided => hir::UserProvided,
4414 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4416 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4417 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4421 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4423 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4424 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4428 // Helper methods for building HIR.
4430 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4439 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4441 id: self.next_id().node_id,
4445 is_shorthand: false,
4449 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4450 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4451 P(self.expr(span, expr_break, attrs))
4458 args: hir::HirVec<hir::Expr>,
4460 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4463 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4464 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4467 fn expr_ident_with_attrs(
4472 attrs: ThinVec<Attribute>,
4474 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4478 def: Def::Local(binding),
4479 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4483 self.expr(span, expr_path, attrs)
4486 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4487 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4493 components: &[&str],
4494 params: Option<P<hir::GenericArgs>>,
4495 attrs: ThinVec<Attribute>,
4497 let path = self.std_path(span, components, params, true);
4500 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4509 arms: hir::HirVec<hir::Arm>,
4510 source: hir::MatchSource,
4512 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4515 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4516 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4519 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4520 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4523 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4524 let LoweredNodeId { node_id, hir_id } = self.next_id();
4537 ex: Option<P<hir::Expr>>,
4539 source: hir::LocalSource,
4541 let LoweredNodeId { node_id, hir_id } = self.next_id();
4543 let local = P(hir::Local {
4550 attrs: ThinVec::new(),
4553 let decl = respan(sp, hir::DeclKind::Local(local));
4554 respan(sp, hir::StmtKind::Decl(P(decl), self.next_id().node_id))
4563 ) -> (hir::Stmt, NodeId) {
4564 let pat = if mutbl {
4565 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4567 self.pat_ident(sp, ident)
4569 let pat_id = pat.id;
4571 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4576 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4577 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4583 stmts: hir::HirVec<hir::Stmt>,
4584 expr: Option<P<hir::Expr>>,
4586 let LoweredNodeId { node_id, hir_id } = self.next_id();
4593 rules: hir::DefaultBlock,
4595 targeted_by_break: false,
4600 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4601 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4604 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4605 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4608 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4609 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4612 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4613 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4619 components: &[&str],
4620 subpats: hir::HirVec<P<hir::Pat>>,
4622 let path = self.std_path(span, components, None, true);
4623 let qpath = hir::QPath::Resolved(None, P(path));
4624 let pt = if subpats.is_empty() {
4625 hir::PatKind::Path(qpath)
4627 hir::PatKind::TupleStruct(qpath, subpats, None)
4632 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4633 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4636 fn pat_ident_binding_mode(
4640 bm: hir::BindingAnnotation,
4642 let LoweredNodeId { node_id, hir_id } = self.next_id();
4647 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4652 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4653 self.pat(span, hir::PatKind::Wild)
4656 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4657 let LoweredNodeId { node_id, hir_id } = self.next_id();
4666 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4667 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4668 /// The path is also resolved according to `is_value`.
4672 components: &[&str],
4673 params: Option<P<hir::GenericArgs>>,
4677 .resolve_str_path(span, self.crate_root, components, params, is_value)
4680 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4682 let node = match qpath {
4683 hir::QPath::Resolved(None, path) => {
4684 // Turn trait object paths into `TyKind::TraitObject` instead.
4685 if let Def::Trait(_) = path.def {
4686 let principal = hir::PolyTraitRef {
4687 bound_generic_params: hir::HirVec::new(),
4688 trait_ref: hir::TraitRef {
4689 path: path.and_then(|path| path),
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);