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 use middle::cstore::CrateStore;
52 use rustc_data_structures::indexed_vec::IndexVec;
54 use util::common::FN_OUTPUT_NAME;
55 use util::nodemap::{DefIdMap, FxHashMap, NodeMap};
57 use std::collections::{BTreeMap, HashSet};
65 use syntax::ext::hygiene::{Mark, SyntaxContext};
66 use syntax::print::pprust;
68 use syntax::codemap::{self, respan, CompilerDesugaringKind, Spanned};
69 use syntax::std_inject;
70 use syntax::symbol::{keywords, Symbol};
71 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
72 use syntax::parse::token::Token;
73 use syntax::util::small_vector::SmallVector;
74 use syntax::visit::{self, Visitor};
77 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
79 pub struct LoweringContext<'a> {
80 crate_root: Option<&'static str>,
82 // Use to assign ids to hir nodes that do not directly correspond to an ast node
85 cstore: &'a CrateStore,
87 resolver: &'a mut Resolver,
88 name_map: FxHashMap<Ident, Name>,
90 /// The items being lowered are collected here.
91 items: BTreeMap<NodeId, hir::Item>,
93 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
94 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
95 bodies: BTreeMap<hir::BodyId, hir::Body>,
96 exported_macros: Vec<hir::MacroDef>,
98 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
99 trait_auto_impl: BTreeMap<DefId, NodeId>,
103 catch_scopes: Vec<NodeId>,
104 loop_scopes: Vec<NodeId>,
105 is_in_loop_condition: bool,
106 is_in_trait_impl: bool,
108 /// What to do when we encounter either an "anonymous lifetime
109 /// reference". The term "anonymous" is meant to encompass both
110 /// `'_` lifetimes as well as fully elided cases where nothing is
111 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
112 anonymous_lifetime_mode: AnonymousLifetimeMode,
114 // This is a list of in-band type definitions being generated by
115 // Argument-position `impl Trait`.
116 // When traversing a signature such as `fn foo(x: impl Trait)`,
117 // we record `impl Trait` as a new type parameter, then later
118 // add it on to `foo`s generics.
119 in_band_ty_params: Vec<hir::GenericParam>,
121 // Used to create lifetime definitions from in-band lifetime usages.
122 // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
123 // When a named lifetime is encountered in a function or impl header and
124 // has not been defined
125 // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
126 // to this list. The results of this list are then added to the list of
127 // lifetime definitions in the corresponding impl or function generics.
128 lifetimes_to_define: Vec<(Span, ParamName)>,
130 // Whether or not in-band lifetimes are being collected. This is used to
131 // indicate whether or not we're in a place where new lifetimes will result
132 // in in-band lifetime definitions, such a function or an impl header.
133 // This will always be false unless the `in_band_lifetimes` feature is
135 is_collecting_in_band_lifetimes: bool,
137 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
138 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
139 // against this list to see if it is already in-scope, or if a definition
140 // needs to be created for it.
141 in_scope_lifetimes: Vec<Name>,
143 type_def_lifetime_params: DefIdMap<usize>,
145 current_hir_id_owner: Vec<(DefIndex, u32)>,
146 item_local_id_counters: NodeMap<u32>,
147 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
151 /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
152 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
154 /// Obtain the resolution for a node id
155 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
157 /// Obtain the possible resolutions for the given `use` statement.
158 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
160 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
161 /// This should only return `None` during testing.
162 fn definitions(&mut self) -> &mut Definitions;
164 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
165 /// it based on `is_value`.
169 crate_root: Option<&str>,
171 params: Option<P<hir::GenericArgs>>,
176 #[derive(Clone, Copy, Debug)]
177 enum ImplTraitContext {
178 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
179 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
180 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
182 /// We store a DefId here so we can look up necessary information later
185 /// Treat `impl Trait` as shorthand for a new universal existential parameter.
186 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
187 /// equivalent to a fresh existential parameter like `abstract type T; fn foo() -> T`.
189 /// We store a DefId here so we can look up necessary information later
192 /// `impl Trait` is not accepted in this position.
199 dep_graph: &DepGraph,
201 resolver: &mut Resolver,
203 // We're constructing the HIR here; we don't care what we will
204 // read, since we haven't even constructed the *input* to
206 dep_graph.assert_ignored();
209 crate_root: std_inject::injected_crate_name(),
213 name_map: FxHashMap(),
214 items: BTreeMap::new(),
215 trait_items: BTreeMap::new(),
216 impl_items: BTreeMap::new(),
217 bodies: BTreeMap::new(),
218 trait_impls: BTreeMap::new(),
219 trait_auto_impl: BTreeMap::new(),
220 exported_macros: Vec::new(),
221 catch_scopes: Vec::new(),
222 loop_scopes: Vec::new(),
223 is_in_loop_condition: false,
224 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
225 type_def_lifetime_params: DefIdMap(),
226 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
227 item_local_id_counters: NodeMap(),
228 node_id_to_hir_id: IndexVec::new(),
230 is_in_trait_impl: false,
231 in_band_ty_params: Vec::new(),
232 lifetimes_to_define: Vec::new(),
233 is_collecting_in_band_lifetimes: false,
234 in_scope_lifetimes: Vec::new(),
238 #[derive(Copy, Clone, PartialEq, Eq)]
240 /// Any path in a type context.
242 /// The `module::Type` in `module::Type::method` in an expression.
247 struct LoweredNodeId {
252 enum ParenthesizedGenericArgs {
258 /// What to do when we encounter an **anonymous** lifetime
259 /// reference. Anonymous lifetime references come in two flavors. You
260 /// have implicit, or fully elided, references to lifetimes, like the
261 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
262 /// or `Ref<'_, T>`. These often behave the same, but not always:
264 /// - certain usages of implicit references are deprecated, like
265 /// `Ref<T>`, and we sometimes just give hard errors in those cases
267 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
268 /// the same as `Box<dyn Foo + '_>`.
270 /// We describe the effects of the various modes in terms of three cases:
272 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
273 /// of a `&` (e.g., the missing lifetime in something like `&T`)
274 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
275 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
276 /// elided bounds follow special rules. Note that this only covers
277 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
278 /// '_>` is a case of "modern" elision.
279 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
280 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
281 /// non-deprecated equivalent.
283 /// Currently, the handling of lifetime elision is somewhat spread out
284 /// between HIR lowering and -- as described below -- the
285 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
286 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
287 /// everything into HIR lowering.
288 #[derive(Copy, Clone)]
289 enum AnonymousLifetimeMode {
290 /// For **Modern** cases, create a new anonymous region parameter
291 /// and reference that.
293 /// For **Dyn Bound** cases, pass responsibility to
294 /// `resolve_lifetime` code.
296 /// For **Deprecated** cases, report an error.
299 /// Pass responsibility to `resolve_lifetime` code for all cases.
303 impl<'a> LoweringContext<'a> {
304 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
305 /// Full-crate AST visitor that inserts into a fresh
306 /// `LoweringContext` any information that may be
307 /// needed from arbitrary locations in the crate.
308 /// E.g. The number of lifetime generic parameters
309 /// declared for every type and trait definition.
310 struct MiscCollector<'lcx, 'interner: 'lcx> {
311 lctx: &'lcx mut LoweringContext<'interner>,
314 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
315 fn visit_item(&mut self, item: &'lcx Item) {
316 self.lctx.allocate_hir_id_counter(item.id, item);
319 ItemKind::Struct(_, ref generics)
320 | ItemKind::Union(_, ref generics)
321 | ItemKind::Enum(_, ref generics)
322 | ItemKind::Ty(_, ref generics)
323 | ItemKind::Trait(_, _, ref generics, ..) => {
324 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
328 .filter(|param| match param.kind {
329 ast::GenericParamKind::Lifetime { .. } => true,
333 self.lctx.type_def_lifetime_params.insert(def_id, count);
337 visit::walk_item(self, item);
340 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
341 self.lctx.allocate_hir_id_counter(item.id, item);
342 visit::walk_trait_item(self, item);
345 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
346 self.lctx.allocate_hir_id_counter(item.id, item);
347 visit::walk_impl_item(self, item);
351 struct ItemLowerer<'lcx, 'interner: 'lcx> {
352 lctx: &'lcx mut LoweringContext<'interner>,
355 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
356 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
358 F: FnOnce(&mut Self),
360 let old = self.lctx.is_in_trait_impl;
361 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
367 self.lctx.is_in_trait_impl = old;
371 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
372 fn visit_item(&mut self, item: &'lcx Item) {
373 let mut item_lowered = true;
374 self.lctx.with_hir_id_owner(item.id, |lctx| {
375 if let Some(hir_item) = lctx.lower_item(item) {
376 lctx.items.insert(item.id, hir_item);
378 item_lowered = false;
383 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
384 hir::Item_::ItemImpl(_, _, _, ref generics, ..)
385 | hir::Item_::ItemTrait(_, _, ref generics, ..) => {
386 generics.params.clone()
391 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
392 let this = &mut ItemLowerer { lctx: this };
393 if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
394 this.with_trait_impl_ref(opt_trait_ref, |this| {
395 visit::walk_item(this, item)
398 visit::walk_item(this, item);
404 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
405 self.lctx.with_hir_id_owner(item.id, |lctx| {
406 let id = hir::TraitItemId { node_id: item.id };
407 let hir_item = lctx.lower_trait_item(item);
408 lctx.trait_items.insert(id, hir_item);
411 visit::walk_trait_item(self, item);
414 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
415 self.lctx.with_hir_id_owner(item.id, |lctx| {
416 let id = hir::ImplItemId { node_id: item.id };
417 let hir_item = lctx.lower_impl_item(item);
418 lctx.impl_items.insert(id, hir_item);
420 visit::walk_impl_item(self, item);
424 self.lower_node_id(CRATE_NODE_ID);
425 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
427 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
428 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
430 let module = self.lower_mod(&c.module);
431 let attrs = self.lower_attrs(&c.attrs);
432 let body_ids = body_ids(&self.bodies);
436 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
442 exported_macros: hir::HirVec::from(self.exported_macros),
444 trait_items: self.trait_items,
445 impl_items: self.impl_items,
448 trait_impls: self.trait_impls,
449 trait_auto_impl: self.trait_auto_impl,
453 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
454 if self.item_local_id_counters.insert(owner, 0).is_some() {
456 "Tried to allocate item_local_id_counter for {:?} twice",
460 // Always allocate the first HirId for the owner itself
461 self.lower_node_id_with_owner(owner, owner)
464 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
466 F: FnOnce(&mut Self) -> hir::HirId,
468 if ast_node_id == DUMMY_NODE_ID {
469 return LoweredNodeId {
470 node_id: DUMMY_NODE_ID,
471 hir_id: hir::DUMMY_HIR_ID,
475 let min_size = ast_node_id.as_usize() + 1;
477 if min_size > self.node_id_to_hir_id.len() {
478 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
481 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
483 if existing_hir_id == hir::DUMMY_HIR_ID {
484 // Generate a new HirId
485 let hir_id = alloc_hir_id(self);
486 self.node_id_to_hir_id[ast_node_id] = hir_id;
488 node_id: ast_node_id,
493 node_id: ast_node_id,
494 hir_id: existing_hir_id,
499 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
501 F: FnOnce(&mut Self) -> T,
503 let counter = self.item_local_id_counters
504 .insert(owner, HIR_ID_COUNTER_LOCKED)
505 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
506 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
507 self.current_hir_id_owner.push((def_index, counter));
509 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
511 debug_assert!(def_index == new_def_index);
512 debug_assert!(new_counter >= counter);
514 let prev = self.item_local_id_counters
515 .insert(owner, new_counter)
517 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
521 /// This method allocates a new HirId for the given NodeId and stores it in
522 /// the LoweringContext's NodeId => HirId map.
523 /// Take care not to call this method if the resulting HirId is then not
524 /// actually used in the HIR, as that would trigger an assertion in the
525 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
526 /// properly. Calling the method twice with the same NodeId is fine though.
527 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
528 self.lower_node_id_generic(ast_node_id, |this| {
529 let &mut (def_index, ref mut local_id_counter) =
530 this.current_hir_id_owner.last_mut().unwrap();
531 let local_id = *local_id_counter;
532 *local_id_counter += 1;
535 local_id: hir::ItemLocalId(local_id),
540 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
541 self.lower_node_id_generic(ast_node_id, |this| {
542 let local_id_counter = this
543 .item_local_id_counters
545 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
546 let local_id = *local_id_counter;
548 // We want to be sure not to modify the counter in the map while it
549 // is also on the stack. Otherwise we'll get lost updates when writing
550 // back from the stack to the map.
551 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
553 *local_id_counter += 1;
557 .opt_def_index(owner)
558 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
559 that do not belong to the current owner");
563 local_id: hir::ItemLocalId(local_id),
568 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
569 let body = hir::Body {
570 arguments: decl.map_or(hir_vec![], |decl| {
571 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
573 is_generator: self.is_generator,
577 self.bodies.insert(id, body);
581 fn next_id(&mut self) -> LoweredNodeId {
582 self.lower_node_id(self.sess.next_node_id())
585 fn expect_full_def(&mut self, id: NodeId) -> Def {
586 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
587 if pr.unresolved_segments() != 0 {
588 bug!("path not fully resolved: {:?}", pr);
594 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item=Def> {
595 self.resolver.get_import(id).present_items().map(|pr| {
596 if pr.unresolved_segments() != 0 {
597 bug!("path not fully resolved: {:?}", pr);
603 fn diagnostic(&self) -> &errors::Handler {
604 self.sess.diagnostic()
607 fn str_to_ident(&self, s: &'static str) -> Name {
611 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
612 let mark = Mark::fresh(Mark::root());
613 mark.set_expn_info(codemap::ExpnInfo {
615 def_site: Some(span),
616 format: codemap::CompilerDesugaring(reason),
617 allow_internal_unstable: true,
618 allow_internal_unsafe: false,
619 edition: codemap::hygiene::default_edition(),
621 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
624 fn with_anonymous_lifetime_mode<R>(
626 anonymous_lifetime_mode: AnonymousLifetimeMode,
627 op: impl FnOnce(&mut Self) -> R,
629 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
630 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
631 let result = op(self);
632 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
636 /// Creates a new hir::GenericParam for every new lifetime and
637 /// type parameter encountered while evaluating `f`. Definitions
638 /// are created with the parent provided. If no `parent_id` is
639 /// provided, no definitions will be returned.
641 /// Presuming that in-band lifetimes are enabled, then
642 /// `self.anonymous_lifetime_mode` will be updated to match the
643 /// argument while `f` is running (and restored afterwards).
644 fn collect_in_band_defs<T, F>(
647 anonymous_lifetime_mode: AnonymousLifetimeMode,
649 ) -> (Vec<hir::GenericParam>, T)
651 F: FnOnce(&mut LoweringContext) -> T,
653 assert!(!self.is_collecting_in_band_lifetimes);
654 assert!(self.lifetimes_to_define.is_empty());
655 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
657 self.is_collecting_in_band_lifetimes = self.sess.features_untracked().in_band_lifetimes;
658 if self.is_collecting_in_band_lifetimes {
659 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
662 assert!(self.in_band_ty_params.is_empty());
665 self.is_collecting_in_band_lifetimes = false;
666 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
668 let in_band_ty_params = self.in_band_ty_params.split_off(0);
669 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
671 let params = lifetimes_to_define
673 .map(|(span, hir_name)| {
674 let def_node_id = self.next_id().node_id;
676 // Get the name we'll use to make the def-path. Note
677 // that collisions are ok here and this shouldn't
678 // really show up for end-user.
679 let str_name = match hir_name {
680 ParamName::Plain(name) => name.as_str(),
681 ParamName::Fresh(_) => keywords::UnderscoreLifetime.name().as_str(),
684 // Add a definition for the in-band lifetime def
685 self.resolver.definitions().create_def_with_parent(
688 DefPathData::LifetimeParam(str_name.as_interned_str()),
689 DefIndexAddressSpace::High,
700 pure_wrt_drop: false,
701 kind: hir::GenericParamKind::Lifetime { in_band: true }
704 .chain(in_band_ty_params.into_iter())
710 /// When there is a reference to some lifetime `'a`, and in-band
711 /// lifetimes are enabled, then we want to push that lifetime into
712 /// the vector of names to define later. In that case, it will get
713 /// added to the appropriate generics.
714 fn maybe_collect_in_band_lifetime(&mut self, span: Span, name: Name) {
715 if !self.is_collecting_in_band_lifetimes {
719 if self.in_scope_lifetimes.contains(&name) {
723 let hir_name = ParamName::Plain(name);
725 if self.lifetimes_to_define.iter().any(|(_, lt_name)| *lt_name == hir_name) {
729 self.lifetimes_to_define.push((span, hir_name));
732 /// When we have either an elided or `'_` lifetime in an impl
733 /// header, we convert it to
734 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
735 assert!(self.is_collecting_in_band_lifetimes);
736 let index = self.lifetimes_to_define.len();
737 let hir_name = ParamName::Fresh(index);
738 self.lifetimes_to_define.push((span, hir_name));
742 // Evaluates `f` with the lifetimes in `params` in-scope.
743 // This is used to track which lifetimes have already been defined, and
744 // which are new in-band lifetimes that need to have a definition created
746 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &Vec<GenericParam>, f: F) -> T
748 F: FnOnce(&mut LoweringContext) -> T,
750 let old_len = self.in_scope_lifetimes.len();
751 let lt_def_names = params.iter().filter_map(|param| match param.kind {
752 GenericParamKind::Lifetime { .. } => Some(param.ident.name),
755 self.in_scope_lifetimes.extend(lt_def_names);
759 self.in_scope_lifetimes.truncate(old_len);
763 // Same as the method above, but accepts `hir::GenericParam`s
764 // instead of `ast::GenericParam`s.
765 // This should only be used with generics that have already had their
766 // in-band lifetimes added. In practice, this means that this function is
767 // only used when lowering a child item of a trait or impl.
768 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
769 params: &HirVec<hir::GenericParam>,
772 F: FnOnce(&mut LoweringContext) -> T,
774 let old_len = self.in_scope_lifetimes.len();
775 let lt_def_names = params.iter().filter_map(|param| match param.kind {
776 hir::GenericParamKind::Lifetime { .. } => Some(param.name.name()),
779 self.in_scope_lifetimes.extend(lt_def_names);
783 self.in_scope_lifetimes.truncate(old_len);
787 /// Appends in-band lifetime defs and argument-position `impl
788 /// Trait` defs to the existing set of generics.
790 /// Presuming that in-band lifetimes are enabled, then
791 /// `self.anonymous_lifetime_mode` will be updated to match the
792 /// argument while `f` is running (and restored afterwards).
793 fn add_in_band_defs<F, T>(
797 anonymous_lifetime_mode: AnonymousLifetimeMode,
799 ) -> (hir::Generics, T)
801 F: FnOnce(&mut LoweringContext) -> T,
803 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
806 let itctx = ImplTraitContext::Universal(parent_id);
807 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
808 (this.lower_generics(generics, itctx), f(this))
813 lowered_generics.params = lowered_generics
820 (lowered_generics, res)
823 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
825 F: FnOnce(&mut LoweringContext) -> T,
827 let len = self.catch_scopes.len();
828 self.catch_scopes.push(catch_id);
830 let result = f(self);
833 self.catch_scopes.len(),
834 "catch scopes should be added and removed in stack order"
837 self.catch_scopes.pop().unwrap();
844 capture_clause: CaptureBy,
845 closure_node_id: NodeId,
847 body: impl FnOnce(&mut LoweringContext) -> hir::Expr,
849 let prev_is_generator = mem::replace(&mut self.is_generator, true);
850 let body_expr = body(self);
851 let span = body_expr.span;
852 let output = match ret_ty {
853 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
854 None => FunctionRetTy::Default(span),
861 let body_id = self.record_body(body_expr, Some(&decl));
862 self.is_generator = prev_is_generator;
864 let capture_clause = self.lower_capture_clause(capture_clause);
865 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
866 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, false);
867 let generator = hir::Expr {
869 hir_id: closure_hir_id,
870 node: hir::ExprClosure(capture_clause, decl, body_id, span,
871 Some(hir::GeneratorMovability::Static)),
873 attrs: ThinVec::new(),
876 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
877 let gen_future = self.expr_std_path(
878 unstable_span, &["future", "from_generator"], None, ThinVec::new());
879 hir::ExprCall(P(gen_future), hir_vec![generator])
882 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
884 F: FnOnce(&mut LoweringContext) -> hir::Expr,
886 let prev = mem::replace(&mut self.is_generator, false);
887 let result = f(self);
888 let r = self.record_body(result, decl);
889 self.is_generator = prev;
893 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
895 F: FnOnce(&mut LoweringContext) -> T,
897 // We're no longer in the base loop's condition; we're in another loop.
898 let was_in_loop_condition = self.is_in_loop_condition;
899 self.is_in_loop_condition = false;
901 let len = self.loop_scopes.len();
902 self.loop_scopes.push(loop_id);
904 let result = f(self);
907 self.loop_scopes.len(),
908 "Loop scopes should be added and removed in stack order"
911 self.loop_scopes.pop().unwrap();
913 self.is_in_loop_condition = was_in_loop_condition;
918 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
920 F: FnOnce(&mut LoweringContext) -> T,
922 let was_in_loop_condition = self.is_in_loop_condition;
923 self.is_in_loop_condition = true;
925 let result = f(self);
927 self.is_in_loop_condition = was_in_loop_condition;
932 fn with_new_scopes<T, F>(&mut self, f: F) -> T
934 F: FnOnce(&mut LoweringContext) -> T,
936 let was_in_loop_condition = self.is_in_loop_condition;
937 self.is_in_loop_condition = false;
939 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
940 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
941 let result = f(self);
942 self.catch_scopes = catch_scopes;
943 self.loop_scopes = loop_scopes;
945 self.is_in_loop_condition = was_in_loop_condition;
950 fn def_key(&mut self, id: DefId) -> DefKey {
952 self.resolver.definitions().def_key(id.index)
954 self.cstore.def_key(id)
958 fn lower_ident(&mut self, ident: Ident) -> Name {
959 let ident = ident.modern();
960 if ident.span.ctxt() == SyntaxContext::empty() {
965 .or_insert_with(|| Symbol::from_ident(ident))
968 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
969 label.map(|label| hir::Label {
970 name: label.ident.name,
971 span: label.ident.span,
975 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
977 Some((id, label)) => {
978 let target_id = if let Def::Label(loop_id) = self.expect_full_def(id) {
979 Ok(self.lower_node_id(loop_id).node_id)
981 Err(hir::LoopIdError::UnresolvedLabel)
984 label: self.lower_label(Some(label)),
989 let target_id = self.loop_scopes
991 .map(|innermost_loop_id| *innermost_loop_id)
992 .map(|id| Ok(self.lower_node_id(id).node_id))
993 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1004 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1007 .map(|a| self.lower_attr(a))
1008 .collect::<Vec<_>>()
1012 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1016 path: attr.path.clone(),
1017 tokens: self.lower_token_stream(attr.tokens.clone()),
1018 is_sugared_doc: attr.is_sugared_doc,
1023 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1026 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1030 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1032 TokenTree::Token(span, token) => self.lower_token(token, span),
1033 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1036 delim: delimited.delim,
1037 tts: self.lower_token_stream(delimited.tts.into()).into(),
1043 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1045 Token::Interpolated(_) => {}
1046 other => return TokenTree::Token(span, other).into(),
1049 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1050 self.lower_token_stream(tts)
1053 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1055 attrs: self.lower_attrs(&arm.attrs),
1056 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1057 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1058 body: P(self.lower_expr(&arm.body)),
1062 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1064 id: self.lower_node_id(b.id).node_id,
1065 name: self.lower_ident(b.ident),
1066 ty: self.lower_ty(&b.ty, itctx),
1071 fn lower_generic_arg(&mut self,
1072 arg: &ast::GenericArg,
1073 itctx: ImplTraitContext)
1074 -> hir::GenericArg {
1076 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1077 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty(&ty, itctx)),
1081 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1082 let kind = match t.node {
1083 TyKind::Infer => hir::TyInfer,
1084 TyKind::Err => hir::TyErr,
1085 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty, itctx)),
1086 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt, itctx)),
1087 TyKind::Rptr(ref region, ref mt) => {
1088 let span = t.span.shrink_to_lo();
1089 let lifetime = match *region {
1090 Some(ref lt) => self.lower_lifetime(lt),
1091 None => self.elided_ref_lifetime(span),
1093 hir::TyRptr(lifetime, self.lower_mt(mt, itctx))
1095 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1098 this.with_anonymous_lifetime_mode(
1099 AnonymousLifetimeMode::PassThrough,
1101 hir::TyBareFn(P(hir::BareFnTy {
1102 generic_params: this.lower_generic_params(
1105 ImplTraitContext::Disallowed,
1107 unsafety: this.lower_unsafety(f.unsafety),
1109 decl: this.lower_fn_decl(&f.decl, None, false, false),
1110 arg_names: this.lower_fn_args_to_names(&f.decl),
1116 TyKind::Never => hir::TyNever,
1117 TyKind::Tup(ref tys) => {
1118 hir::TyTup(tys.iter().map(|ty| self.lower_ty(ty, itctx)).collect())
1120 TyKind::Paren(ref ty) => {
1121 return self.lower_ty(ty, itctx);
1123 TyKind::Path(ref qself, ref path) => {
1124 let id = self.lower_node_id(t.id);
1125 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1126 let ty = self.ty_path(id, t.span, qpath);
1127 if let hir::TyTraitObject(..) = ty.node {
1128 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1132 TyKind::ImplicitSelf => hir::TyPath(hir::QPath::Resolved(
1135 def: self.expect_full_def(t.id),
1136 segments: hir_vec![hir::PathSegment::from_name(keywords::SelfType.name())],
1140 TyKind::Array(ref ty, ref length) => {
1141 hir::TyArray(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1143 TyKind::Typeof(ref expr) => {
1144 hir::TyTypeof(self.lower_anon_const(expr))
1146 TyKind::TraitObject(ref bounds, kind) => {
1147 let mut lifetime_bound = None;
1150 .filter_map(|bound| match *bound {
1151 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1152 Some(self.lower_poly_trait_ref(ty, itctx))
1154 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1155 GenericBound::Outlives(ref lifetime) => {
1156 if lifetime_bound.is_none() {
1157 lifetime_bound = Some(self.lower_lifetime(lifetime));
1163 let lifetime_bound =
1164 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1165 if kind != TraitObjectSyntax::Dyn {
1166 self.maybe_lint_bare_trait(t.span, t.id, false);
1168 hir::TyTraitObject(bounds, lifetime_bound)
1170 TyKind::ImplTrait(ref bounds) => {
1173 ImplTraitContext::Existential(fn_def_id) => {
1174 self.lower_existential_impl_trait(
1175 span, fn_def_id, |this| this.lower_param_bounds(bounds, itctx))
1177 ImplTraitContext::Universal(def_id) => {
1178 let def_node_id = self.next_id().node_id;
1180 // Add a definition for the in-band TyParam
1181 let def_index = self.resolver.definitions().create_def_with_parent(
1184 DefPathData::UniversalImplTrait,
1185 DefIndexAddressSpace::High,
1190 let hir_bounds = self.lower_param_bounds(bounds, itctx);
1191 // Set the name to `impl Bound1 + Bound2`
1192 let name = Symbol::intern(&pprust::ty_to_string(t));
1193 self.in_band_ty_params.push(hir::GenericParam {
1195 name: ParamName::Plain(name),
1197 pure_wrt_drop: false,
1200 kind: hir::GenericParamKind::Type {
1202 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1206 hir::TyPath(hir::QPath::Resolved(
1210 def: Def::TyParam(DefId::local(def_index)),
1211 segments: hir_vec![hir::PathSegment::from_name(name)],
1215 ImplTraitContext::Disallowed => {
1220 "`impl Trait` not allowed outside of function \
1221 and inherent method return types"
1227 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1230 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1239 fn lower_existential_impl_trait(
1243 lower_bounds: impl FnOnce(&mut LoweringContext) -> hir::GenericBounds,
1245 // We need to manually repeat the code of `next_id` because the lowering
1246 // needs to happen while the owner_id is pointing to the item itself,
1247 // because items are their own owners
1248 let exist_ty_node_id = self.sess.next_node_id();
1250 // Make sure we know that some funky desugaring has been going on here.
1251 // This is a first: there is code in other places like for loop
1252 // desugaring that explicitly states that we don't want to track that.
1253 // Not tracking it makes lints in rustc and clippy very fragile as
1254 // frequently opened issues show.
1255 let exist_ty_span = self.allow_internal_unstable(
1256 CompilerDesugaringKind::ExistentialReturnType,
1260 // Pull a new definition from the ether
1261 let exist_ty_def_index = self
1264 .create_def_with_parent(
1267 DefPathData::ExistentialImplTrait,
1268 DefIndexAddressSpace::High,
1273 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1275 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1277 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1283 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1284 let exist_ty_item_kind = hir::ItemExistential(hir::ExistTy {
1285 generics: hir::Generics {
1286 params: lifetime_defs,
1287 where_clause: hir::WhereClause {
1288 id: lctx.next_id().node_id,
1289 predicates: Vec::new().into(),
1294 impl_trait_fn: Some(fn_def_id),
1296 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1297 // Generate an `existential type Foo: Trait;` declaration
1298 trace!("creating existential type with id {:#?}", exist_ty_id);
1300 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1301 let exist_ty_item = hir::Item {
1302 id: exist_ty_id.node_id,
1303 hir_id: exist_ty_id.hir_id,
1304 name: keywords::Invalid.name(),
1305 attrs: Default::default(),
1306 node: exist_ty_item_kind,
1307 vis: hir::Visibility::Inherited,
1308 span: exist_ty_span,
1311 // Insert the item into the global list. This usually happens
1312 // automatically for all AST items. But this existential type item
1313 // does not actually exist in the AST.
1314 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1316 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1317 hir::TyImplTraitExistential(
1319 id: exist_ty_id.node_id
1321 DefId::local(exist_ty_def_index),
1327 fn lifetimes_from_impl_trait_bounds(
1329 exist_ty_id: NodeId,
1330 parent_index: DefIndex,
1331 bounds: &hir::GenericBounds,
1332 ) -> (HirVec<hir::Lifetime>, HirVec<hir::GenericParam>) {
1333 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1334 // appear in the bounds, excluding lifetimes that are created within the bounds.
1335 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1336 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1337 context: &'r mut LoweringContext<'a>,
1339 exist_ty_id: NodeId,
1340 collect_elided_lifetimes: bool,
1341 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1342 already_defined_lifetimes: HashSet<hir::LifetimeName>,
1343 output_lifetimes: Vec<hir::Lifetime>,
1344 output_lifetime_params: Vec<hir::GenericParam>,
1347 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1348 fn nested_visit_map<'this>(
1350 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1351 hir::intravisit::NestedVisitorMap::None
1354 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1355 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1356 if parameters.parenthesized {
1357 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1358 self.collect_elided_lifetimes = false;
1359 hir::intravisit::walk_generic_args(self, span, parameters);
1360 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1362 hir::intravisit::walk_generic_args(self, span, parameters);
1366 fn visit_ty(&mut self, t: &'v hir::Ty) {
1367 // Don't collect elided lifetimes used inside of `fn()` syntax
1368 if let &hir::Ty_::TyBareFn(_) = &t.node {
1369 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1370 self.collect_elided_lifetimes = false;
1372 // Record the "stack height" of `for<'a>` lifetime bindings
1373 // to be able to later fully undo their introduction.
1374 let old_len = self.currently_bound_lifetimes.len();
1375 hir::intravisit::walk_ty(self, t);
1376 self.currently_bound_lifetimes.truncate(old_len);
1378 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1380 hir::intravisit::walk_ty(self, t);
1384 fn visit_poly_trait_ref(
1386 trait_ref: &'v hir::PolyTraitRef,
1387 modifier: hir::TraitBoundModifier,
1389 // Record the "stack height" of `for<'a>` lifetime bindings
1390 // to be able to later fully undo their introduction.
1391 let old_len = self.currently_bound_lifetimes.len();
1392 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1393 self.currently_bound_lifetimes.truncate(old_len);
1396 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1397 // Record the introduction of 'a in `for<'a> ...`
1398 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1399 // Introduce lifetimes one at a time so that we can handle
1400 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1401 let lt_name = hir::LifetimeName::Param(param.name);
1402 self.currently_bound_lifetimes.push(lt_name);
1405 hir::intravisit::walk_generic_param(self, param);
1408 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1409 let name = match lifetime.name {
1410 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1411 if self.collect_elided_lifetimes {
1412 // Use `'_` for both implicit and underscore lifetimes in
1413 // `abstract type Foo<'_>: SomeTrait<'_>;`
1414 hir::LifetimeName::Underscore
1419 hir::LifetimeName::Param(_) => lifetime.name,
1420 hir::LifetimeName::Static => return,
1423 if !self.currently_bound_lifetimes.contains(&name)
1424 && !self.already_defined_lifetimes.contains(&name) {
1425 self.already_defined_lifetimes.insert(name);
1427 self.output_lifetimes.push(hir::Lifetime {
1428 id: self.context.next_id().node_id,
1429 span: lifetime.span,
1433 // We need to manually create the ids here, because the
1434 // definitions will go into the explicit `existential type`
1435 // declaration and thus need to have their owner set to that item
1436 let def_node_id = self.context.sess.next_node_id();
1437 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1438 self.context.resolver.definitions().create_def_with_parent(
1441 DefPathData::LifetimeParam(name.name().as_interned_str()),
1442 DefIndexAddressSpace::High,
1447 let name = match name {
1448 hir::LifetimeName::Underscore => {
1449 hir::ParamName::Plain(keywords::UnderscoreLifetime.name())
1451 hir::LifetimeName::Param(param_name) => param_name,
1452 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1455 self.output_lifetime_params.push(hir::GenericParam {
1458 span: lifetime.span,
1459 pure_wrt_drop: false,
1462 kind: hir::GenericParamKind::Lifetime {
1470 let mut lifetime_collector = ImplTraitLifetimeCollector {
1472 parent: parent_index,
1474 collect_elided_lifetimes: true,
1475 currently_bound_lifetimes: Vec::new(),
1476 already_defined_lifetimes: HashSet::new(),
1477 output_lifetimes: Vec::new(),
1478 output_lifetime_params: Vec::new(),
1481 for bound in bounds {
1482 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1486 lifetime_collector.output_lifetimes.into(),
1487 lifetime_collector.output_lifetime_params.into(),
1491 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1496 .map(|x| self.lower_foreign_item(x))
1501 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1508 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1510 node: hir::Variant_ {
1511 name: v.node.ident.name,
1512 attrs: self.lower_attrs(&v.node.attrs),
1513 data: self.lower_variant_data(&v.node.data),
1514 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1523 qself: &Option<QSelf>,
1525 param_mode: ParamMode,
1526 itctx: ImplTraitContext,
1528 let qself_position = qself.as_ref().map(|q| q.position);
1529 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx));
1531 let resolution = self.resolver
1533 .unwrap_or(PathResolution::new(Def::Err));
1535 let proj_start = p.segments.len() - resolution.unresolved_segments();
1536 let path = P(hir::Path {
1537 def: resolution.base_def(),
1538 segments: p.segments[..proj_start]
1541 .map(|(i, segment)| {
1542 let param_mode = match (qself_position, param_mode) {
1543 (Some(j), ParamMode::Optional) if i < j => {
1544 // This segment is part of the trait path in a
1545 // qualified path - one of `a`, `b` or `Trait`
1546 // in `<X as a::b::Trait>::T::U::method`.
1552 // Figure out if this is a type/trait segment,
1553 // which may need lifetime elision performed.
1554 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1555 krate: def_id.krate,
1556 index: this.def_key(def_id).parent.expect("missing parent"),
1558 let type_def_id = match resolution.base_def() {
1559 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1560 Some(parent_def_id(self, def_id))
1562 Def::Variant(def_id) if i + 1 == proj_start => {
1563 Some(parent_def_id(self, def_id))
1566 | Def::Union(def_id)
1568 | Def::TyAlias(def_id)
1569 | Def::Trait(def_id) if i + 1 == proj_start =>
1575 let parenthesized_generic_args = match resolution.base_def() {
1576 // `a::b::Trait(Args)`
1577 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1578 // `a::b::Trait(Args)::TraitItem`
1579 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1580 if i + 2 == proj_start =>
1582 ParenthesizedGenericArgs::Ok
1584 // Avoid duplicated errors
1585 Def::Err => ParenthesizedGenericArgs::Ok,
1591 | Def::Variant(..) if i + 1 == proj_start =>
1593 ParenthesizedGenericArgs::Err
1595 // A warning for now, for compatibility reasons
1596 _ => ParenthesizedGenericArgs::Warn,
1599 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1600 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1603 assert!(!def_id.is_local());
1605 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1606 let n = item_generics.own_counts().lifetimes;
1607 self.type_def_lifetime_params.insert(def_id, n);
1610 self.lower_path_segment(
1615 parenthesized_generic_args,
1623 // Simple case, either no projections, or only fully-qualified.
1624 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1625 if resolution.unresolved_segments() == 0 {
1626 return hir::QPath::Resolved(qself, path);
1629 // Create the innermost type that we're projecting from.
1630 let mut ty = if path.segments.is_empty() {
1631 // If the base path is empty that means there exists a
1632 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1633 qself.expect("missing QSelf for <T>::...")
1635 // Otherwise, the base path is an implicit `Self` type path,
1636 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1637 // `<I as Iterator>::Item::default`.
1638 let new_id = self.next_id();
1639 self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))
1642 // Anything after the base path are associated "extensions",
1643 // out of which all but the last one are associated types,
1644 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1645 // * base path is `std::vec::Vec<T>`
1646 // * "extensions" are `IntoIter`, `Item` and `clone`
1647 // * type nodes are:
1648 // 1. `std::vec::Vec<T>` (created above)
1649 // 2. `<std::vec::Vec<T>>::IntoIter`
1650 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1651 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1652 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1653 let segment = P(self.lower_path_segment(
1658 ParenthesizedGenericArgs::Warn,
1661 let qpath = hir::QPath::TypeRelative(ty, segment);
1663 // It's finished, return the extension of the right node type.
1664 if i == p.segments.len() - 1 {
1668 // Wrap the associated extension in another type node.
1669 let new_id = self.next_id();
1670 ty = self.ty_path(new_id, p.span, qpath);
1673 // Should've returned in the for loop above.
1676 "lower_qpath: no final extension segment in {}..{}",
1682 fn lower_path_extra(
1687 param_mode: ParamMode,
1691 segments: p.segments
1694 self.lower_path_segment(
1699 ParenthesizedGenericArgs::Err,
1700 ImplTraitContext::Disallowed,
1703 .chain(name.map(|name| hir::PathSegment::from_name(name)))
1709 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1710 let def = self.expect_full_def(id);
1711 self.lower_path_extra(def, p, None, param_mode)
1714 fn lower_path_segment(
1717 segment: &PathSegment,
1718 param_mode: ParamMode,
1719 expected_lifetimes: usize,
1720 parenthesized_generic_args: ParenthesizedGenericArgs,
1721 itctx: ImplTraitContext,
1722 ) -> hir::PathSegment {
1723 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1724 let msg = "parenthesized parameters may only be used with a trait";
1725 match **generic_args {
1726 GenericArgs::AngleBracketed(ref data) => {
1727 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1729 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1730 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1731 ParenthesizedGenericArgs::Warn => {
1732 self.sess.buffer_lint(
1733 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1738 (hir::GenericArgs::none(), true)
1740 ParenthesizedGenericArgs::Err => {
1741 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1742 .span_label(data.span, "only traits may use parentheses")
1744 (hir::GenericArgs::none(), true)
1749 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1752 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1753 GenericArg::Lifetime(_) => true,
1756 if !generic_args.parenthesized && !has_lifetimes {
1758 self.elided_path_lifetimes(path_span, expected_lifetimes)
1760 .map(|lt| GenericArg::Lifetime(lt))
1761 .chain(generic_args.args.into_iter())
1765 hir::PathSegment::new(
1766 self.lower_ident(segment.ident),
1772 fn lower_angle_bracketed_parameter_data(
1774 data: &AngleBracketedArgs,
1775 param_mode: ParamMode,
1776 itctx: ImplTraitContext,
1777 ) -> (hir::GenericArgs, bool) {
1778 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1779 let has_types = args.iter().any(|arg| match arg {
1780 ast::GenericArg::Type(_) => true,
1784 args: args.iter().map(|a| self.lower_generic_arg(a, itctx)).collect(),
1785 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(),
1786 parenthesized: false,
1788 !has_types && param_mode == ParamMode::Optional)
1791 fn lower_parenthesized_parameter_data(
1793 data: &ParenthesisedArgs,
1794 ) -> (hir::GenericArgs, bool) {
1795 // Switch to `PassThrough` mode for anonymous lifetimes: this
1796 // means that we permit things like `&Ref<T>`, where `Ref` has
1797 // a hidden lifetime parameter. This is needed for backwards
1798 // compatibility, even in contexts like an impl header where
1799 // we generally don't permit such things (see #51008).
1800 self.with_anonymous_lifetime_mode(
1801 AnonymousLifetimeMode::PassThrough,
1803 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1804 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1805 let inputs = inputs.iter().map(|ty| this.lower_ty(ty, DISALLOWED)).collect();
1806 let mk_tup = |this: &mut Self, tys, span| {
1807 let LoweredNodeId { node_id, hir_id } = this.next_id();
1808 P(hir::Ty { node: hir::TyTup(tys), id: node_id, hir_id, span })
1813 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1816 id: this.next_id().node_id,
1817 name: Symbol::intern(FN_OUTPUT_NAME),
1820 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1821 .unwrap_or_else(|| mk_tup(this, hir::HirVec::new(), span)),
1822 span: output.as_ref().map_or(span, |ty| ty.span),
1825 parenthesized: true,
1833 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1834 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1840 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1841 pat: self.lower_pat(&l.pat),
1842 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1844 attrs: l.attrs.clone(),
1845 source: hir::LocalSource::Normal,
1849 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1851 Mutability::Mutable => hir::MutMutable,
1852 Mutability::Immutable => hir::MutImmutable,
1856 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1857 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1861 pat: self.lower_pat(&arg.pat),
1865 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Spanned<Name>> {
1868 .map(|arg| match arg.pat.node {
1869 PatKind::Ident(_, ident, None) => respan(ident.span, ident.name),
1870 _ => respan(arg.pat.span, keywords::Invalid.name()),
1875 // Lowers a function declaration.
1877 // decl: the unlowered (ast) function declaration.
1878 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1879 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1880 // make_ret_async is true.
1881 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1882 // This guards against trait declarations and implementations where impl Trait is
1884 // make_ret_async: if enabled, converts `-> T` into `-> impl Future<Output = T>` in the
1885 // return type. This is used for `async fn` declarations.
1889 fn_def_id: Option<DefId>,
1890 impl_trait_return_allow: bool,
1891 make_ret_async: bool,
1892 ) -> P<hir::FnDecl> {
1893 let inputs = decl.inputs
1896 if let Some(def_id) = fn_def_id {
1897 self.lower_ty(&arg.ty, ImplTraitContext::Universal(def_id))
1899 self.lower_ty(&arg.ty, ImplTraitContext::Disallowed)
1902 .collect::<HirVec<_>>();
1904 let output = if make_ret_async {
1905 self.lower_async_fn_ret_ty(
1906 &inputs, &decl.output, fn_def_id.expect("make_ret_async but no fn_def_id"))
1909 FunctionRetTy::Ty(ref ty) => match fn_def_id {
1910 Some(def_id) if impl_trait_return_allow => {
1911 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1913 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1915 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1922 variadic: decl.variadic,
1923 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1924 TyKind::ImplicitSelf => true,
1925 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1931 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
1933 // fn_span: the span of the async function declaration. Used for error reporting.
1934 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
1935 // output: unlowered output type (`T` in `-> T`)
1936 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
1937 fn lower_async_fn_ret_ty(
1939 inputs: &[P<hir::Ty>],
1940 output: &FunctionRetTy,
1942 ) -> hir::FunctionRetTy {
1943 // Get lifetimes used in the input arguments to the function. Our output type must also
1944 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
1945 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
1946 // is a subset of the other. We really want some new lifetime that is a subset of all input
1947 // lifetimes, but that doesn't exist at the moment.
1949 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
1950 context: &'r mut LoweringContext<'a>,
1951 // Lifetimes bound by HRTB
1952 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1953 // Whether to count elided lifetimes.
1954 // Disabled inside of `Fn` or `fn` syntax.
1955 collect_elided_lifetimes: bool,
1956 // The lifetime found.
1957 // Multiple different or elided lifetimes cannot appear in async fn for now.
1958 output_lifetime: Option<(hir::LifetimeName, Span)>,
1961 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
1962 fn nested_visit_map<'this>(
1964 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1965 hir::intravisit::NestedVisitorMap::None
1968 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1969 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1970 if parameters.parenthesized {
1971 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1972 self.collect_elided_lifetimes = false;
1973 hir::intravisit::walk_generic_args(self, span, parameters);
1974 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1976 hir::intravisit::walk_generic_args(self, span, parameters);
1980 fn visit_ty(&mut self, t: &'v hir::Ty) {
1981 // Don't collect elided lifetimes used inside of `fn()` syntax
1982 if let &hir::Ty_::TyBareFn(_) = &t.node {
1983 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1984 self.collect_elided_lifetimes = false;
1986 // Record the "stack height" of `for<'a>` lifetime bindings
1987 // to be able to later fully undo their introduction.
1988 let old_len = self.currently_bound_lifetimes.len();
1989 hir::intravisit::walk_ty(self, t);
1990 self.currently_bound_lifetimes.truncate(old_len);
1992 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1994 hir::intravisit::walk_ty(self, t);
1998 fn visit_poly_trait_ref(
2000 trait_ref: &'v hir::PolyTraitRef,
2001 modifier: hir::TraitBoundModifier,
2003 // Record the "stack height" of `for<'a>` lifetime bindings
2004 // to be able to later fully undo their introduction.
2005 let old_len = self.currently_bound_lifetimes.len();
2006 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2007 self.currently_bound_lifetimes.truncate(old_len);
2010 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2011 // Record the introduction of 'a in `for<'a> ...`
2012 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2013 // Introduce lifetimes one at a time so that we can handle
2014 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2015 let lt_name = hir::LifetimeName::Param(param.name);
2016 self.currently_bound_lifetimes.push(lt_name);
2019 hir::intravisit::walk_generic_param(self, param);
2022 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2023 let name = match lifetime.name {
2024 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2025 if self.collect_elided_lifetimes {
2026 // Use `'_` for both implicit and underscore lifetimes in
2027 // `abstract type Foo<'_>: SomeTrait<'_>;`
2028 hir::LifetimeName::Underscore
2033 hir::LifetimeName::Param(_) => lifetime.name,
2034 hir::LifetimeName::Static => return,
2037 if !self.currently_bound_lifetimes.contains(&name) {
2038 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2039 // We don't currently have a reliable way to desugar `async fn` with
2040 // multiple potentially unrelated input lifetimes into
2041 // `-> impl Trait + 'lt`, so we report an error in this case.
2042 if current_lt_name != name {
2045 current_lt_span.between(lifetime.span),
2047 "multiple different lifetimes used in arguments of `async fn`",
2049 .span_label(current_lt_span, "first lifetime here")
2050 .span_label(lifetime.span, "different lifetime here")
2051 .help("`async fn` can only accept borrowed values \
2052 with identical lifetimes")
2054 } else if current_lt_name.is_elided() && name.is_elided() {
2057 current_lt_span.between(lifetime.span),
2059 "multiple elided lifetimes used in arguments of `async fn`",
2061 .span_label(current_lt_span, "first lifetime here")
2062 .span_label(lifetime.span, "different lifetime here")
2063 .help("consider giving these arguments named lifetimes")
2067 self.output_lifetime = Some((name, lifetime.span));
2073 let bound_lifetime = {
2074 let mut lifetime_collector = AsyncFnLifetimeCollector {
2076 currently_bound_lifetimes: Vec::new(),
2077 collect_elided_lifetimes: true,
2078 output_lifetime: None,
2082 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2084 lifetime_collector.output_lifetime
2087 let span = match output {
2088 FunctionRetTy::Ty(ty) => ty.span,
2089 FunctionRetTy::Default(span) => *span,
2092 let impl_trait_ty = self.lower_existential_impl_trait(
2093 span, fn_def_id, |this| {
2094 let output_ty = match output {
2095 FunctionRetTy::Ty(ty) =>
2096 this.lower_ty(ty, ImplTraitContext::Existential(fn_def_id)),
2097 FunctionRetTy::Default(span) => {
2098 let LoweredNodeId { node_id, hir_id } = this.next_id();
2102 node: hir::TyTup(hir_vec![]),
2109 let future_params = P(hir::GenericArgs {
2111 bindings: hir_vec![hir::TypeBinding {
2112 name: Symbol::intern(FN_OUTPUT_NAME),
2114 id: this.next_id().node_id,
2117 parenthesized: false,
2121 this.std_path(span, &["future", "Future"], Some(future_params), false);
2123 let mut bounds = vec![
2124 hir::GenericBound::Trait(
2126 trait_ref: hir::TraitRef {
2128 ref_id: this.next_id().node_id,
2130 bound_generic_params: hir_vec![],
2133 hir::TraitBoundModifier::None
2137 if let Some((name, span)) = bound_lifetime {
2138 bounds.push(hir::GenericBound::Outlives(
2139 hir::Lifetime { id: this.next_id().node_id, name, span }));
2142 hir::HirVec::from(bounds)
2145 let LoweredNodeId { node_id, hir_id } = self.next_id();
2146 let impl_trait_ty = P(hir::Ty {
2148 node: impl_trait_ty,
2153 hir::FunctionRetTy::Return(impl_trait_ty)
2156 fn lower_param_bound(
2159 itctx: ImplTraitContext,
2160 ) -> hir::GenericBound {
2162 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2163 self.lower_poly_trait_ref(ty, itctx),
2164 self.lower_trait_bound_modifier(modifier),
2166 GenericBound::Outlives(ref lifetime) => {
2167 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2172 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2173 let span = l.ident.span;
2174 match self.lower_ident(l.ident) {
2175 x if x == "'static" => self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2176 x if x == "'_" => match self.anonymous_lifetime_mode {
2177 AnonymousLifetimeMode::CreateParameter => {
2178 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2179 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2182 AnonymousLifetimeMode::PassThrough => {
2183 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2187 self.maybe_collect_in_band_lifetime(span, name);
2188 let param_name = ParamName::Plain(name);
2189 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2194 fn new_named_lifetime(
2198 name: hir::LifetimeName,
2199 ) -> hir::Lifetime {
2201 id: self.lower_node_id(id).node_id,
2207 fn lower_generic_params(
2209 params: &Vec<GenericParam>,
2210 add_bounds: &NodeMap<Vec<GenericBound>>,
2211 itctx: ImplTraitContext,
2212 ) -> hir::HirVec<hir::GenericParam> {
2213 params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect()
2216 fn lower_generic_param(&mut self,
2217 param: &GenericParam,
2218 add_bounds: &NodeMap<Vec<GenericBound>>,
2219 itctx: ImplTraitContext)
2220 -> hir::GenericParam {
2221 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx);
2223 GenericParamKind::Lifetime => {
2224 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2225 self.is_collecting_in_band_lifetimes = false;
2227 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
2228 let param_name = match lt.name {
2229 hir::LifetimeName::Param(param_name) => param_name,
2230 _ => hir::ParamName::Plain(lt.name.name()),
2232 let param = hir::GenericParam {
2236 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2237 attrs: self.lower_attrs(¶m.attrs),
2239 kind: hir::GenericParamKind::Lifetime { in_band: false }
2242 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2246 GenericParamKind::Type { ref default, .. } => {
2247 let mut name = self.lower_ident(param.ident);
2249 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2250 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2251 // Instead, use gensym("Self") to create a distinct name that looks the same.
2252 if name == keywords::SelfType.name() {
2253 name = Symbol::gensym("Self");
2256 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2257 if !add_bounds.is_empty() {
2258 bounds = bounds.into_iter()
2259 .chain(self.lower_param_bounds(add_bounds, itctx).into_iter())
2264 id: self.lower_node_id(param.id).node_id,
2265 name: hir::ParamName::Plain(name),
2266 span: param.ident.span,
2267 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2268 attrs: self.lower_attrs(¶m.attrs),
2270 kind: hir::GenericParamKind::Type {
2271 default: default.as_ref().map(|x| {
2272 self.lower_ty(x, ImplTraitContext::Disallowed)
2274 synthetic: param.attrs.iter()
2275 .filter(|attr| attr.check_name("rustc_synthetic"))
2276 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2286 generics: &Generics,
2287 itctx: ImplTraitContext)
2290 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2291 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2292 // paths where report_error is called are also the only paths that advance to after
2293 // the match statement, so the error reporting could probably just be moved there.
2294 let mut add_bounds = NodeMap();
2295 for pred in &generics.where_clause.predicates {
2296 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2297 'next_bound: for bound in &bound_pred.bounds {
2298 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2299 let report_error = |this: &mut Self| {
2300 this.diagnostic().span_err(
2301 bound_pred.bounded_ty.span,
2302 "`?Trait` bounds are only permitted at the \
2303 point where a type parameter is declared",
2306 // Check if the where clause type is a plain type parameter.
2307 match bound_pred.bounded_ty.node {
2308 TyKind::Path(None, ref path)
2309 if path.segments.len() == 1
2310 && bound_pred.bound_generic_params.is_empty() =>
2312 if let Some(Def::TyParam(def_id)) = self.resolver
2313 .get_resolution(bound_pred.bounded_ty.id)
2314 .map(|d| d.base_def())
2316 if let Some(node_id) =
2317 self.resolver.definitions().as_local_node_id(def_id)
2319 for param in &generics.params {
2321 GenericParamKind::Type { .. } => {
2322 if node_id == param.id {
2323 add_bounds.entry(param.id)
2324 .or_insert(Vec::new())
2325 .push(bound.clone());
2326 continue 'next_bound;
2336 _ => report_error(self),
2344 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2345 where_clause: self.lower_where_clause(&generics.where_clause),
2346 span: generics.span,
2350 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2352 id: self.lower_node_id(wc.id).node_id,
2353 predicates: wc.predicates
2355 .map(|predicate| self.lower_where_predicate(predicate))
2360 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2362 WherePredicate::BoundPredicate(WhereBoundPredicate {
2363 ref bound_generic_params,
2368 self.with_in_scope_lifetime_defs(
2369 &bound_generic_params,
2371 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2372 bound_generic_params: this.lower_generic_params(
2373 bound_generic_params,
2375 ImplTraitContext::Disallowed,
2377 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2380 .filter_map(|bound| match *bound {
2381 // Ignore `?Trait` bounds.
2382 // Tthey were copied into type parameters already.
2383 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2384 _ => Some(this.lower_param_bound(
2386 ImplTraitContext::Disallowed,
2395 WherePredicate::RegionPredicate(WhereRegionPredicate {
2399 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2401 lifetime: self.lower_lifetime(lifetime),
2402 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2404 WherePredicate::EqPredicate(WhereEqPredicate {
2409 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2410 id: self.lower_node_id(id).node_id,
2411 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2412 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2418 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2420 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2424 .map(|f| self.lower_struct_field(f))
2426 self.lower_node_id(id).node_id,
2428 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2432 .map(|f| self.lower_struct_field(f))
2434 self.lower_node_id(id).node_id,
2436 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2440 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2441 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2442 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2443 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2447 ref_id: self.lower_node_id(p.ref_id).node_id,
2451 fn lower_poly_trait_ref(
2454 itctx: ImplTraitContext,
2455 ) -> hir::PolyTraitRef {
2456 let bound_generic_params =
2457 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx);
2458 let trait_ref = self.with_parent_impl_lifetime_defs(
2459 &bound_generic_params,
2460 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2464 bound_generic_params,
2470 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2473 id: self.lower_node_id(f.id).node_id,
2474 ident: match f.ident {
2475 Some(ident) => ident,
2476 // FIXME(jseyfried) positional field hygiene
2477 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2479 vis: self.lower_visibility(&f.vis, None),
2480 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2481 attrs: self.lower_attrs(&f.attrs),
2485 fn lower_field(&mut self, f: &Field) -> hir::Field {
2487 id: self.next_id().node_id,
2489 expr: P(self.lower_expr(&f.expr)),
2491 is_shorthand: f.is_shorthand,
2495 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2497 ty: self.lower_ty(&mt.ty, itctx),
2498 mutbl: self.lower_mutability(mt.mutbl),
2502 fn lower_param_bounds(&mut self, bounds: &[GenericBound], itctx: ImplTraitContext)
2503 -> hir::GenericBounds {
2504 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx)).collect()
2507 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2508 let mut expr = None;
2510 let mut stmts = vec![];
2512 for (index, stmt) in b.stmts.iter().enumerate() {
2513 if index == b.stmts.len() - 1 {
2514 if let StmtKind::Expr(ref e) = stmt.node {
2515 expr = Some(P(self.lower_expr(e)));
2517 stmts.extend(self.lower_stmt(stmt));
2520 stmts.extend(self.lower_stmt(stmt));
2524 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2529 stmts: stmts.into(),
2531 rules: self.lower_block_check_mode(&b.rules),
2534 recovered: b.recovered,
2542 attrs: &hir::HirVec<Attribute>,
2543 vis: &mut hir::Visibility,
2547 ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2548 ItemKind::Use(ref use_tree) => {
2549 // Start with an empty prefix
2552 span: use_tree.span,
2555 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2557 ItemKind::Static(ref t, m, ref e) => {
2558 let value = self.lower_body(None, |this| this.lower_expr(e));
2560 self.lower_ty(t, ImplTraitContext::Disallowed),
2561 self.lower_mutability(m),
2565 ItemKind::Const(ref t, ref e) => {
2566 let value = self.lower_body(None, |this| this.lower_expr(e));
2567 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2569 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2570 let fn_def_id = self.resolver.definitions().local_def_id(id);
2572 self.with_new_scopes(|this| {
2573 // Note: we don't need to change the return type from `T` to
2574 // `impl Future<Output = T>` here because lower_body
2575 // only cares about the input argument patterns in the function
2576 // declaration (decl), not the return types.
2577 let body_id = this.lower_body(Some(decl), |this| {
2578 if let IsAsync::Async(async_node_id) = header.asyncness {
2579 let async_expr = this.make_async_expr(
2580 CaptureBy::Value, async_node_id, None,
2582 let body = this.lower_block(body, false);
2583 this.expr_block(body, ThinVec::new())
2585 this.expr(body.span, async_expr, ThinVec::new())
2587 let body = this.lower_block(body, false);
2588 this.expr_block(body, ThinVec::new())
2592 let (generics, fn_decl) = this.add_in_band_defs(
2595 AnonymousLifetimeMode::PassThrough,
2596 |this| this.lower_fn_decl(
2597 decl, Some(fn_def_id), true, header.asyncness.is_async())
2602 this.lower_fn_header(header),
2608 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2609 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2610 ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2611 ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2612 self.lower_ty(t, ImplTraitContext::Disallowed),
2613 self.lower_generics(generics, ImplTraitContext::Disallowed),
2615 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2617 variants: enum_definition
2620 .map(|x| self.lower_variant(x))
2623 self.lower_generics(generics, ImplTraitContext::Disallowed),
2625 ItemKind::Struct(ref struct_def, ref generics) => {
2626 let struct_def = self.lower_variant_data(struct_def);
2629 self.lower_generics(generics, ImplTraitContext::Disallowed),
2632 ItemKind::Union(ref vdata, ref generics) => {
2633 let vdata = self.lower_variant_data(vdata);
2636 self.lower_generics(generics, ImplTraitContext::Disallowed),
2648 let def_id = self.resolver.definitions().local_def_id(id);
2650 // Lower the "impl header" first. This ordering is important
2651 // for in-band lifetimes! Consider `'a` here:
2653 // impl Foo<'a> for u32 {
2654 // fn method(&'a self) { .. }
2657 // Because we start by lowering the `Foo<'a> for u32`
2658 // part, we will add `'a` to the list of generics on
2659 // the impl. When we then encounter it later in the
2660 // method, it will not be considered an in-band
2661 // lifetime to be added, but rather a reference to a
2663 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2666 AnonymousLifetimeMode::CreateParameter,
2668 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2669 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2672 if let Some(ref trait_ref) = trait_ref {
2673 if let Def::Trait(def_id) = trait_ref.path.def {
2674 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2678 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2680 (trait_ref, lowered_ty)
2684 let new_impl_items = self.with_in_scope_lifetime_defs(
2685 &ast_generics.params,
2689 .map(|item| this.lower_impl_item_ref(item))
2695 self.lower_unsafety(unsafety),
2696 self.lower_impl_polarity(polarity),
2697 self.lower_defaultness(defaultness, true /* [1] */),
2704 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2705 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2708 .map(|item| self.lower_trait_item_ref(item))
2711 self.lower_is_auto(is_auto),
2712 self.lower_unsafety(unsafety),
2713 self.lower_generics(generics, ImplTraitContext::Disallowed),
2718 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2719 self.lower_generics(generics, ImplTraitContext::Disallowed),
2720 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2722 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2725 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2726 // not cause an assertion failure inside the `lower_defaultness` function
2734 vis: &mut hir::Visibility,
2736 attrs: &hir::HirVec<Attribute>,
2738 let path = &tree.prefix;
2741 UseTreeKind::Simple(rename, id1, id2) => {
2742 *name = tree.ident().name;
2744 // First apply the prefix to the path
2745 let mut path = Path {
2749 .chain(path.segments.iter())
2755 // Correctly resolve `self` imports
2756 if path.segments.len() > 1
2757 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2759 let _ = path.segments.pop();
2760 if rename.is_none() {
2761 *name = path.segments.last().unwrap().ident.name;
2765 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2766 let mut defs = self.expect_full_def_from_use(id);
2767 // we want to return *something* from this function, so hang onto the first item
2769 let mut ret_def = defs.next().unwrap_or(Def::Err);
2771 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2772 let vis = vis.clone();
2773 let name = name.clone();
2774 let span = path.span;
2775 self.resolver.definitions().create_def_with_parent(
2779 DefIndexAddressSpace::High,
2782 self.allocate_hir_id_counter(new_node_id, &path);
2784 self.with_hir_id_owner(new_node_id, |this| {
2785 let new_id = this.lower_node_id(new_node_id);
2786 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2787 let item = hir::ItemUse(P(path), hir::UseKind::Single);
2788 let vis = match vis {
2789 hir::Visibility::Public => hir::Visibility::Public,
2790 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2791 hir::Visibility::Inherited => hir::Visibility::Inherited,
2792 hir::Visibility::Restricted { ref path, id: _ } => {
2793 hir::Visibility::Restricted {
2795 // We are allocating a new NodeId here
2796 id: this.next_id().node_id,
2805 hir_id: new_id.hir_id,
2807 attrs: attrs.clone(),
2816 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2817 hir::ItemUse(path, hir::UseKind::Single)
2819 UseTreeKind::Glob => {
2820 let path = P(self.lower_path(
2826 .chain(path.segments.iter())
2831 ParamMode::Explicit,
2833 hir::ItemUse(path, hir::UseKind::Glob)
2835 UseTreeKind::Nested(ref trees) => {
2840 .chain(path.segments.iter())
2843 span: prefix.span.to(path.span),
2846 // Add all the nested PathListItems in the HIR
2847 for &(ref use_tree, id) in trees {
2848 self.allocate_hir_id_counter(id, &use_tree);
2852 } = self.lower_node_id(id);
2854 let mut vis = vis.clone();
2855 let mut name = name.clone();
2857 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2859 self.with_hir_id_owner(new_id, |this| {
2860 let vis = match vis {
2861 hir::Visibility::Public => hir::Visibility::Public,
2862 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2863 hir::Visibility::Inherited => hir::Visibility::Inherited,
2864 hir::Visibility::Restricted { ref path, id: _ } => {
2865 hir::Visibility::Restricted {
2867 // We are allocating a new NodeId here
2868 id: this.next_id().node_id,
2879 attrs: attrs.clone(),
2882 span: use_tree.span,
2888 // Privatize the degenerate import base, used only to check
2889 // the stability of `use a::{};`, to avoid it showing up as
2890 // a re-export by accident when `pub`, e.g. in documentation.
2891 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2892 *vis = hir::Inherited;
2893 hir::ItemUse(path, hir::UseKind::ListStem)
2898 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2899 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2900 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2902 let (generics, node) = match i.node {
2903 TraitItemKind::Const(ref ty, ref default) => (
2904 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2905 hir::TraitItemKind::Const(
2906 self.lower_ty(ty, ImplTraitContext::Disallowed),
2909 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2912 TraitItemKind::Method(ref sig, None) => {
2913 let names = self.lower_fn_args_to_names(&sig.decl);
2914 self.add_in_band_defs(
2917 AnonymousLifetimeMode::PassThrough,
2919 hir::TraitItemKind::Method(
2920 this.lower_method_sig(sig, trait_item_def_id, false, false),
2921 hir::TraitMethod::Required(names),
2926 TraitItemKind::Method(ref sig, Some(ref body)) => {
2927 let body_id = self.lower_body(Some(&sig.decl), |this| {
2928 let body = this.lower_block(body, false);
2929 this.expr_block(body, ThinVec::new())
2932 self.add_in_band_defs(
2935 AnonymousLifetimeMode::PassThrough,
2937 hir::TraitItemKind::Method(
2938 this.lower_method_sig(sig, trait_item_def_id, false, false),
2939 hir::TraitMethod::Provided(body_id),
2944 TraitItemKind::Type(ref bounds, ref default) => (
2945 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2946 hir::TraitItemKind::Type(
2947 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2950 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2953 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2959 name: self.lower_ident(i.ident),
2960 attrs: self.lower_attrs(&i.attrs),
2967 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2968 let (kind, has_default) = match i.node {
2969 TraitItemKind::Const(_, ref default) => {
2970 (hir::AssociatedItemKind::Const, default.is_some())
2972 TraitItemKind::Type(_, ref default) => {
2973 (hir::AssociatedItemKind::Type, default.is_some())
2975 TraitItemKind::Method(ref sig, ref default) => (
2976 hir::AssociatedItemKind::Method {
2977 has_self: sig.decl.has_self(),
2981 TraitItemKind::Macro(..) => unimplemented!(),
2984 id: hir::TraitItemId { node_id: i.id },
2985 name: self.lower_ident(i.ident),
2987 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
2992 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
2993 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2994 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
2996 let (generics, node) = match i.node {
2997 ImplItemKind::Const(ref ty, ref expr) => {
2998 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3000 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3001 hir::ImplItemKind::Const(
3002 self.lower_ty(ty, ImplTraitContext::Disallowed),
3007 ImplItemKind::Method(ref sig, ref body) => {
3008 let body_id = self.lower_body(Some(&sig.decl), |this| {
3009 if let IsAsync::Async(async_node_id) = sig.header.asyncness {
3010 let async_expr = this.make_async_expr(
3011 CaptureBy::Value, async_node_id, None,
3013 let body = this.lower_block(body, false);
3014 this.expr_block(body, ThinVec::new())
3016 this.expr(body.span, async_expr, ThinVec::new())
3018 let body = this.lower_block(body, false);
3019 this.expr_block(body, ThinVec::new())
3022 let impl_trait_return_allow = !self.is_in_trait_impl;
3024 self.add_in_band_defs(
3027 AnonymousLifetimeMode::PassThrough,
3029 hir::ImplItemKind::Method(
3030 this.lower_method_sig(
3033 impl_trait_return_allow,
3034 sig.header.asyncness.is_async(),
3041 ImplItemKind::Type(ref ty) => (
3042 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3043 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
3045 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3051 name: self.lower_ident(i.ident),
3052 attrs: self.lower_attrs(&i.attrs),
3054 vis: self.lower_visibility(&i.vis, None),
3055 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3060 // [1] since `default impl` is not yet implemented, this is always true in impls
3063 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3065 id: hir::ImplItemId { node_id: i.id },
3066 name: self.lower_ident(i.ident),
3068 vis: self.lower_visibility(&i.vis, Some(i.id)),
3069 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3070 kind: match i.node {
3071 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3072 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3073 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3074 has_self: sig.decl.has_self(),
3076 ImplItemKind::Macro(..) => unimplemented!(),
3080 // [1] since `default impl` is not yet implemented, this is always true in impls
3083 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3086 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3090 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
3092 ItemKind::Use(ref use_tree) => {
3093 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
3094 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3097 ItemKind::MacroDef(..) => return SmallVector::new(),
3100 SmallVector::one(hir::ItemId { id: i.id })
3103 fn lower_item_id_use_tree(&mut self,
3106 vec: &mut SmallVector<hir::ItemId>)
3109 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3110 vec.push(hir::ItemId { id });
3111 self.lower_item_id_use_tree(nested, id, vec);
3113 UseTreeKind::Glob => {}
3114 UseTreeKind::Simple(_, id1, id2) => {
3115 for (_, &id) in self.expect_full_def_from_use(base_id)
3117 .zip([id1, id2].iter())
3119 vec.push(hir::ItemId { id });
3125 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3126 let mut name = i.ident.name;
3127 let mut vis = self.lower_visibility(&i.vis, None);
3128 let attrs = self.lower_attrs(&i.attrs);
3129 if let ItemKind::MacroDef(ref def) = i.node {
3130 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
3131 let body = self.lower_token_stream(def.stream());
3132 self.exported_macros.push(hir::MacroDef {
3145 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3147 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3160 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3161 let node_id = self.lower_node_id(i.id).node_id;
3162 let def_id = self.resolver.definitions().local_def_id(node_id);
3166 attrs: self.lower_attrs(&i.attrs),
3167 node: match i.node {
3168 ForeignItemKind::Fn(ref fdec, ref generics) => {
3169 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3172 AnonymousLifetimeMode::PassThrough,
3175 // Disallow impl Trait in foreign items
3176 this.lower_fn_decl(fdec, None, false, false),
3177 this.lower_fn_args_to_names(fdec),
3182 hir::ForeignItemFn(fn_dec, fn_args, generics)
3184 ForeignItemKind::Static(ref t, m) => {
3185 hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
3187 ForeignItemKind::Ty => hir::ForeignItemType,
3188 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3190 vis: self.lower_visibility(&i.vis, None),
3195 fn lower_method_sig(
3199 impl_trait_return_allow: bool,
3201 ) -> hir::MethodSig {
3203 header: self.lower_fn_header(sig.header),
3204 decl: self.lower_fn_decl(&sig.decl, Some(fn_def_id), impl_trait_return_allow, is_async),
3208 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3210 IsAuto::Yes => hir::IsAuto::Yes,
3211 IsAuto::No => hir::IsAuto::No,
3215 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3217 unsafety: self.lower_unsafety(h.unsafety),
3218 asyncness: self.lower_asyncness(h.asyncness),
3219 constness: self.lower_constness(h.constness),
3224 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3226 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3227 Unsafety::Normal => hir::Unsafety::Normal,
3231 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3233 Constness::Const => hir::Constness::Const,
3234 Constness::NotConst => hir::Constness::NotConst,
3238 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3240 IsAsync::Async(_) => hir::IsAsync::Async,
3241 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3245 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3247 UnOp::Deref => hir::UnDeref,
3248 UnOp::Not => hir::UnNot,
3249 UnOp::Neg => hir::UnNeg,
3253 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3255 node: match b.node {
3256 BinOpKind::Add => hir::BiAdd,
3257 BinOpKind::Sub => hir::BiSub,
3258 BinOpKind::Mul => hir::BiMul,
3259 BinOpKind::Div => hir::BiDiv,
3260 BinOpKind::Rem => hir::BiRem,
3261 BinOpKind::And => hir::BiAnd,
3262 BinOpKind::Or => hir::BiOr,
3263 BinOpKind::BitXor => hir::BiBitXor,
3264 BinOpKind::BitAnd => hir::BiBitAnd,
3265 BinOpKind::BitOr => hir::BiBitOr,
3266 BinOpKind::Shl => hir::BiShl,
3267 BinOpKind::Shr => hir::BiShr,
3268 BinOpKind::Eq => hir::BiEq,
3269 BinOpKind::Lt => hir::BiLt,
3270 BinOpKind::Le => hir::BiLe,
3271 BinOpKind::Ne => hir::BiNe,
3272 BinOpKind::Ge => hir::BiGe,
3273 BinOpKind::Gt => hir::BiGt,
3279 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3280 let node = match p.node {
3281 PatKind::Wild => hir::PatKind::Wild,
3282 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3283 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3284 // `None` can occur in body-less function signatures
3285 def @ None | def @ Some(Def::Local(_)) => {
3286 let canonical_id = match def {
3287 Some(Def::Local(id)) => id,
3290 hir::PatKind::Binding(
3291 self.lower_binding_mode(binding_mode),
3293 respan(ident.span, ident.name),
3294 sub.as_ref().map(|x| self.lower_pat(x)),
3297 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3302 segments: hir_vec![hir::PathSegment::from_name(ident.name)],
3307 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3308 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3309 let qpath = self.lower_qpath(
3313 ParamMode::Optional,
3314 ImplTraitContext::Disallowed,
3316 hir::PatKind::TupleStruct(
3318 pats.iter().map(|x| self.lower_pat(x)).collect(),
3322 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3326 ParamMode::Optional,
3327 ImplTraitContext::Disallowed,
3329 PatKind::Struct(ref path, ref fields, etc) => {
3330 let qpath = self.lower_qpath(
3334 ParamMode::Optional,
3335 ImplTraitContext::Disallowed,
3342 node: hir::FieldPat {
3343 id: self.next_id().node_id,
3344 ident: f.node.ident,
3345 pat: self.lower_pat(&f.node.pat),
3346 is_shorthand: f.node.is_shorthand,
3350 hir::PatKind::Struct(qpath, fs, etc)
3352 PatKind::Tuple(ref elts, ddpos) => {
3353 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3355 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3356 PatKind::Ref(ref inner, mutbl) => {
3357 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3359 PatKind::Range(ref e1, ref e2, ref end) => hir::PatKind::Range(
3360 P(self.lower_expr(e1)),
3361 P(self.lower_expr(e2)),
3362 self.lower_range_end(end),
3364 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3365 before.iter().map(|x| self.lower_pat(x)).collect(),
3366 slice.as_ref().map(|x| self.lower_pat(x)),
3367 after.iter().map(|x| self.lower_pat(x)).collect(),
3369 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3370 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3373 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3382 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3384 RangeEnd::Included(_) => hir::RangeEnd::Included,
3385 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3389 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3390 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3395 body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3399 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3400 let kind = match e.node {
3401 ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
3402 ExprKind::ObsoleteInPlace(..) => {
3403 self.sess.abort_if_errors();
3404 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3406 ExprKind::Array(ref exprs) => {
3407 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
3409 ExprKind::Repeat(ref expr, ref count) => {
3410 let expr = P(self.lower_expr(expr));
3411 let count = self.lower_anon_const(count);
3412 hir::ExprRepeat(expr, count)
3414 ExprKind::Tup(ref elts) => {
3415 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
3417 ExprKind::Call(ref f, ref args) => {
3418 let f = P(self.lower_expr(f));
3419 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
3421 ExprKind::MethodCall(ref seg, ref args) => {
3422 let hir_seg = self.lower_path_segment(
3425 ParamMode::Optional,
3427 ParenthesizedGenericArgs::Err,
3428 ImplTraitContext::Disallowed,
3430 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3431 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
3433 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3434 let binop = self.lower_binop(binop);
3435 let lhs = P(self.lower_expr(lhs));
3436 let rhs = P(self.lower_expr(rhs));
3437 hir::ExprBinary(binop, lhs, rhs)
3439 ExprKind::Unary(op, ref ohs) => {
3440 let op = self.lower_unop(op);
3441 let ohs = P(self.lower_expr(ohs));
3442 hir::ExprUnary(op, ohs)
3444 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
3445 ExprKind::Cast(ref expr, ref ty) => {
3446 let expr = P(self.lower_expr(expr));
3447 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3449 ExprKind::Type(ref expr, ref ty) => {
3450 let expr = P(self.lower_expr(expr));
3451 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3453 ExprKind::AddrOf(m, ref ohs) => {
3454 let m = self.lower_mutability(m);
3455 let ohs = P(self.lower_expr(ohs));
3456 hir::ExprAddrOf(m, ohs)
3458 // More complicated than you might expect because the else branch
3459 // might be `if let`.
3460 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3461 let else_opt = else_opt.as_ref().map(|els| {
3463 ExprKind::IfLet(..) => {
3464 // wrap the if-let expr in a block
3465 let span = els.span;
3466 let els = P(self.lower_expr(els));
3467 let LoweredNodeId { node_id, hir_id } = self.next_id();
3468 let blk = P(hir::Block {
3473 rules: hir::DefaultBlock,
3475 targeted_by_break: false,
3476 recovered: blk.recovered,
3478 P(self.expr_block(blk, ThinVec::new()))
3480 _ => P(self.lower_expr(els)),
3484 let then_blk = self.lower_block(blk, false);
3485 let then_expr = self.expr_block(then_blk, ThinVec::new());
3487 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3489 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3491 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3492 this.lower_block(body, false),
3493 this.lower_label(opt_label),
3496 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3498 this.lower_block(body, false),
3499 this.lower_label(opt_label),
3500 hir::LoopSource::Loop,
3503 ExprKind::Catch(ref body) => {
3504 self.with_catch_scope(body.id, |this| {
3506 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3507 let mut block = this.lower_block(body, true).into_inner();
3508 let tail = block.expr.take().map_or_else(
3510 let LoweredNodeId { node_id, hir_id } = this.next_id();
3511 let span = this.sess.codemap().end_point(unstable_span);
3515 node: hir::ExprTup(hir_vec![]),
3516 attrs: ThinVec::new(),
3520 |x: P<hir::Expr>| x.into_inner(),
3522 block.expr = Some(this.wrap_in_try_constructor(
3523 "from_ok", tail, unstable_span));
3524 hir::ExprBlock(P(block), None)
3527 ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3528 P(self.lower_expr(expr)),
3529 arms.iter().map(|x| self.lower_arm(x)).collect(),
3530 hir::MatchSource::Normal,
3532 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3533 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3534 this.with_new_scopes(|this| {
3535 let block = this.lower_block(block, false);
3536 this.expr_block(block, ThinVec::new())
3541 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span) =>
3543 self.with_new_scopes(|this| {
3544 if let IsAsync::Async(async_closure_node_id) = asyncness {
3545 // FIXME(cramertj) allow `async` non-`move` closures with
3546 if capture_clause == CaptureBy::Ref &&
3547 !decl.inputs.is_empty()
3553 "`async` non-`move` closures with arguments \
3554 are not currently supported",
3556 .help("consider using `let` statements to manually capture \
3557 variables by reference before entering an \
3558 `async move` closure")
3562 // Transform `async |x: u8| -> X { ... }` into
3563 // `|x: u8| future_from_generator(|| -> X { ... })`
3564 let outer_decl = FnDecl {
3565 inputs: decl.inputs.clone(),
3566 output: FunctionRetTy::Default(fn_decl_span),
3569 let body_id = this.lower_body(Some(&outer_decl), |this| {
3570 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3573 let async_body = this.make_async_expr(
3574 capture_clause, async_closure_node_id, async_ret_ty,
3576 this.with_new_scopes(|this| this.lower_expr(body))
3578 this.expr(fn_decl_span, async_body, ThinVec::new())
3581 this.lower_capture_clause(capture_clause),
3582 this.lower_fn_decl(&outer_decl, None, false, false),
3588 let mut is_generator = false;
3589 let body_id = this.lower_body(Some(decl), |this| {
3590 let e = this.lower_expr(body);
3591 is_generator = this.is_generator;
3594 let generator_option = if is_generator {
3595 if !decl.inputs.is_empty() {
3600 "generators cannot have explicit arguments"
3602 this.sess.abort_if_errors();
3604 Some(match movability {
3605 Movability::Movable => hir::GeneratorMovability::Movable,
3606 Movability::Static => hir::GeneratorMovability::Static,
3609 if movability == Movability::Static {
3614 "closures cannot be static"
3620 this.lower_capture_clause(capture_clause),
3621 this.lower_fn_decl(decl, None, false, false),
3629 ExprKind::Block(ref blk, opt_label) => {
3630 hir::ExprBlock(self.lower_block(blk,
3631 opt_label.is_some()),
3632 self.lower_label(opt_label))
3634 ExprKind::Assign(ref el, ref er) => {
3635 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3637 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3638 self.lower_binop(op),
3639 P(self.lower_expr(el)),
3640 P(self.lower_expr(er)),
3642 ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3643 ExprKind::Index(ref el, ref er) => {
3644 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3646 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3647 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3648 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3649 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3650 let id = self.next_id();
3651 let e1 = self.lower_expr(e1);
3652 let e2 = self.lower_expr(e2);
3653 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], None, false));
3654 let ty = self.ty_path(id, span, hir::QPath::Resolved(None, ty_path));
3655 let new_seg = P(hir::PathSegment::from_name(Symbol::intern("new")));
3656 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3657 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3658 hir::ExprCall(new, hir_vec![e1, e2])
3660 ExprKind::Range(ref e1, ref e2, lims) => {
3661 use syntax::ast::RangeLimits::*;
3663 let path = match (e1, e2, lims) {
3664 (&None, &None, HalfOpen) => "RangeFull",
3665 (&Some(..), &None, HalfOpen) => "RangeFrom",
3666 (&None, &Some(..), HalfOpen) => "RangeTo",
3667 (&Some(..), &Some(..), HalfOpen) => "Range",
3668 (&None, &Some(..), Closed) => "RangeToInclusive",
3669 (&Some(..), &Some(..), Closed) => unreachable!(),
3670 (_, &None, Closed) => self.diagnostic()
3671 .span_fatal(e.span, "inclusive range with no end")
3675 let fields = e1.iter()
3676 .map(|e| ("start", e))
3677 .chain(e2.iter().map(|e| ("end", e)))
3679 let expr = P(self.lower_expr(&e));
3681 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3682 let ident = Ident::new(Symbol::intern(s), unstable_span);
3683 self.field(ident, expr, unstable_span)
3685 .collect::<P<[hir::Field]>>();
3687 let is_unit = fields.is_empty();
3689 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3690 let struct_path = iter::once("ops")
3691 .chain(iter::once(path))
3692 .collect::<Vec<_>>();
3693 let struct_path = self.std_path(unstable_span, &struct_path, None, is_unit);
3694 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3696 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3702 hir::ExprPath(struct_path)
3704 hir::ExprStruct(struct_path, fields, None)
3706 span: unstable_span,
3707 attrs: e.attrs.clone(),
3710 ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3714 ParamMode::Optional,
3715 ImplTraitContext::Disallowed,
3717 ExprKind::Break(opt_label, ref opt_expr) => {
3718 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3721 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3724 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3728 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3731 ExprKind::Continue(opt_label) => {
3732 hir::ExprContinue(if self.is_in_loop_condition && opt_label.is_none() {
3735 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3738 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3741 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3742 ExprKind::InlineAsm(ref asm) => {
3743 let hir_asm = hir::InlineAsm {
3744 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3745 outputs: asm.outputs
3747 .map(|out| hir::InlineAsmOutput {
3748 constraint: out.constraint.clone(),
3750 is_indirect: out.is_indirect,
3753 asm: asm.asm.clone(),
3754 asm_str_style: asm.asm_str_style,
3755 clobbers: asm.clobbers.clone().into(),
3756 volatile: asm.volatile,
3757 alignstack: asm.alignstack,
3758 dialect: asm.dialect,
3761 let outputs = asm.outputs
3763 .map(|out| self.lower_expr(&out.expr))
3765 let inputs = asm.inputs
3767 .map(|&(_, ref input)| self.lower_expr(input))
3769 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3771 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3776 ParamMode::Optional,
3777 ImplTraitContext::Disallowed,
3779 fields.iter().map(|x| self.lower_field(x)).collect(),
3780 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3782 ExprKind::Paren(ref ex) => {
3783 let mut ex = self.lower_expr(ex);
3784 // include parens in span, but only if it is a super-span.
3785 if e.span.contains(ex.span) {
3788 // merge attributes into the inner expression.
3789 let mut attrs = e.attrs.clone();
3790 attrs.extend::<Vec<_>>(ex.attrs.into());
3795 ExprKind::Yield(ref opt_expr) => {
3796 self.is_generator = true;
3799 .map(|x| self.lower_expr(x))
3800 .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3801 hir::ExprYield(P(expr))
3804 // Desugar ExprIfLet
3805 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3806 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3809 // match <sub_expr> {
3811 // _ => [<else_opt> | ()]
3814 let mut arms = vec![];
3816 // `<pat> => <body>`
3818 let body = self.lower_block(body, false);
3819 let body_expr = P(self.expr_block(body, ThinVec::new()));
3820 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3821 arms.push(self.arm(pats, body_expr));
3824 // _ => [<else_opt>|()]
3826 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3827 let wildcard_pattern = self.pat_wild(e.span);
3828 let body = if let Some(else_expr) = wildcard_arm {
3829 P(self.lower_expr(else_expr))
3831 self.expr_tuple(e.span, hir_vec![])
3833 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3836 let contains_else_clause = else_opt.is_some();
3838 let sub_expr = P(self.lower_expr(sub_expr));
3843 hir::MatchSource::IfLetDesugar {
3844 contains_else_clause,
3849 // Desugar ExprWhileLet
3850 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3851 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3854 // [opt_ident]: loop {
3855 // match <sub_expr> {
3861 // Note that the block AND the condition are evaluated in the loop scope.
3862 // This is done to allow `break` from inside the condition of the loop.
3863 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3865 this.lower_block(body, false),
3866 this.expr_break(e.span, ThinVec::new()),
3867 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3871 // `<pat> => <body>`
3873 let body_expr = P(self.expr_block(body, ThinVec::new()));
3874 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3875 self.arm(pats, body_expr)
3880 let pat_under = self.pat_wild(e.span);
3881 self.arm(hir_vec![pat_under], break_expr)
3884 // `match <sub_expr> { ... }`
3885 let arms = hir_vec![pat_arm, break_arm];
3886 let match_expr = self.expr(
3888 hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3892 // `[opt_ident]: loop { ... }`
3893 let loop_block = P(self.block_expr(P(match_expr)));
3894 let loop_expr = hir::ExprLoop(
3896 self.lower_label(opt_label),
3897 hir::LoopSource::WhileLet,
3899 // add attributes to the outer returned expr node
3903 // Desugar ExprForLoop
3904 // From: `[opt_ident]: for <pat> in <head> <body>`
3905 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3909 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3911 // [opt_ident]: loop {
3913 // match ::std::iter::Iterator::next(&mut iter) {
3914 // ::std::option::Option::Some(val) => __next = val,
3915 // ::std::option::Option::None => break
3917 // let <pat> = __next;
3918 // StmtExpr(<body>);
3926 let head = self.lower_expr(head);
3927 let head_sp = head.span;
3929 let iter = self.str_to_ident("iter");
3931 let next_ident = self.str_to_ident("__next");
3932 let next_pat = self.pat_ident_binding_mode(
3935 hir::BindingAnnotation::Mutable,
3938 // `::std::option::Option::Some(val) => next = val`
3940 let val_ident = self.str_to_ident("val");
3941 let val_pat = self.pat_ident(pat.span, val_ident);
3942 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
3943 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
3944 let assign = P(self.expr(
3946 hir::ExprAssign(next_expr, val_expr),
3949 let some_pat = self.pat_some(pat.span, val_pat);
3950 self.arm(hir_vec![some_pat], assign)
3953 // `::std::option::Option::None => break`
3956 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
3957 let pat = self.pat_none(e.span);
3958 self.arm(hir_vec![pat], break_expr)
3963 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
3965 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
3967 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
3968 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
3969 let next_path = &["iter", "Iterator", "next"];
3970 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
3971 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
3972 let arms = hir_vec![pat_arm, break_arm];
3976 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
3980 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
3982 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
3986 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
3988 // `let <pat> = __next`
3989 let pat = self.lower_pat(pat);
3990 let pat_let = self.stmt_let_pat(
3994 hir::LocalSource::ForLoopDesugar,
3997 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
3998 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
3999 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
4001 let loop_block = P(self.block_all(
4003 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4007 // `[opt_ident]: loop { ... }`
4008 let loop_expr = hir::ExprLoop(
4010 self.lower_label(opt_label),
4011 hir::LoopSource::ForLoop,
4013 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4014 let loop_expr = P(hir::Expr {
4019 attrs: ThinVec::new(),
4022 // `mut iter => { ... }`
4023 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4025 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4026 let into_iter_expr = {
4027 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4028 let into_iter = P(self.expr_std_path(
4029 head_sp, into_iter_path, None, ThinVec::new()));
4030 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4033 let match_expr = P(self.expr_match(
4037 hir::MatchSource::ForLoopDesugar,
4040 // `{ let _result = ...; _result }`
4041 // underscore prevents an unused_variables lint if the head diverges
4042 let result_ident = self.str_to_ident("_result");
4043 let (let_stmt, let_stmt_binding) =
4044 self.stmt_let(e.span, false, result_ident, match_expr);
4046 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4047 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4048 // add the attributes to the outer returned expr node
4049 return self.expr_block(block, e.attrs.clone());
4052 // Desugar ExprKind::Try
4054 ExprKind::Try(ref sub_expr) => {
4057 // match Try::into_result(<expr>) {
4058 // Ok(val) => #[allow(unreachable_code)] val,
4059 // Err(err) => #[allow(unreachable_code)]
4060 // // If there is an enclosing `catch {...}`
4061 // break 'catch_target Try::from_error(From::from(err)),
4063 // return Try::from_error(From::from(err)),
4067 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4069 // Try::into_result(<expr>)
4072 let sub_expr = self.lower_expr(sub_expr);
4074 let path = &["ops", "Try", "into_result"];
4075 let path = P(self.expr_std_path(
4076 unstable_span, path, None, ThinVec::new()));
4077 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4080 // #[allow(unreachable_code)]
4082 // allow(unreachable_code)
4084 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4085 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4086 let uc_nested = attr::mk_nested_word_item(uc_ident);
4087 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4089 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4091 let attrs = vec![attr];
4093 // Ok(val) => #[allow(unreachable_code)] val,
4095 let val_ident = self.str_to_ident("val");
4096 let val_pat = self.pat_ident(e.span, val_ident);
4097 let val_expr = P(self.expr_ident_with_attrs(
4101 ThinVec::from(attrs.clone()),
4103 let ok_pat = self.pat_ok(e.span, val_pat);
4105 self.arm(hir_vec![ok_pat], val_expr)
4108 // Err(err) => #[allow(unreachable_code)]
4109 // return Try::from_error(From::from(err)),
4111 let err_ident = self.str_to_ident("err");
4112 let err_local = self.pat_ident(e.span, err_ident);
4114 let path = &["convert", "From", "from"];
4115 let from = P(self.expr_std_path(
4116 e.span, path, None, ThinVec::new()));
4117 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4119 self.expr_call(e.span, from, hir_vec![err_expr])
4122 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4123 let thin_attrs = ThinVec::from(attrs);
4124 let catch_scope = self.catch_scopes.last().map(|x| *x);
4125 let ret_expr = if let Some(catch_node) = catch_scope {
4131 target_id: Ok(catch_node),
4133 Some(from_err_expr),
4138 P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
4141 let err_pat = self.pat_err(e.span, err_local);
4142 self.arm(hir_vec![err_pat], ret_expr)
4147 hir_vec![err_arm, ok_arm],
4148 hir::MatchSource::TryDesugar,
4152 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4155 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4162 attrs: e.attrs.clone(),
4166 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
4167 SmallVector::one(match s.node {
4168 StmtKind::Local(ref l) => Spanned {
4169 node: hir::StmtDecl(
4171 node: hir::DeclLocal(self.lower_local(l)),
4174 self.lower_node_id(s.id).node_id,
4178 StmtKind::Item(ref it) => {
4179 // Can only use the ID once.
4180 let mut id = Some(s.id);
4181 return self.lower_item_id(it)
4183 .map(|item_id| Spanned {
4184 node: hir::StmtDecl(
4186 node: hir::DeclItem(item_id),
4190 .map(|id| self.lower_node_id(id).node_id)
4191 .unwrap_or_else(|| self.next_id().node_id),
4197 StmtKind::Expr(ref e) => Spanned {
4198 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4201 StmtKind::Semi(ref e) => Spanned {
4202 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4205 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4209 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4211 CaptureBy::Value => hir::CaptureByValue,
4212 CaptureBy::Ref => hir::CaptureByRef,
4216 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4217 /// the address space of that item instead of the item currently being
4218 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4219 /// lower a `Visibility` value although we haven't lowered the owning
4220 /// `ImplItem` in question yet.
4221 fn lower_visibility(
4224 explicit_owner: Option<NodeId>,
4225 ) -> hir::Visibility {
4227 VisibilityKind::Public => hir::Public,
4228 VisibilityKind::Crate(sugar) => hir::Visibility::Crate(sugar),
4229 VisibilityKind::Restricted { ref path, id, .. } => hir::Visibility::Restricted {
4230 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4231 id: if let Some(owner) = explicit_owner {
4232 self.lower_node_id_with_owner(id, owner).node_id
4234 self.lower_node_id(id).node_id
4237 VisibilityKind::Inherited => hir::Inherited,
4241 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4243 Defaultness::Default => hir::Defaultness::Default {
4244 has_value: has_value,
4246 Defaultness::Final => {
4248 hir::Defaultness::Final
4253 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4255 BlockCheckMode::Default => hir::DefaultBlock,
4256 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4260 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4262 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4263 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4264 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4265 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4269 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4271 CompilerGenerated => hir::CompilerGenerated,
4272 UserProvided => hir::UserProvided,
4276 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4278 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4279 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4283 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4285 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4286 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4290 // Helper methods for building HIR.
4292 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4301 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4303 id: self.next_id().node_id,
4307 is_shorthand: false,
4311 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4312 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
4313 P(self.expr(span, expr_break, attrs))
4320 args: hir::HirVec<hir::Expr>,
4322 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
4325 fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
4326 self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
4329 fn expr_ident_with_attrs(
4334 attrs: ThinVec<Attribute>,
4336 let expr_path = hir::ExprPath(hir::QPath::Resolved(
4340 def: Def::Local(binding),
4341 segments: hir_vec![hir::PathSegment::from_name(id)],
4345 self.expr(span, expr_path, attrs)
4348 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4349 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
4355 components: &[&str],
4356 params: Option<P<hir::GenericArgs>>,
4357 attrs: ThinVec<Attribute>,
4359 let path = self.std_path(span, components, params, true);
4362 hir::ExprPath(hir::QPath::Resolved(None, P(path))),
4371 arms: hir::HirVec<hir::Arm>,
4372 source: hir::MatchSource,
4374 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
4377 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4378 self.expr(b.span, hir::ExprBlock(b, None), attrs)
4381 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4382 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
4385 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
4386 let LoweredNodeId { node_id, hir_id } = self.next_id();
4399 ex: Option<P<hir::Expr>>,
4401 source: hir::LocalSource,
4403 let LoweredNodeId { node_id, hir_id } = self.next_id();
4405 let local = P(hir::Local {
4412 attrs: ThinVec::new(),
4415 let decl = respan(sp, hir::DeclLocal(local));
4416 respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
4425 ) -> (hir::Stmt, NodeId) {
4426 let pat = if mutbl {
4427 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4429 self.pat_ident(sp, ident)
4431 let pat_id = pat.id;
4433 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4438 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4439 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4445 stmts: hir::HirVec<hir::Stmt>,
4446 expr: Option<P<hir::Expr>>,
4448 let LoweredNodeId { node_id, hir_id } = self.next_id();
4455 rules: hir::DefaultBlock,
4457 targeted_by_break: false,
4462 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4463 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4466 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4467 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4470 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4471 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4474 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4475 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4481 components: &[&str],
4482 subpats: hir::HirVec<P<hir::Pat>>,
4484 let path = self.std_path(span, components, None, true);
4485 let qpath = hir::QPath::Resolved(None, P(path));
4486 let pt = if subpats.is_empty() {
4487 hir::PatKind::Path(qpath)
4489 hir::PatKind::TupleStruct(qpath, subpats, None)
4494 fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
4495 self.pat_ident_binding_mode(span, name, hir::BindingAnnotation::Unannotated)
4498 fn pat_ident_binding_mode(
4502 bm: hir::BindingAnnotation,
4504 let LoweredNodeId { node_id, hir_id } = self.next_id();
4509 node: hir::PatKind::Binding(bm, node_id, Spanned { span, node: name }, None),
4514 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4515 self.pat(span, hir::PatKind::Wild)
4518 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4519 let LoweredNodeId { node_id, hir_id } = self.next_id();
4528 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4529 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4530 /// The path is also resolved according to `is_value`.
4534 components: &[&str],
4535 params: Option<P<hir::GenericArgs>>,
4539 .resolve_str_path(span, self.crate_root, components, params, is_value)
4542 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
4544 let node = match qpath {
4545 hir::QPath::Resolved(None, path) => {
4546 // Turn trait object paths into `TyTraitObject` instead.
4547 if let Def::Trait(_) = path.def {
4548 let principal = hir::PolyTraitRef {
4549 bound_generic_params: hir::HirVec::new(),
4550 trait_ref: hir::TraitRef {
4551 path: path.and_then(|path| path),
4557 // The original ID is taken by the `PolyTraitRef`,
4558 // so the `Ty` itself needs a different one.
4559 id = self.next_id();
4560 hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4562 hir::TyPath(hir::QPath::Resolved(None, path))
4565 _ => hir::TyPath(qpath),
4575 /// Invoked to create the lifetime argument for a type `&T`
4576 /// with no explicit lifetime.
4577 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4578 match self.anonymous_lifetime_mode {
4579 // Intercept when we are in an impl header and introduce an in-band lifetime.
4580 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4582 AnonymousLifetimeMode::CreateParameter => {
4583 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4585 id: self.next_id().node_id,
4587 name: hir::LifetimeName::Param(fresh_name),
4591 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4595 /// Invoked to create the lifetime argument(s) for a path like
4596 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4597 /// sorts of cases are deprecated. This may therefore report a warning or an
4598 /// error, depending on the mode.
4599 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4600 match self.anonymous_lifetime_mode {
4601 // NB. We intentionally ignore the create-parameter mode here
4602 // and instead "pass through" to resolve-lifetimes, which will then
4603 // report an error. This is because we don't want to support
4604 // impl elision for deprecated forms like
4606 // impl Foo for std::cell::Ref<u32> // note lack of '_
4607 AnonymousLifetimeMode::CreateParameter => {}
4609 // This is the normal case.
4610 AnonymousLifetimeMode::PassThrough => {}
4614 .map(|_| self.new_implicit_lifetime(span))
4618 /// Invoked to create the lifetime argument(s) for an elided trait object
4619 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4620 /// when the bound is written, even if it is written with `'_` like in
4621 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4622 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4623 match self.anonymous_lifetime_mode {
4624 // NB. We intentionally ignore the create-parameter mode here.
4625 // and instead "pass through" to resolve-lifetimes, which will apply
4626 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4627 // do not act like other elided lifetimes. In other words, given this:
4629 // impl Foo for Box<dyn Debug>
4631 // we do not introduce a fresh `'_` to serve as the bound, but instead
4632 // ultimately translate to the equivalent of:
4634 // impl Foo for Box<dyn Debug + 'static>
4636 // `resolve_lifetime` has the code to make that happen.
4637 AnonymousLifetimeMode::CreateParameter => {}
4639 // This is the normal case.
4640 AnonymousLifetimeMode::PassThrough => {}
4643 self.new_implicit_lifetime(span)
4646 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4648 id: self.next_id().node_id,
4650 name: hir::LifetimeName::Implicit,
4654 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4655 self.sess.buffer_lint_with_diagnostic(
4656 builtin::BARE_TRAIT_OBJECTS,
4659 "trait objects without an explicit `dyn` are deprecated",
4660 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4664 fn wrap_in_try_constructor(
4666 method: &'static str,
4668 unstable_span: Span,
4670 let path = &["ops", "Try", method];
4671 let from_err = P(self.expr_std_path(unstable_span, path, None,
4673 P(self.expr_call(e.span, from_err, hir_vec![e]))
4677 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4678 // Sorting by span ensures that we get things in order within a
4679 // file, and also puts the files in a sensible order.
4680 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4681 body_ids.sort_by_key(|b| bodies[b].value.span);