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_direct(&ty, itctx)),
1081 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1082 P(self.lower_ty_direct(t, itctx))
1085 fn lower_ty_direct(&mut self, t: &Ty, itctx: ImplTraitContext) -> hir::Ty {
1086 let kind = match t.node {
1087 TyKind::Infer => hir::TyInfer,
1088 TyKind::Err => hir::TyErr,
1089 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty, itctx)),
1090 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt, itctx)),
1091 TyKind::Rptr(ref region, ref mt) => {
1092 let span = t.span.shrink_to_lo();
1093 let lifetime = match *region {
1094 Some(ref lt) => self.lower_lifetime(lt),
1095 None => self.elided_ref_lifetime(span),
1097 hir::TyRptr(lifetime, self.lower_mt(mt, itctx))
1099 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1102 this.with_anonymous_lifetime_mode(
1103 AnonymousLifetimeMode::PassThrough,
1105 hir::TyBareFn(P(hir::BareFnTy {
1106 generic_params: this.lower_generic_params(
1109 ImplTraitContext::Disallowed,
1111 unsafety: this.lower_unsafety(f.unsafety),
1113 decl: this.lower_fn_decl(&f.decl, None, false, false),
1114 arg_names: this.lower_fn_args_to_names(&f.decl),
1120 TyKind::Never => hir::TyNever,
1121 TyKind::Tup(ref tys) => {
1122 hir::TyTup(tys.iter().map(|ty| self.lower_ty_direct(ty, itctx)).collect())
1124 TyKind::Paren(ref ty) => {
1125 return self.lower_ty_direct(ty, itctx);
1127 TyKind::Path(ref qself, ref path) => {
1128 let id = self.lower_node_id(t.id);
1129 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1130 let ty = self.ty_path(id, t.span, qpath);
1131 if let hir::TyTraitObject(..) = ty.node {
1132 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1136 TyKind::ImplicitSelf => hir::TyPath(hir::QPath::Resolved(
1139 def: self.expect_full_def(t.id),
1140 segments: hir_vec![hir::PathSegment::from_name(keywords::SelfType.name())],
1144 TyKind::Array(ref ty, ref length) => {
1145 hir::TyArray(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1147 TyKind::Typeof(ref expr) => {
1148 hir::TyTypeof(self.lower_anon_const(expr))
1150 TyKind::TraitObject(ref bounds, kind) => {
1151 let mut lifetime_bound = None;
1154 .filter_map(|bound| match *bound {
1155 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1156 Some(self.lower_poly_trait_ref(ty, itctx))
1158 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1159 GenericBound::Outlives(ref lifetime) => {
1160 if lifetime_bound.is_none() {
1161 lifetime_bound = Some(self.lower_lifetime(lifetime));
1167 let lifetime_bound =
1168 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1169 if kind != TraitObjectSyntax::Dyn {
1170 self.maybe_lint_bare_trait(t.span, t.id, false);
1172 hir::TyTraitObject(bounds, lifetime_bound)
1174 TyKind::ImplTrait(ref bounds) => {
1177 ImplTraitContext::Existential(fn_def_id) => {
1178 self.lower_existential_impl_trait(
1179 span, fn_def_id, |this| this.lower_param_bounds(bounds, itctx))
1181 ImplTraitContext::Universal(def_id) => {
1182 let def_node_id = self.next_id().node_id;
1184 // Add a definition for the in-band TyParam
1185 let def_index = self.resolver.definitions().create_def_with_parent(
1188 DefPathData::UniversalImplTrait,
1189 DefIndexAddressSpace::High,
1194 let hir_bounds = self.lower_param_bounds(bounds, itctx);
1195 // Set the name to `impl Bound1 + Bound2`
1196 let name = Symbol::intern(&pprust::ty_to_string(t));
1197 self.in_band_ty_params.push(hir::GenericParam {
1199 name: ParamName::Plain(name),
1201 pure_wrt_drop: false,
1204 kind: hir::GenericParamKind::Type {
1206 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1210 hir::TyPath(hir::QPath::Resolved(
1214 def: Def::TyParam(DefId::local(def_index)),
1215 segments: hir_vec![hir::PathSegment::from_name(name)],
1219 ImplTraitContext::Disallowed => {
1224 "`impl Trait` not allowed outside of function \
1225 and inherent method return types"
1231 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1234 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1243 fn lower_existential_impl_trait(
1247 lower_bounds: impl FnOnce(&mut LoweringContext) -> hir::GenericBounds,
1249 // We need to manually repeat the code of `next_id` because the lowering
1250 // needs to happen while the owner_id is pointing to the item itself,
1251 // because items are their own owners
1252 let exist_ty_node_id = self.sess.next_node_id();
1254 // Make sure we know that some funky desugaring has been going on here.
1255 // This is a first: there is code in other places like for loop
1256 // desugaring that explicitly states that we don't want to track that.
1257 // Not tracking it makes lints in rustc and clippy very fragile as
1258 // frequently opened issues show.
1259 let exist_ty_span = self.allow_internal_unstable(
1260 CompilerDesugaringKind::ExistentialReturnType,
1264 // Pull a new definition from the ether
1265 let exist_ty_def_index = self
1268 .create_def_with_parent(
1271 DefPathData::ExistentialImplTrait,
1272 DefIndexAddressSpace::High,
1277 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1279 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1281 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1287 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1288 let exist_ty_item_kind = hir::ItemExistential(hir::ExistTy {
1289 generics: hir::Generics {
1290 params: lifetime_defs,
1291 where_clause: hir::WhereClause {
1292 id: lctx.next_id().node_id,
1293 predicates: Vec::new().into(),
1298 impl_trait_fn: Some(fn_def_id),
1300 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1301 // Generate an `existential type Foo: Trait;` declaration
1302 trace!("creating existential type with id {:#?}", exist_ty_id);
1304 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1305 let exist_ty_item = hir::Item {
1306 id: exist_ty_id.node_id,
1307 hir_id: exist_ty_id.hir_id,
1308 name: keywords::Invalid.name(),
1309 attrs: Default::default(),
1310 node: exist_ty_item_kind,
1311 vis: hir::Visibility::Inherited,
1312 span: exist_ty_span,
1315 // Insert the item into the global list. This usually happens
1316 // automatically for all AST items. But this existential type item
1317 // does not actually exist in the AST.
1318 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1320 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1321 hir::TyImplTraitExistential(
1323 id: exist_ty_id.node_id
1325 DefId::local(exist_ty_def_index),
1331 fn lifetimes_from_impl_trait_bounds(
1333 exist_ty_id: NodeId,
1334 parent_index: DefIndex,
1335 bounds: &hir::GenericBounds,
1336 ) -> (HirVec<hir::Lifetime>, HirVec<hir::GenericParam>) {
1337 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1338 // appear in the bounds, excluding lifetimes that are created within the bounds.
1339 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1340 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1341 context: &'r mut LoweringContext<'a>,
1343 exist_ty_id: NodeId,
1344 collect_elided_lifetimes: bool,
1345 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1346 already_defined_lifetimes: HashSet<hir::LifetimeName>,
1347 output_lifetimes: Vec<hir::Lifetime>,
1348 output_lifetime_params: Vec<hir::GenericParam>,
1351 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1352 fn nested_visit_map<'this>(
1354 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1355 hir::intravisit::NestedVisitorMap::None
1358 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1359 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1360 if parameters.parenthesized {
1361 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1362 self.collect_elided_lifetimes = false;
1363 hir::intravisit::walk_generic_args(self, span, parameters);
1364 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1366 hir::intravisit::walk_generic_args(self, span, parameters);
1370 fn visit_ty(&mut self, t: &'v hir::Ty) {
1371 // Don't collect elided lifetimes used inside of `fn()` syntax
1372 if let &hir::Ty_::TyBareFn(_) = &t.node {
1373 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1374 self.collect_elided_lifetimes = false;
1376 // Record the "stack height" of `for<'a>` lifetime bindings
1377 // to be able to later fully undo their introduction.
1378 let old_len = self.currently_bound_lifetimes.len();
1379 hir::intravisit::walk_ty(self, t);
1380 self.currently_bound_lifetimes.truncate(old_len);
1382 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1384 hir::intravisit::walk_ty(self, t);
1388 fn visit_poly_trait_ref(
1390 trait_ref: &'v hir::PolyTraitRef,
1391 modifier: hir::TraitBoundModifier,
1393 // Record the "stack height" of `for<'a>` lifetime bindings
1394 // to be able to later fully undo their introduction.
1395 let old_len = self.currently_bound_lifetimes.len();
1396 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1397 self.currently_bound_lifetimes.truncate(old_len);
1400 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1401 // Record the introduction of 'a in `for<'a> ...`
1402 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1403 // Introduce lifetimes one at a time so that we can handle
1404 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1405 let lt_name = hir::LifetimeName::Param(param.name);
1406 self.currently_bound_lifetimes.push(lt_name);
1409 hir::intravisit::walk_generic_param(self, param);
1412 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1413 let name = match lifetime.name {
1414 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1415 if self.collect_elided_lifetimes {
1416 // Use `'_` for both implicit and underscore lifetimes in
1417 // `abstract type Foo<'_>: SomeTrait<'_>;`
1418 hir::LifetimeName::Underscore
1423 hir::LifetimeName::Param(_) => lifetime.name,
1424 hir::LifetimeName::Static => return,
1427 if !self.currently_bound_lifetimes.contains(&name)
1428 && !self.already_defined_lifetimes.contains(&name) {
1429 self.already_defined_lifetimes.insert(name);
1431 self.output_lifetimes.push(hir::Lifetime {
1432 id: self.context.next_id().node_id,
1433 span: lifetime.span,
1437 // We need to manually create the ids here, because the
1438 // definitions will go into the explicit `existential type`
1439 // declaration and thus need to have their owner set to that item
1440 let def_node_id = self.context.sess.next_node_id();
1441 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1442 self.context.resolver.definitions().create_def_with_parent(
1445 DefPathData::LifetimeParam(name.name().as_interned_str()),
1446 DefIndexAddressSpace::High,
1451 let name = match name {
1452 hir::LifetimeName::Underscore => {
1453 hir::ParamName::Plain(keywords::UnderscoreLifetime.name())
1455 hir::LifetimeName::Param(param_name) => param_name,
1456 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1459 self.output_lifetime_params.push(hir::GenericParam {
1462 span: lifetime.span,
1463 pure_wrt_drop: false,
1466 kind: hir::GenericParamKind::Lifetime {
1474 let mut lifetime_collector = ImplTraitLifetimeCollector {
1476 parent: parent_index,
1478 collect_elided_lifetimes: true,
1479 currently_bound_lifetimes: Vec::new(),
1480 already_defined_lifetimes: HashSet::new(),
1481 output_lifetimes: Vec::new(),
1482 output_lifetime_params: Vec::new(),
1485 for bound in bounds {
1486 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1490 lifetime_collector.output_lifetimes.into(),
1491 lifetime_collector.output_lifetime_params.into(),
1495 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1500 .map(|x| self.lower_foreign_item(x))
1505 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1512 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1514 node: hir::Variant_ {
1515 name: v.node.ident.name,
1516 attrs: self.lower_attrs(&v.node.attrs),
1517 data: self.lower_variant_data(&v.node.data),
1518 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1527 qself: &Option<QSelf>,
1529 param_mode: ParamMode,
1530 itctx: ImplTraitContext,
1532 let qself_position = qself.as_ref().map(|q| q.position);
1533 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx));
1535 let resolution = self.resolver
1537 .unwrap_or(PathResolution::new(Def::Err));
1539 let proj_start = p.segments.len() - resolution.unresolved_segments();
1540 let path = P(hir::Path {
1541 def: resolution.base_def(),
1542 segments: p.segments[..proj_start]
1545 .map(|(i, segment)| {
1546 let param_mode = match (qself_position, param_mode) {
1547 (Some(j), ParamMode::Optional) if i < j => {
1548 // This segment is part of the trait path in a
1549 // qualified path - one of `a`, `b` or `Trait`
1550 // in `<X as a::b::Trait>::T::U::method`.
1556 // Figure out if this is a type/trait segment,
1557 // which may need lifetime elision performed.
1558 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1559 krate: def_id.krate,
1560 index: this.def_key(def_id).parent.expect("missing parent"),
1562 let type_def_id = match resolution.base_def() {
1563 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1564 Some(parent_def_id(self, def_id))
1566 Def::Variant(def_id) if i + 1 == proj_start => {
1567 Some(parent_def_id(self, def_id))
1570 | Def::Union(def_id)
1572 | Def::TyAlias(def_id)
1573 | Def::Trait(def_id) if i + 1 == proj_start =>
1579 let parenthesized_generic_args = match resolution.base_def() {
1580 // `a::b::Trait(Args)`
1581 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1582 // `a::b::Trait(Args)::TraitItem`
1583 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1584 if i + 2 == proj_start =>
1586 ParenthesizedGenericArgs::Ok
1588 // Avoid duplicated errors
1589 Def::Err => ParenthesizedGenericArgs::Ok,
1595 | Def::Variant(..) if i + 1 == proj_start =>
1597 ParenthesizedGenericArgs::Err
1599 // A warning for now, for compatibility reasons
1600 _ => ParenthesizedGenericArgs::Warn,
1603 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1604 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1607 assert!(!def_id.is_local());
1609 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1610 let n = item_generics.own_counts().lifetimes;
1611 self.type_def_lifetime_params.insert(def_id, n);
1614 self.lower_path_segment(
1619 parenthesized_generic_args,
1627 // Simple case, either no projections, or only fully-qualified.
1628 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1629 if resolution.unresolved_segments() == 0 {
1630 return hir::QPath::Resolved(qself, path);
1633 // Create the innermost type that we're projecting from.
1634 let mut ty = if path.segments.is_empty() {
1635 // If the base path is empty that means there exists a
1636 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1637 qself.expect("missing QSelf for <T>::...")
1639 // Otherwise, the base path is an implicit `Self` type path,
1640 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1641 // `<I as Iterator>::Item::default`.
1642 let new_id = self.next_id();
1643 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1646 // Anything after the base path are associated "extensions",
1647 // out of which all but the last one are associated types,
1648 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1649 // * base path is `std::vec::Vec<T>`
1650 // * "extensions" are `IntoIter`, `Item` and `clone`
1651 // * type nodes are:
1652 // 1. `std::vec::Vec<T>` (created above)
1653 // 2. `<std::vec::Vec<T>>::IntoIter`
1654 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1655 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1656 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1657 let segment = P(self.lower_path_segment(
1662 ParenthesizedGenericArgs::Warn,
1665 let qpath = hir::QPath::TypeRelative(ty, segment);
1667 // It's finished, return the extension of the right node type.
1668 if i == p.segments.len() - 1 {
1672 // Wrap the associated extension in another type node.
1673 let new_id = self.next_id();
1674 ty = P(self.ty_path(new_id, p.span, qpath));
1677 // Should've returned in the for loop above.
1680 "lower_qpath: no final extension segment in {}..{}",
1686 fn lower_path_extra(
1691 param_mode: ParamMode,
1695 segments: p.segments
1698 self.lower_path_segment(
1703 ParenthesizedGenericArgs::Err,
1704 ImplTraitContext::Disallowed,
1707 .chain(name.map(|name| hir::PathSegment::from_name(name)))
1713 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1714 let def = self.expect_full_def(id);
1715 self.lower_path_extra(def, p, None, param_mode)
1718 fn lower_path_segment(
1721 segment: &PathSegment,
1722 param_mode: ParamMode,
1723 expected_lifetimes: usize,
1724 parenthesized_generic_args: ParenthesizedGenericArgs,
1725 itctx: ImplTraitContext,
1726 ) -> hir::PathSegment {
1727 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1728 let msg = "parenthesized parameters may only be used with a trait";
1729 match **generic_args {
1730 GenericArgs::AngleBracketed(ref data) => {
1731 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1733 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1734 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1735 ParenthesizedGenericArgs::Warn => {
1736 self.sess.buffer_lint(
1737 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1742 (hir::GenericArgs::none(), true)
1744 ParenthesizedGenericArgs::Err => {
1745 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1746 .span_label(data.span, "only traits may use parentheses")
1748 (hir::GenericArgs::none(), true)
1753 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1756 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1757 GenericArg::Lifetime(_) => true,
1760 if !generic_args.parenthesized && !has_lifetimes {
1762 self.elided_path_lifetimes(path_span, expected_lifetimes)
1764 .map(|lt| GenericArg::Lifetime(lt))
1765 .chain(generic_args.args.into_iter())
1769 hir::PathSegment::new(
1770 self.lower_ident(segment.ident),
1776 fn lower_angle_bracketed_parameter_data(
1778 data: &AngleBracketedArgs,
1779 param_mode: ParamMode,
1780 itctx: ImplTraitContext,
1781 ) -> (hir::GenericArgs, bool) {
1782 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1783 let has_types = args.iter().any(|arg| match arg {
1784 ast::GenericArg::Type(_) => true,
1788 args: args.iter().map(|a| self.lower_generic_arg(a, itctx)).collect(),
1789 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(),
1790 parenthesized: false,
1792 !has_types && param_mode == ParamMode::Optional)
1795 fn lower_parenthesized_parameter_data(
1797 data: &ParenthesisedArgs,
1798 ) -> (hir::GenericArgs, bool) {
1799 // Switch to `PassThrough` mode for anonymous lifetimes: this
1800 // means that we permit things like `&Ref<T>`, where `Ref` has
1801 // a hidden lifetime parameter. This is needed for backwards
1802 // compatibility, even in contexts like an impl header where
1803 // we generally don't permit such things (see #51008).
1804 self.with_anonymous_lifetime_mode(
1805 AnonymousLifetimeMode::PassThrough,
1807 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1808 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1809 let inputs = inputs.iter().map(|ty| this.lower_ty_direct(ty, DISALLOWED)).collect();
1810 let mk_tup = |this: &mut Self, tys, span| {
1811 let LoweredNodeId { node_id, hir_id } = this.next_id();
1812 hir::Ty { node: hir::TyTup(tys), id: node_id, hir_id, span }
1817 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1820 id: this.next_id().node_id,
1821 name: Symbol::intern(FN_OUTPUT_NAME),
1824 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1825 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1826 span: output.as_ref().map_or(span, |ty| ty.span),
1829 parenthesized: true,
1837 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1838 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1844 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1845 pat: self.lower_pat(&l.pat),
1846 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1848 attrs: l.attrs.clone(),
1849 source: hir::LocalSource::Normal,
1853 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1855 Mutability::Mutable => hir::MutMutable,
1856 Mutability::Immutable => hir::MutImmutable,
1860 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1861 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1865 pat: self.lower_pat(&arg.pat),
1869 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Spanned<Name>> {
1872 .map(|arg| match arg.pat.node {
1873 PatKind::Ident(_, ident, None) => respan(ident.span, ident.name),
1874 _ => respan(arg.pat.span, keywords::Invalid.name()),
1879 // Lowers a function declaration.
1881 // decl: the unlowered (ast) function declaration.
1882 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1883 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1884 // make_ret_async is true.
1885 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1886 // This guards against trait declarations and implementations where impl Trait is
1888 // make_ret_async: if enabled, converts `-> T` into `-> impl Future<Output = T>` in the
1889 // return type. This is used for `async fn` declarations.
1893 fn_def_id: Option<DefId>,
1894 impl_trait_return_allow: bool,
1895 make_ret_async: bool,
1896 ) -> P<hir::FnDecl> {
1897 let inputs = decl.inputs
1900 if let Some(def_id) = fn_def_id {
1901 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(def_id))
1903 self.lower_ty_direct(&arg.ty, ImplTraitContext::Disallowed)
1906 .collect::<HirVec<_>>();
1908 let output = if make_ret_async {
1909 self.lower_async_fn_ret_ty(
1910 &inputs, &decl.output, fn_def_id.expect("make_ret_async but no fn_def_id"))
1913 FunctionRetTy::Ty(ref ty) => match fn_def_id {
1914 Some(def_id) if impl_trait_return_allow => {
1915 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1917 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1919 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1926 variadic: decl.variadic,
1927 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1928 TyKind::ImplicitSelf => true,
1929 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1935 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
1937 // fn_span: the span of the async function declaration. Used for error reporting.
1938 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
1939 // output: unlowered output type (`T` in `-> T`)
1940 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
1941 fn lower_async_fn_ret_ty(
1944 output: &FunctionRetTy,
1946 ) -> hir::FunctionRetTy {
1947 // Get lifetimes used in the input arguments to the function. Our output type must also
1948 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
1949 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
1950 // is a subset of the other. We really want some new lifetime that is a subset of all input
1951 // lifetimes, but that doesn't exist at the moment.
1953 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
1954 context: &'r mut LoweringContext<'a>,
1955 // Lifetimes bound by HRTB
1956 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1957 // Whether to count elided lifetimes.
1958 // Disabled inside of `Fn` or `fn` syntax.
1959 collect_elided_lifetimes: bool,
1960 // The lifetime found.
1961 // Multiple different or elided lifetimes cannot appear in async fn for now.
1962 output_lifetime: Option<(hir::LifetimeName, Span)>,
1965 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
1966 fn nested_visit_map<'this>(
1968 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1969 hir::intravisit::NestedVisitorMap::None
1972 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1973 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1974 if parameters.parenthesized {
1975 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1976 self.collect_elided_lifetimes = false;
1977 hir::intravisit::walk_generic_args(self, span, parameters);
1978 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1980 hir::intravisit::walk_generic_args(self, span, parameters);
1984 fn visit_ty(&mut self, t: &'v hir::Ty) {
1985 // Don't collect elided lifetimes used inside of `fn()` syntax
1986 if let &hir::Ty_::TyBareFn(_) = &t.node {
1987 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1988 self.collect_elided_lifetimes = false;
1990 // Record the "stack height" of `for<'a>` lifetime bindings
1991 // to be able to later fully undo their introduction.
1992 let old_len = self.currently_bound_lifetimes.len();
1993 hir::intravisit::walk_ty(self, t);
1994 self.currently_bound_lifetimes.truncate(old_len);
1996 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1998 hir::intravisit::walk_ty(self, t);
2002 fn visit_poly_trait_ref(
2004 trait_ref: &'v hir::PolyTraitRef,
2005 modifier: hir::TraitBoundModifier,
2007 // Record the "stack height" of `for<'a>` lifetime bindings
2008 // to be able to later fully undo their introduction.
2009 let old_len = self.currently_bound_lifetimes.len();
2010 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2011 self.currently_bound_lifetimes.truncate(old_len);
2014 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2015 // Record the introduction of 'a in `for<'a> ...`
2016 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2017 // Introduce lifetimes one at a time so that we can handle
2018 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2019 let lt_name = hir::LifetimeName::Param(param.name);
2020 self.currently_bound_lifetimes.push(lt_name);
2023 hir::intravisit::walk_generic_param(self, param);
2026 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2027 let name = match lifetime.name {
2028 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2029 if self.collect_elided_lifetimes {
2030 // Use `'_` for both implicit and underscore lifetimes in
2031 // `abstract type Foo<'_>: SomeTrait<'_>;`
2032 hir::LifetimeName::Underscore
2037 hir::LifetimeName::Param(_) => lifetime.name,
2038 hir::LifetimeName::Static => return,
2041 if !self.currently_bound_lifetimes.contains(&name) {
2042 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2043 // We don't currently have a reliable way to desugar `async fn` with
2044 // multiple potentially unrelated input lifetimes into
2045 // `-> impl Trait + 'lt`, so we report an error in this case.
2046 if current_lt_name != name {
2049 current_lt_span.between(lifetime.span),
2051 "multiple different lifetimes used in arguments of `async fn`",
2053 .span_label(current_lt_span, "first lifetime here")
2054 .span_label(lifetime.span, "different lifetime here")
2055 .help("`async fn` can only accept borrowed values \
2056 with identical lifetimes")
2058 } else if current_lt_name.is_elided() && name.is_elided() {
2061 current_lt_span.between(lifetime.span),
2063 "multiple elided lifetimes used in arguments of `async fn`",
2065 .span_label(current_lt_span, "first lifetime here")
2066 .span_label(lifetime.span, "different lifetime here")
2067 .help("consider giving these arguments named lifetimes")
2071 self.output_lifetime = Some((name, lifetime.span));
2077 let bound_lifetime = {
2078 let mut lifetime_collector = AsyncFnLifetimeCollector {
2080 currently_bound_lifetimes: Vec::new(),
2081 collect_elided_lifetimes: true,
2082 output_lifetime: None,
2086 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2088 lifetime_collector.output_lifetime
2091 let span = match output {
2092 FunctionRetTy::Ty(ty) => ty.span,
2093 FunctionRetTy::Default(span) => *span,
2096 let impl_trait_ty = self.lower_existential_impl_trait(
2097 span, fn_def_id, |this| {
2098 let output_ty = match output {
2099 FunctionRetTy::Ty(ty) =>
2100 this.lower_ty(ty, ImplTraitContext::Existential(fn_def_id)),
2101 FunctionRetTy::Default(span) => {
2102 let LoweredNodeId { node_id, hir_id } = this.next_id();
2106 node: hir::TyTup(hir_vec![]),
2113 let future_params = P(hir::GenericArgs {
2115 bindings: hir_vec![hir::TypeBinding {
2116 name: Symbol::intern(FN_OUTPUT_NAME),
2118 id: this.next_id().node_id,
2121 parenthesized: false,
2125 this.std_path(span, &["future", "Future"], Some(future_params), false);
2127 let mut bounds = vec![
2128 hir::GenericBound::Trait(
2130 trait_ref: hir::TraitRef {
2132 ref_id: this.next_id().node_id,
2134 bound_generic_params: hir_vec![],
2137 hir::TraitBoundModifier::None
2141 if let Some((name, span)) = bound_lifetime {
2142 bounds.push(hir::GenericBound::Outlives(
2143 hir::Lifetime { id: this.next_id().node_id, name, span }));
2146 hir::HirVec::from(bounds)
2149 let LoweredNodeId { node_id, hir_id } = self.next_id();
2150 let impl_trait_ty = P(hir::Ty {
2152 node: impl_trait_ty,
2157 hir::FunctionRetTy::Return(impl_trait_ty)
2160 fn lower_param_bound(
2163 itctx: ImplTraitContext,
2164 ) -> hir::GenericBound {
2166 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2167 self.lower_poly_trait_ref(ty, itctx),
2168 self.lower_trait_bound_modifier(modifier),
2170 GenericBound::Outlives(ref lifetime) => {
2171 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2176 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2177 let span = l.ident.span;
2178 match self.lower_ident(l.ident) {
2179 x if x == "'static" => self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2180 x if x == "'_" => match self.anonymous_lifetime_mode {
2181 AnonymousLifetimeMode::CreateParameter => {
2182 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2183 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2186 AnonymousLifetimeMode::PassThrough => {
2187 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2191 self.maybe_collect_in_band_lifetime(span, name);
2192 let param_name = ParamName::Plain(name);
2193 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2198 fn new_named_lifetime(
2202 name: hir::LifetimeName,
2203 ) -> hir::Lifetime {
2205 id: self.lower_node_id(id).node_id,
2211 fn lower_generic_params(
2213 params: &Vec<GenericParam>,
2214 add_bounds: &NodeMap<Vec<GenericBound>>,
2215 itctx: ImplTraitContext,
2216 ) -> hir::HirVec<hir::GenericParam> {
2217 params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect()
2220 fn lower_generic_param(&mut self,
2221 param: &GenericParam,
2222 add_bounds: &NodeMap<Vec<GenericBound>>,
2223 itctx: ImplTraitContext)
2224 -> hir::GenericParam {
2225 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx);
2227 GenericParamKind::Lifetime => {
2228 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2229 self.is_collecting_in_band_lifetimes = false;
2231 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
2232 let param_name = match lt.name {
2233 hir::LifetimeName::Param(param_name) => param_name,
2234 _ => hir::ParamName::Plain(lt.name.name()),
2236 let param = hir::GenericParam {
2240 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2241 attrs: self.lower_attrs(¶m.attrs),
2243 kind: hir::GenericParamKind::Lifetime { in_band: false }
2246 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2250 GenericParamKind::Type { ref default, .. } => {
2251 let mut name = self.lower_ident(param.ident);
2253 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2254 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2255 // Instead, use gensym("Self") to create a distinct name that looks the same.
2256 if name == keywords::SelfType.name() {
2257 name = Symbol::gensym("Self");
2260 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2261 if !add_bounds.is_empty() {
2262 bounds = bounds.into_iter()
2263 .chain(self.lower_param_bounds(add_bounds, itctx).into_iter())
2268 id: self.lower_node_id(param.id).node_id,
2269 name: hir::ParamName::Plain(name),
2270 span: param.ident.span,
2271 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2272 attrs: self.lower_attrs(¶m.attrs),
2274 kind: hir::GenericParamKind::Type {
2275 default: default.as_ref().map(|x| {
2276 self.lower_ty(x, ImplTraitContext::Disallowed)
2278 synthetic: param.attrs.iter()
2279 .filter(|attr| attr.check_name("rustc_synthetic"))
2280 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2290 generics: &Generics,
2291 itctx: ImplTraitContext)
2294 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2295 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2296 // paths where report_error is called are also the only paths that advance to after
2297 // the match statement, so the error reporting could probably just be moved there.
2298 let mut add_bounds = NodeMap();
2299 for pred in &generics.where_clause.predicates {
2300 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2301 'next_bound: for bound in &bound_pred.bounds {
2302 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2303 let report_error = |this: &mut Self| {
2304 this.diagnostic().span_err(
2305 bound_pred.bounded_ty.span,
2306 "`?Trait` bounds are only permitted at the \
2307 point where a type parameter is declared",
2310 // Check if the where clause type is a plain type parameter.
2311 match bound_pred.bounded_ty.node {
2312 TyKind::Path(None, ref path)
2313 if path.segments.len() == 1
2314 && bound_pred.bound_generic_params.is_empty() =>
2316 if let Some(Def::TyParam(def_id)) = self.resolver
2317 .get_resolution(bound_pred.bounded_ty.id)
2318 .map(|d| d.base_def())
2320 if let Some(node_id) =
2321 self.resolver.definitions().as_local_node_id(def_id)
2323 for param in &generics.params {
2325 GenericParamKind::Type { .. } => {
2326 if node_id == param.id {
2327 add_bounds.entry(param.id)
2328 .or_insert(Vec::new())
2329 .push(bound.clone());
2330 continue 'next_bound;
2340 _ => report_error(self),
2348 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2349 where_clause: self.lower_where_clause(&generics.where_clause),
2350 span: generics.span,
2354 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2356 id: self.lower_node_id(wc.id).node_id,
2357 predicates: wc.predicates
2359 .map(|predicate| self.lower_where_predicate(predicate))
2364 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2366 WherePredicate::BoundPredicate(WhereBoundPredicate {
2367 ref bound_generic_params,
2372 self.with_in_scope_lifetime_defs(
2373 &bound_generic_params,
2375 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2376 bound_generic_params: this.lower_generic_params(
2377 bound_generic_params,
2379 ImplTraitContext::Disallowed,
2381 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2384 .filter_map(|bound| match *bound {
2385 // Ignore `?Trait` bounds.
2386 // Tthey were copied into type parameters already.
2387 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2388 _ => Some(this.lower_param_bound(
2390 ImplTraitContext::Disallowed,
2399 WherePredicate::RegionPredicate(WhereRegionPredicate {
2403 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2405 lifetime: self.lower_lifetime(lifetime),
2406 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2408 WherePredicate::EqPredicate(WhereEqPredicate {
2413 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2414 id: self.lower_node_id(id).node_id,
2415 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2416 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2422 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2424 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2428 .map(|f| self.lower_struct_field(f))
2430 self.lower_node_id(id).node_id,
2432 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2436 .map(|f| self.lower_struct_field(f))
2438 self.lower_node_id(id).node_id,
2440 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2444 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2445 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2446 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2447 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2451 ref_id: self.lower_node_id(p.ref_id).node_id,
2455 fn lower_poly_trait_ref(
2458 itctx: ImplTraitContext,
2459 ) -> hir::PolyTraitRef {
2460 let bound_generic_params =
2461 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx);
2462 let trait_ref = self.with_parent_impl_lifetime_defs(
2463 &bound_generic_params,
2464 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2468 bound_generic_params,
2474 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2477 id: self.lower_node_id(f.id).node_id,
2478 ident: match f.ident {
2479 Some(ident) => ident,
2480 // FIXME(jseyfried) positional field hygiene
2481 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2483 vis: self.lower_visibility(&f.vis, None),
2484 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2485 attrs: self.lower_attrs(&f.attrs),
2489 fn lower_field(&mut self, f: &Field) -> hir::Field {
2491 id: self.next_id().node_id,
2493 expr: P(self.lower_expr(&f.expr)),
2495 is_shorthand: f.is_shorthand,
2499 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2501 ty: self.lower_ty(&mt.ty, itctx),
2502 mutbl: self.lower_mutability(mt.mutbl),
2506 fn lower_param_bounds(&mut self, bounds: &[GenericBound], itctx: ImplTraitContext)
2507 -> hir::GenericBounds {
2508 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx)).collect()
2511 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2512 let mut expr = None;
2514 let mut stmts = vec![];
2516 for (index, stmt) in b.stmts.iter().enumerate() {
2517 if index == b.stmts.len() - 1 {
2518 if let StmtKind::Expr(ref e) = stmt.node {
2519 expr = Some(P(self.lower_expr(e)));
2521 stmts.extend(self.lower_stmt(stmt));
2524 stmts.extend(self.lower_stmt(stmt));
2528 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2533 stmts: stmts.into(),
2535 rules: self.lower_block_check_mode(&b.rules),
2538 recovered: b.recovered,
2546 attrs: &hir::HirVec<Attribute>,
2547 vis: &mut hir::Visibility,
2551 ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2552 ItemKind::Use(ref use_tree) => {
2553 // Start with an empty prefix
2556 span: use_tree.span,
2559 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2561 ItemKind::Static(ref t, m, ref e) => {
2562 let value = self.lower_body(None, |this| this.lower_expr(e));
2564 self.lower_ty(t, ImplTraitContext::Disallowed),
2565 self.lower_mutability(m),
2569 ItemKind::Const(ref t, ref e) => {
2570 let value = self.lower_body(None, |this| this.lower_expr(e));
2571 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2573 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2574 let fn_def_id = self.resolver.definitions().local_def_id(id);
2576 self.with_new_scopes(|this| {
2577 // Note: we don't need to change the return type from `T` to
2578 // `impl Future<Output = T>` here because lower_body
2579 // only cares about the input argument patterns in the function
2580 // declaration (decl), not the return types.
2581 let body_id = this.lower_body(Some(decl), |this| {
2582 if let IsAsync::Async(async_node_id) = header.asyncness {
2583 let async_expr = this.make_async_expr(
2584 CaptureBy::Value, async_node_id, None,
2586 let body = this.lower_block(body, false);
2587 this.expr_block(body, ThinVec::new())
2589 this.expr(body.span, async_expr, ThinVec::new())
2591 let body = this.lower_block(body, false);
2592 this.expr_block(body, ThinVec::new())
2596 let (generics, fn_decl) = this.add_in_band_defs(
2599 AnonymousLifetimeMode::PassThrough,
2600 |this| this.lower_fn_decl(
2601 decl, Some(fn_def_id), true, header.asyncness.is_async())
2606 this.lower_fn_header(header),
2612 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2613 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2614 ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2615 ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2616 self.lower_ty(t, ImplTraitContext::Disallowed),
2617 self.lower_generics(generics, ImplTraitContext::Disallowed),
2619 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2621 variants: enum_definition
2624 .map(|x| self.lower_variant(x))
2627 self.lower_generics(generics, ImplTraitContext::Disallowed),
2629 ItemKind::Struct(ref struct_def, ref generics) => {
2630 let struct_def = self.lower_variant_data(struct_def);
2633 self.lower_generics(generics, ImplTraitContext::Disallowed),
2636 ItemKind::Union(ref vdata, ref generics) => {
2637 let vdata = self.lower_variant_data(vdata);
2640 self.lower_generics(generics, ImplTraitContext::Disallowed),
2652 let def_id = self.resolver.definitions().local_def_id(id);
2654 // Lower the "impl header" first. This ordering is important
2655 // for in-band lifetimes! Consider `'a` here:
2657 // impl Foo<'a> for u32 {
2658 // fn method(&'a self) { .. }
2661 // Because we start by lowering the `Foo<'a> for u32`
2662 // part, we will add `'a` to the list of generics on
2663 // the impl. When we then encounter it later in the
2664 // method, it will not be considered an in-band
2665 // lifetime to be added, but rather a reference to a
2667 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2670 AnonymousLifetimeMode::CreateParameter,
2672 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2673 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2676 if let Some(ref trait_ref) = trait_ref {
2677 if let Def::Trait(def_id) = trait_ref.path.def {
2678 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2682 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2684 (trait_ref, lowered_ty)
2688 let new_impl_items = self.with_in_scope_lifetime_defs(
2689 &ast_generics.params,
2693 .map(|item| this.lower_impl_item_ref(item))
2699 self.lower_unsafety(unsafety),
2700 self.lower_impl_polarity(polarity),
2701 self.lower_defaultness(defaultness, true /* [1] */),
2708 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2709 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2712 .map(|item| self.lower_trait_item_ref(item))
2715 self.lower_is_auto(is_auto),
2716 self.lower_unsafety(unsafety),
2717 self.lower_generics(generics, ImplTraitContext::Disallowed),
2722 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2723 self.lower_generics(generics, ImplTraitContext::Disallowed),
2724 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2726 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2729 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2730 // not cause an assertion failure inside the `lower_defaultness` function
2738 vis: &mut hir::Visibility,
2740 attrs: &hir::HirVec<Attribute>,
2742 let path = &tree.prefix;
2745 UseTreeKind::Simple(rename, id1, id2) => {
2746 *name = tree.ident().name;
2748 // First apply the prefix to the path
2749 let mut path = Path {
2753 .chain(path.segments.iter())
2759 // Correctly resolve `self` imports
2760 if path.segments.len() > 1
2761 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2763 let _ = path.segments.pop();
2764 if rename.is_none() {
2765 *name = path.segments.last().unwrap().ident.name;
2769 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2770 let mut defs = self.expect_full_def_from_use(id);
2771 // we want to return *something* from this function, so hang onto the first item
2773 let mut ret_def = defs.next().unwrap_or(Def::Err);
2775 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2776 let vis = vis.clone();
2777 let name = name.clone();
2778 let span = path.span;
2779 self.resolver.definitions().create_def_with_parent(
2783 DefIndexAddressSpace::High,
2786 self.allocate_hir_id_counter(new_node_id, &path);
2788 self.with_hir_id_owner(new_node_id, |this| {
2789 let new_id = this.lower_node_id(new_node_id);
2790 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2791 let item = hir::ItemUse(P(path), hir::UseKind::Single);
2792 let vis = match vis {
2793 hir::Visibility::Public => hir::Visibility::Public,
2794 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2795 hir::Visibility::Inherited => hir::Visibility::Inherited,
2796 hir::Visibility::Restricted { ref path, id: _ } => {
2797 hir::Visibility::Restricted {
2799 // We are allocating a new NodeId here
2800 id: this.next_id().node_id,
2809 hir_id: new_id.hir_id,
2811 attrs: attrs.clone(),
2820 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2821 hir::ItemUse(path, hir::UseKind::Single)
2823 UseTreeKind::Glob => {
2824 let path = P(self.lower_path(
2830 .chain(path.segments.iter())
2835 ParamMode::Explicit,
2837 hir::ItemUse(path, hir::UseKind::Glob)
2839 UseTreeKind::Nested(ref trees) => {
2844 .chain(path.segments.iter())
2847 span: prefix.span.to(path.span),
2850 // Add all the nested PathListItems in the HIR
2851 for &(ref use_tree, id) in trees {
2852 self.allocate_hir_id_counter(id, &use_tree);
2856 } = self.lower_node_id(id);
2858 let mut vis = vis.clone();
2859 let mut name = name.clone();
2861 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2863 self.with_hir_id_owner(new_id, |this| {
2864 let vis = match vis {
2865 hir::Visibility::Public => hir::Visibility::Public,
2866 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2867 hir::Visibility::Inherited => hir::Visibility::Inherited,
2868 hir::Visibility::Restricted { ref path, id: _ } => {
2869 hir::Visibility::Restricted {
2871 // We are allocating a new NodeId here
2872 id: this.next_id().node_id,
2883 attrs: attrs.clone(),
2886 span: use_tree.span,
2892 // Privatize the degenerate import base, used only to check
2893 // the stability of `use a::{};`, to avoid it showing up as
2894 // a re-export by accident when `pub`, e.g. in documentation.
2895 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2896 *vis = hir::Inherited;
2897 hir::ItemUse(path, hir::UseKind::ListStem)
2902 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2903 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2904 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2906 let (generics, node) = match i.node {
2907 TraitItemKind::Const(ref ty, ref default) => (
2908 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2909 hir::TraitItemKind::Const(
2910 self.lower_ty(ty, ImplTraitContext::Disallowed),
2913 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2916 TraitItemKind::Method(ref sig, None) => {
2917 let names = self.lower_fn_args_to_names(&sig.decl);
2918 self.add_in_band_defs(
2921 AnonymousLifetimeMode::PassThrough,
2923 hir::TraitItemKind::Method(
2924 this.lower_method_sig(sig, trait_item_def_id, false, false),
2925 hir::TraitMethod::Required(names),
2930 TraitItemKind::Method(ref sig, Some(ref body)) => {
2931 let body_id = self.lower_body(Some(&sig.decl), |this| {
2932 let body = this.lower_block(body, false);
2933 this.expr_block(body, ThinVec::new())
2936 self.add_in_band_defs(
2939 AnonymousLifetimeMode::PassThrough,
2941 hir::TraitItemKind::Method(
2942 this.lower_method_sig(sig, trait_item_def_id, false, false),
2943 hir::TraitMethod::Provided(body_id),
2948 TraitItemKind::Type(ref bounds, ref default) => (
2949 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2950 hir::TraitItemKind::Type(
2951 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2954 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2957 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2963 name: self.lower_ident(i.ident),
2964 attrs: self.lower_attrs(&i.attrs),
2971 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2972 let (kind, has_default) = match i.node {
2973 TraitItemKind::Const(_, ref default) => {
2974 (hir::AssociatedItemKind::Const, default.is_some())
2976 TraitItemKind::Type(_, ref default) => {
2977 (hir::AssociatedItemKind::Type, default.is_some())
2979 TraitItemKind::Method(ref sig, ref default) => (
2980 hir::AssociatedItemKind::Method {
2981 has_self: sig.decl.has_self(),
2985 TraitItemKind::Macro(..) => unimplemented!(),
2988 id: hir::TraitItemId { node_id: i.id },
2989 name: self.lower_ident(i.ident),
2991 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
2996 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
2997 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2998 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3000 let (generics, node) = match i.node {
3001 ImplItemKind::Const(ref ty, ref expr) => {
3002 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3004 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3005 hir::ImplItemKind::Const(
3006 self.lower_ty(ty, ImplTraitContext::Disallowed),
3011 ImplItemKind::Method(ref sig, ref body) => {
3012 let body_id = self.lower_body(Some(&sig.decl), |this| {
3013 if let IsAsync::Async(async_node_id) = sig.header.asyncness {
3014 let async_expr = this.make_async_expr(
3015 CaptureBy::Value, async_node_id, None,
3017 let body = this.lower_block(body, false);
3018 this.expr_block(body, ThinVec::new())
3020 this.expr(body.span, async_expr, ThinVec::new())
3022 let body = this.lower_block(body, false);
3023 this.expr_block(body, ThinVec::new())
3026 let impl_trait_return_allow = !self.is_in_trait_impl;
3028 self.add_in_band_defs(
3031 AnonymousLifetimeMode::PassThrough,
3033 hir::ImplItemKind::Method(
3034 this.lower_method_sig(
3037 impl_trait_return_allow,
3038 sig.header.asyncness.is_async(),
3045 ImplItemKind::Type(ref ty) => (
3046 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3047 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
3049 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3055 name: self.lower_ident(i.ident),
3056 attrs: self.lower_attrs(&i.attrs),
3058 vis: self.lower_visibility(&i.vis, None),
3059 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3064 // [1] since `default impl` is not yet implemented, this is always true in impls
3067 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3069 id: hir::ImplItemId { node_id: i.id },
3070 name: self.lower_ident(i.ident),
3072 vis: self.lower_visibility(&i.vis, Some(i.id)),
3073 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3074 kind: match i.node {
3075 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3076 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3077 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3078 has_self: sig.decl.has_self(),
3080 ImplItemKind::Macro(..) => unimplemented!(),
3084 // [1] since `default impl` is not yet implemented, this is always true in impls
3087 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3090 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3094 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
3096 ItemKind::Use(ref use_tree) => {
3097 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
3098 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3101 ItemKind::MacroDef(..) => return SmallVector::new(),
3104 SmallVector::one(hir::ItemId { id: i.id })
3107 fn lower_item_id_use_tree(&mut self,
3110 vec: &mut SmallVector<hir::ItemId>)
3113 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3114 vec.push(hir::ItemId { id });
3115 self.lower_item_id_use_tree(nested, id, vec);
3117 UseTreeKind::Glob => {}
3118 UseTreeKind::Simple(_, id1, id2) => {
3119 for (_, &id) in self.expect_full_def_from_use(base_id)
3121 .zip([id1, id2].iter())
3123 vec.push(hir::ItemId { id });
3129 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3130 let mut name = i.ident.name;
3131 let mut vis = self.lower_visibility(&i.vis, None);
3132 let attrs = self.lower_attrs(&i.attrs);
3133 if let ItemKind::MacroDef(ref def) = i.node {
3134 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
3135 let body = self.lower_token_stream(def.stream());
3136 self.exported_macros.push(hir::MacroDef {
3149 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3151 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3164 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3165 let node_id = self.lower_node_id(i.id).node_id;
3166 let def_id = self.resolver.definitions().local_def_id(node_id);
3170 attrs: self.lower_attrs(&i.attrs),
3171 node: match i.node {
3172 ForeignItemKind::Fn(ref fdec, ref generics) => {
3173 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3176 AnonymousLifetimeMode::PassThrough,
3179 // Disallow impl Trait in foreign items
3180 this.lower_fn_decl(fdec, None, false, false),
3181 this.lower_fn_args_to_names(fdec),
3186 hir::ForeignItemFn(fn_dec, fn_args, generics)
3188 ForeignItemKind::Static(ref t, m) => {
3189 hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
3191 ForeignItemKind::Ty => hir::ForeignItemType,
3192 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3194 vis: self.lower_visibility(&i.vis, None),
3199 fn lower_method_sig(
3203 impl_trait_return_allow: bool,
3205 ) -> hir::MethodSig {
3207 header: self.lower_fn_header(sig.header),
3208 decl: self.lower_fn_decl(&sig.decl, Some(fn_def_id), impl_trait_return_allow, is_async),
3212 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3214 IsAuto::Yes => hir::IsAuto::Yes,
3215 IsAuto::No => hir::IsAuto::No,
3219 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3221 unsafety: self.lower_unsafety(h.unsafety),
3222 asyncness: self.lower_asyncness(h.asyncness),
3223 constness: self.lower_constness(h.constness),
3228 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3230 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3231 Unsafety::Normal => hir::Unsafety::Normal,
3235 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3237 Constness::Const => hir::Constness::Const,
3238 Constness::NotConst => hir::Constness::NotConst,
3242 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3244 IsAsync::Async(_) => hir::IsAsync::Async,
3245 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3249 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3251 UnOp::Deref => hir::UnDeref,
3252 UnOp::Not => hir::UnNot,
3253 UnOp::Neg => hir::UnNeg,
3257 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3259 node: match b.node {
3260 BinOpKind::Add => hir::BiAdd,
3261 BinOpKind::Sub => hir::BiSub,
3262 BinOpKind::Mul => hir::BiMul,
3263 BinOpKind::Div => hir::BiDiv,
3264 BinOpKind::Rem => hir::BiRem,
3265 BinOpKind::And => hir::BiAnd,
3266 BinOpKind::Or => hir::BiOr,
3267 BinOpKind::BitXor => hir::BiBitXor,
3268 BinOpKind::BitAnd => hir::BiBitAnd,
3269 BinOpKind::BitOr => hir::BiBitOr,
3270 BinOpKind::Shl => hir::BiShl,
3271 BinOpKind::Shr => hir::BiShr,
3272 BinOpKind::Eq => hir::BiEq,
3273 BinOpKind::Lt => hir::BiLt,
3274 BinOpKind::Le => hir::BiLe,
3275 BinOpKind::Ne => hir::BiNe,
3276 BinOpKind::Ge => hir::BiGe,
3277 BinOpKind::Gt => hir::BiGt,
3283 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3284 let node = match p.node {
3285 PatKind::Wild => hir::PatKind::Wild,
3286 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3287 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3288 // `None` can occur in body-less function signatures
3289 def @ None | def @ Some(Def::Local(_)) => {
3290 let canonical_id = match def {
3291 Some(Def::Local(id)) => id,
3294 hir::PatKind::Binding(
3295 self.lower_binding_mode(binding_mode),
3297 respan(ident.span, ident.name),
3298 sub.as_ref().map(|x| self.lower_pat(x)),
3301 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3306 segments: hir_vec![hir::PathSegment::from_name(ident.name)],
3311 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3312 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3313 let qpath = self.lower_qpath(
3317 ParamMode::Optional,
3318 ImplTraitContext::Disallowed,
3320 hir::PatKind::TupleStruct(
3322 pats.iter().map(|x| self.lower_pat(x)).collect(),
3326 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3330 ParamMode::Optional,
3331 ImplTraitContext::Disallowed,
3333 PatKind::Struct(ref path, ref fields, etc) => {
3334 let qpath = self.lower_qpath(
3338 ParamMode::Optional,
3339 ImplTraitContext::Disallowed,
3346 node: hir::FieldPat {
3347 id: self.next_id().node_id,
3348 ident: f.node.ident,
3349 pat: self.lower_pat(&f.node.pat),
3350 is_shorthand: f.node.is_shorthand,
3354 hir::PatKind::Struct(qpath, fs, etc)
3356 PatKind::Tuple(ref elts, ddpos) => {
3357 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3359 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3360 PatKind::Ref(ref inner, mutbl) => {
3361 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3363 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3364 P(self.lower_expr(e1)),
3365 P(self.lower_expr(e2)),
3366 self.lower_range_end(end),
3368 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3369 before.iter().map(|x| self.lower_pat(x)).collect(),
3370 slice.as_ref().map(|x| self.lower_pat(x)),
3371 after.iter().map(|x| self.lower_pat(x)).collect(),
3373 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3374 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3377 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3386 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3388 RangeEnd::Included(_) => hir::RangeEnd::Included,
3389 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3393 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3394 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3399 body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3403 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3404 let kind = match e.node {
3405 ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
3406 ExprKind::ObsoleteInPlace(..) => {
3407 self.sess.abort_if_errors();
3408 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3410 ExprKind::Array(ref exprs) => {
3411 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
3413 ExprKind::Repeat(ref expr, ref count) => {
3414 let expr = P(self.lower_expr(expr));
3415 let count = self.lower_anon_const(count);
3416 hir::ExprRepeat(expr, count)
3418 ExprKind::Tup(ref elts) => {
3419 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
3421 ExprKind::Call(ref f, ref args) => {
3422 let f = P(self.lower_expr(f));
3423 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
3425 ExprKind::MethodCall(ref seg, ref args) => {
3426 let hir_seg = self.lower_path_segment(
3429 ParamMode::Optional,
3431 ParenthesizedGenericArgs::Err,
3432 ImplTraitContext::Disallowed,
3434 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3435 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
3437 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3438 let binop = self.lower_binop(binop);
3439 let lhs = P(self.lower_expr(lhs));
3440 let rhs = P(self.lower_expr(rhs));
3441 hir::ExprBinary(binop, lhs, rhs)
3443 ExprKind::Unary(op, ref ohs) => {
3444 let op = self.lower_unop(op);
3445 let ohs = P(self.lower_expr(ohs));
3446 hir::ExprUnary(op, ohs)
3448 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
3449 ExprKind::Cast(ref expr, ref ty) => {
3450 let expr = P(self.lower_expr(expr));
3451 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3453 ExprKind::Type(ref expr, ref ty) => {
3454 let expr = P(self.lower_expr(expr));
3455 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3457 ExprKind::AddrOf(m, ref ohs) => {
3458 let m = self.lower_mutability(m);
3459 let ohs = P(self.lower_expr(ohs));
3460 hir::ExprAddrOf(m, ohs)
3462 // More complicated than you might expect because the else branch
3463 // might be `if let`.
3464 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3465 let else_opt = else_opt.as_ref().map(|els| {
3467 ExprKind::IfLet(..) => {
3468 // wrap the if-let expr in a block
3469 let span = els.span;
3470 let els = P(self.lower_expr(els));
3471 let LoweredNodeId { node_id, hir_id } = self.next_id();
3472 let blk = P(hir::Block {
3477 rules: hir::DefaultBlock,
3479 targeted_by_break: false,
3480 recovered: blk.recovered,
3482 P(self.expr_block(blk, ThinVec::new()))
3484 _ => P(self.lower_expr(els)),
3488 let then_blk = self.lower_block(blk, false);
3489 let then_expr = self.expr_block(then_blk, ThinVec::new());
3491 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3493 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3495 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3496 this.lower_block(body, false),
3497 this.lower_label(opt_label),
3500 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3502 this.lower_block(body, false),
3503 this.lower_label(opt_label),
3504 hir::LoopSource::Loop,
3507 ExprKind::Catch(ref body) => {
3508 self.with_catch_scope(body.id, |this| {
3510 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3511 let mut block = this.lower_block(body, true).into_inner();
3512 let tail = block.expr.take().map_or_else(
3514 let LoweredNodeId { node_id, hir_id } = this.next_id();
3515 let span = this.sess.codemap().end_point(unstable_span);
3519 node: hir::ExprTup(hir_vec![]),
3520 attrs: ThinVec::new(),
3524 |x: P<hir::Expr>| x.into_inner(),
3526 block.expr = Some(this.wrap_in_try_constructor(
3527 "from_ok", tail, unstable_span));
3528 hir::ExprBlock(P(block), None)
3531 ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3532 P(self.lower_expr(expr)),
3533 arms.iter().map(|x| self.lower_arm(x)).collect(),
3534 hir::MatchSource::Normal,
3536 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3537 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3538 this.with_new_scopes(|this| {
3539 let block = this.lower_block(block, false);
3540 this.expr_block(block, ThinVec::new())
3545 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3547 if let IsAsync::Async(async_closure_node_id) = asyncness {
3548 let outer_decl = FnDecl {
3549 inputs: decl.inputs.clone(),
3550 output: FunctionRetTy::Default(fn_decl_span),
3553 // We need to lower the declaration outside the new scope, because we
3554 // have to conserve the state of being inside a loop condition for the
3555 // closure argument types.
3556 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, false);
3558 self.with_new_scopes(|this| {
3559 // FIXME(cramertj) allow `async` non-`move` closures with
3560 if capture_clause == CaptureBy::Ref &&
3561 !decl.inputs.is_empty()
3567 "`async` non-`move` closures with arguments \
3568 are not currently supported",
3570 .help("consider using `let` statements to manually capture \
3571 variables by reference before entering an \
3572 `async move` closure")
3576 // Transform `async |x: u8| -> X { ... }` into
3577 // `|x: u8| future_from_generator(|| -> X { ... })`
3578 let body_id = this.lower_body(Some(&outer_decl), |this| {
3579 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3582 let async_body = this.make_async_expr(
3583 capture_clause, async_closure_node_id, async_ret_ty,
3585 this.with_new_scopes(|this| this.lower_expr(body))
3587 this.expr(fn_decl_span, async_body, ThinVec::new())
3590 this.lower_capture_clause(capture_clause),
3598 // Lower outside new scope to preserve `is_in_loop_condition`.
3599 let fn_decl = self.lower_fn_decl(decl, None, false, false);
3601 self.with_new_scopes(|this| {
3602 let mut is_generator = false;
3603 let body_id = this.lower_body(Some(decl), |this| {
3604 let e = this.lower_expr(body);
3605 is_generator = this.is_generator;
3608 let generator_option = if is_generator {
3609 if !decl.inputs.is_empty() {
3614 "generators cannot have explicit arguments"
3616 this.sess.abort_if_errors();
3618 Some(match movability {
3619 Movability::Movable => hir::GeneratorMovability::Movable,
3620 Movability::Static => hir::GeneratorMovability::Static,
3623 if movability == Movability::Static {
3628 "closures cannot be static"
3634 this.lower_capture_clause(capture_clause),
3643 ExprKind::Block(ref blk, opt_label) => {
3644 hir::ExprBlock(self.lower_block(blk,
3645 opt_label.is_some()),
3646 self.lower_label(opt_label))
3648 ExprKind::Assign(ref el, ref er) => {
3649 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3651 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3652 self.lower_binop(op),
3653 P(self.lower_expr(el)),
3654 P(self.lower_expr(er)),
3656 ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3657 ExprKind::Index(ref el, ref er) => {
3658 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3660 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3661 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3662 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3663 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3664 let id = self.next_id();
3665 let e1 = self.lower_expr(e1);
3666 let e2 = self.lower_expr(e2);
3667 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], None, false));
3668 let ty = P(self.ty_path(id, span, hir::QPath::Resolved(None, ty_path)));
3669 let new_seg = P(hir::PathSegment::from_name(Symbol::intern("new")));
3670 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3671 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3672 hir::ExprCall(new, hir_vec![e1, e2])
3674 ExprKind::Range(ref e1, ref e2, lims) => {
3675 use syntax::ast::RangeLimits::*;
3677 let path = match (e1, e2, lims) {
3678 (&None, &None, HalfOpen) => "RangeFull",
3679 (&Some(..), &None, HalfOpen) => "RangeFrom",
3680 (&None, &Some(..), HalfOpen) => "RangeTo",
3681 (&Some(..), &Some(..), HalfOpen) => "Range",
3682 (&None, &Some(..), Closed) => "RangeToInclusive",
3683 (&Some(..), &Some(..), Closed) => unreachable!(),
3684 (_, &None, Closed) => self.diagnostic()
3685 .span_fatal(e.span, "inclusive range with no end")
3689 let fields = e1.iter()
3690 .map(|e| ("start", e))
3691 .chain(e2.iter().map(|e| ("end", e)))
3693 let expr = P(self.lower_expr(&e));
3695 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3696 let ident = Ident::new(Symbol::intern(s), unstable_span);
3697 self.field(ident, expr, unstable_span)
3699 .collect::<P<[hir::Field]>>();
3701 let is_unit = fields.is_empty();
3703 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3704 let struct_path = iter::once("ops")
3705 .chain(iter::once(path))
3706 .collect::<Vec<_>>();
3707 let struct_path = self.std_path(unstable_span, &struct_path, None, is_unit);
3708 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3710 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3716 hir::ExprPath(struct_path)
3718 hir::ExprStruct(struct_path, fields, None)
3720 span: unstable_span,
3721 attrs: e.attrs.clone(),
3724 ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3728 ParamMode::Optional,
3729 ImplTraitContext::Disallowed,
3731 ExprKind::Break(opt_label, ref opt_expr) => {
3732 let destination = 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)))
3742 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3745 ExprKind::Continue(opt_label) => {
3746 hir::ExprContinue(if self.is_in_loop_condition && opt_label.is_none() {
3749 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3752 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3755 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3756 ExprKind::InlineAsm(ref asm) => {
3757 let hir_asm = hir::InlineAsm {
3758 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3759 outputs: asm.outputs
3761 .map(|out| hir::InlineAsmOutput {
3762 constraint: out.constraint.clone(),
3764 is_indirect: out.is_indirect,
3767 asm: asm.asm.clone(),
3768 asm_str_style: asm.asm_str_style,
3769 clobbers: asm.clobbers.clone().into(),
3770 volatile: asm.volatile,
3771 alignstack: asm.alignstack,
3772 dialect: asm.dialect,
3775 let outputs = asm.outputs
3777 .map(|out| self.lower_expr(&out.expr))
3779 let inputs = asm.inputs
3781 .map(|&(_, ref input)| self.lower_expr(input))
3783 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3785 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3790 ParamMode::Optional,
3791 ImplTraitContext::Disallowed,
3793 fields.iter().map(|x| self.lower_field(x)).collect(),
3794 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3796 ExprKind::Paren(ref ex) => {
3797 let mut ex = self.lower_expr(ex);
3798 // include parens in span, but only if it is a super-span.
3799 if e.span.contains(ex.span) {
3802 // merge attributes into the inner expression.
3803 let mut attrs = e.attrs.clone();
3804 attrs.extend::<Vec<_>>(ex.attrs.into());
3809 ExprKind::Yield(ref opt_expr) => {
3810 self.is_generator = true;
3813 .map(|x| self.lower_expr(x))
3814 .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3815 hir::ExprYield(P(expr))
3818 // Desugar ExprIfLet
3819 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3820 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3823 // match <sub_expr> {
3825 // _ => [<else_opt> | ()]
3828 let mut arms = vec![];
3830 // `<pat> => <body>`
3832 let body = self.lower_block(body, false);
3833 let body_expr = P(self.expr_block(body, ThinVec::new()));
3834 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3835 arms.push(self.arm(pats, body_expr));
3838 // _ => [<else_opt>|()]
3840 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3841 let wildcard_pattern = self.pat_wild(e.span);
3842 let body = if let Some(else_expr) = wildcard_arm {
3843 P(self.lower_expr(else_expr))
3845 self.expr_tuple(e.span, hir_vec![])
3847 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3850 let contains_else_clause = else_opt.is_some();
3852 let sub_expr = P(self.lower_expr(sub_expr));
3857 hir::MatchSource::IfLetDesugar {
3858 contains_else_clause,
3863 // Desugar ExprWhileLet
3864 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3865 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3868 // [opt_ident]: loop {
3869 // match <sub_expr> {
3875 // Note that the block AND the condition are evaluated in the loop scope.
3876 // This is done to allow `break` from inside the condition of the loop.
3877 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3879 this.lower_block(body, false),
3880 this.expr_break(e.span, ThinVec::new()),
3881 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3885 // `<pat> => <body>`
3887 let body_expr = P(self.expr_block(body, ThinVec::new()));
3888 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3889 self.arm(pats, body_expr)
3894 let pat_under = self.pat_wild(e.span);
3895 self.arm(hir_vec![pat_under], break_expr)
3898 // `match <sub_expr> { ... }`
3899 let arms = hir_vec![pat_arm, break_arm];
3900 let match_expr = self.expr(
3902 hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3906 // `[opt_ident]: loop { ... }`
3907 let loop_block = P(self.block_expr(P(match_expr)));
3908 let loop_expr = hir::ExprLoop(
3910 self.lower_label(opt_label),
3911 hir::LoopSource::WhileLet,
3913 // add attributes to the outer returned expr node
3917 // Desugar ExprForLoop
3918 // From: `[opt_ident]: for <pat> in <head> <body>`
3919 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3923 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3925 // [opt_ident]: loop {
3927 // match ::std::iter::Iterator::next(&mut iter) {
3928 // ::std::option::Option::Some(val) => __next = val,
3929 // ::std::option::Option::None => break
3931 // let <pat> = __next;
3932 // StmtExpr(<body>);
3940 let head = self.lower_expr(head);
3941 let head_sp = head.span;
3943 let iter = self.str_to_ident("iter");
3945 let next_ident = self.str_to_ident("__next");
3946 let next_pat = self.pat_ident_binding_mode(
3949 hir::BindingAnnotation::Mutable,
3952 // `::std::option::Option::Some(val) => next = val`
3954 let val_ident = self.str_to_ident("val");
3955 let val_pat = self.pat_ident(pat.span, val_ident);
3956 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
3957 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
3958 let assign = P(self.expr(
3960 hir::ExprAssign(next_expr, val_expr),
3963 let some_pat = self.pat_some(pat.span, val_pat);
3964 self.arm(hir_vec![some_pat], assign)
3967 // `::std::option::Option::None => break`
3970 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
3971 let pat = self.pat_none(e.span);
3972 self.arm(hir_vec![pat], break_expr)
3977 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
3979 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
3981 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
3982 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
3983 let next_path = &["iter", "Iterator", "next"];
3984 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
3985 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
3986 let arms = hir_vec![pat_arm, break_arm];
3990 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
3994 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
3996 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4000 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
4002 // `let <pat> = __next`
4003 let pat = self.lower_pat(pat);
4004 let pat_let = self.stmt_let_pat(
4008 hir::LocalSource::ForLoopDesugar,
4011 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4012 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4013 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
4015 let loop_block = P(self.block_all(
4017 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4021 // `[opt_ident]: loop { ... }`
4022 let loop_expr = hir::ExprLoop(
4024 self.lower_label(opt_label),
4025 hir::LoopSource::ForLoop,
4027 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4028 let loop_expr = P(hir::Expr {
4033 attrs: ThinVec::new(),
4036 // `mut iter => { ... }`
4037 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4039 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4040 let into_iter_expr = {
4041 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4042 let into_iter = P(self.expr_std_path(
4043 head_sp, into_iter_path, None, ThinVec::new()));
4044 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4047 let match_expr = P(self.expr_match(
4051 hir::MatchSource::ForLoopDesugar,
4054 // `{ let _result = ...; _result }`
4055 // underscore prevents an unused_variables lint if the head diverges
4056 let result_ident = self.str_to_ident("_result");
4057 let (let_stmt, let_stmt_binding) =
4058 self.stmt_let(e.span, false, result_ident, match_expr);
4060 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4061 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4062 // add the attributes to the outer returned expr node
4063 return self.expr_block(block, e.attrs.clone());
4066 // Desugar ExprKind::Try
4068 ExprKind::Try(ref sub_expr) => {
4071 // match Try::into_result(<expr>) {
4072 // Ok(val) => #[allow(unreachable_code)] val,
4073 // Err(err) => #[allow(unreachable_code)]
4074 // // If there is an enclosing `catch {...}`
4075 // break 'catch_target Try::from_error(From::from(err)),
4077 // return Try::from_error(From::from(err)),
4081 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4083 // Try::into_result(<expr>)
4086 let sub_expr = self.lower_expr(sub_expr);
4088 let path = &["ops", "Try", "into_result"];
4089 let path = P(self.expr_std_path(
4090 unstable_span, path, None, ThinVec::new()));
4091 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4094 // #[allow(unreachable_code)]
4096 // allow(unreachable_code)
4098 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4099 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4100 let uc_nested = attr::mk_nested_word_item(uc_ident);
4101 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4103 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4105 let attrs = vec![attr];
4107 // Ok(val) => #[allow(unreachable_code)] val,
4109 let val_ident = self.str_to_ident("val");
4110 let val_pat = self.pat_ident(e.span, val_ident);
4111 let val_expr = P(self.expr_ident_with_attrs(
4115 ThinVec::from(attrs.clone()),
4117 let ok_pat = self.pat_ok(e.span, val_pat);
4119 self.arm(hir_vec![ok_pat], val_expr)
4122 // Err(err) => #[allow(unreachable_code)]
4123 // return Try::from_error(From::from(err)),
4125 let err_ident = self.str_to_ident("err");
4126 let err_local = self.pat_ident(e.span, err_ident);
4128 let path = &["convert", "From", "from"];
4129 let from = P(self.expr_std_path(
4130 e.span, path, None, ThinVec::new()));
4131 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4133 self.expr_call(e.span, from, hir_vec![err_expr])
4136 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4137 let thin_attrs = ThinVec::from(attrs);
4138 let catch_scope = self.catch_scopes.last().map(|x| *x);
4139 let ret_expr = if let Some(catch_node) = catch_scope {
4145 target_id: Ok(catch_node),
4147 Some(from_err_expr),
4152 P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
4155 let err_pat = self.pat_err(e.span, err_local);
4156 self.arm(hir_vec![err_pat], ret_expr)
4161 hir_vec![err_arm, ok_arm],
4162 hir::MatchSource::TryDesugar,
4166 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4169 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4176 attrs: e.attrs.clone(),
4180 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
4181 SmallVector::one(match s.node {
4182 StmtKind::Local(ref l) => Spanned {
4183 node: hir::StmtDecl(
4185 node: hir::DeclLocal(self.lower_local(l)),
4188 self.lower_node_id(s.id).node_id,
4192 StmtKind::Item(ref it) => {
4193 // Can only use the ID once.
4194 let mut id = Some(s.id);
4195 return self.lower_item_id(it)
4197 .map(|item_id| Spanned {
4198 node: hir::StmtDecl(
4200 node: hir::DeclItem(item_id),
4204 .map(|id| self.lower_node_id(id).node_id)
4205 .unwrap_or_else(|| self.next_id().node_id),
4211 StmtKind::Expr(ref e) => Spanned {
4212 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4215 StmtKind::Semi(ref e) => Spanned {
4216 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4219 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4223 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4225 CaptureBy::Value => hir::CaptureByValue,
4226 CaptureBy::Ref => hir::CaptureByRef,
4230 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4231 /// the address space of that item instead of the item currently being
4232 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4233 /// lower a `Visibility` value although we haven't lowered the owning
4234 /// `ImplItem` in question yet.
4235 fn lower_visibility(
4238 explicit_owner: Option<NodeId>,
4239 ) -> hir::Visibility {
4241 VisibilityKind::Public => hir::Public,
4242 VisibilityKind::Crate(sugar) => hir::Visibility::Crate(sugar),
4243 VisibilityKind::Restricted { ref path, id, .. } => hir::Visibility::Restricted {
4244 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4245 id: if let Some(owner) = explicit_owner {
4246 self.lower_node_id_with_owner(id, owner).node_id
4248 self.lower_node_id(id).node_id
4251 VisibilityKind::Inherited => hir::Inherited,
4255 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4257 Defaultness::Default => hir::Defaultness::Default {
4258 has_value: has_value,
4260 Defaultness::Final => {
4262 hir::Defaultness::Final
4267 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4269 BlockCheckMode::Default => hir::DefaultBlock,
4270 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4274 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4276 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4277 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4278 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4279 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4283 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4285 CompilerGenerated => hir::CompilerGenerated,
4286 UserProvided => hir::UserProvided,
4290 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4292 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4293 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4297 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4299 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4300 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4304 // Helper methods for building HIR.
4306 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4315 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4317 id: self.next_id().node_id,
4321 is_shorthand: false,
4325 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4326 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
4327 P(self.expr(span, expr_break, attrs))
4334 args: hir::HirVec<hir::Expr>,
4336 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
4339 fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
4340 self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
4343 fn expr_ident_with_attrs(
4348 attrs: ThinVec<Attribute>,
4350 let expr_path = hir::ExprPath(hir::QPath::Resolved(
4354 def: Def::Local(binding),
4355 segments: hir_vec![hir::PathSegment::from_name(id)],
4359 self.expr(span, expr_path, attrs)
4362 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4363 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
4369 components: &[&str],
4370 params: Option<P<hir::GenericArgs>>,
4371 attrs: ThinVec<Attribute>,
4373 let path = self.std_path(span, components, params, true);
4376 hir::ExprPath(hir::QPath::Resolved(None, P(path))),
4385 arms: hir::HirVec<hir::Arm>,
4386 source: hir::MatchSource,
4388 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
4391 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4392 self.expr(b.span, hir::ExprBlock(b, None), attrs)
4395 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4396 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
4399 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
4400 let LoweredNodeId { node_id, hir_id } = self.next_id();
4413 ex: Option<P<hir::Expr>>,
4415 source: hir::LocalSource,
4417 let LoweredNodeId { node_id, hir_id } = self.next_id();
4419 let local = P(hir::Local {
4426 attrs: ThinVec::new(),
4429 let decl = respan(sp, hir::DeclLocal(local));
4430 respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
4439 ) -> (hir::Stmt, NodeId) {
4440 let pat = if mutbl {
4441 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4443 self.pat_ident(sp, ident)
4445 let pat_id = pat.id;
4447 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4452 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4453 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4459 stmts: hir::HirVec<hir::Stmt>,
4460 expr: Option<P<hir::Expr>>,
4462 let LoweredNodeId { node_id, hir_id } = self.next_id();
4469 rules: hir::DefaultBlock,
4471 targeted_by_break: false,
4476 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4477 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4480 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4481 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4484 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4485 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4488 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4489 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4495 components: &[&str],
4496 subpats: hir::HirVec<P<hir::Pat>>,
4498 let path = self.std_path(span, components, None, true);
4499 let qpath = hir::QPath::Resolved(None, P(path));
4500 let pt = if subpats.is_empty() {
4501 hir::PatKind::Path(qpath)
4503 hir::PatKind::TupleStruct(qpath, subpats, None)
4508 fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
4509 self.pat_ident_binding_mode(span, name, hir::BindingAnnotation::Unannotated)
4512 fn pat_ident_binding_mode(
4516 bm: hir::BindingAnnotation,
4518 let LoweredNodeId { node_id, hir_id } = self.next_id();
4523 node: hir::PatKind::Binding(bm, node_id, Spanned { span, node: name }, None),
4528 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4529 self.pat(span, hir::PatKind::Wild)
4532 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4533 let LoweredNodeId { node_id, hir_id } = self.next_id();
4542 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4543 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4544 /// The path is also resolved according to `is_value`.
4548 components: &[&str],
4549 params: Option<P<hir::GenericArgs>>,
4553 .resolve_str_path(span, self.crate_root, components, params, is_value)
4556 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4558 let node = match qpath {
4559 hir::QPath::Resolved(None, path) => {
4560 // Turn trait object paths into `TyTraitObject` instead.
4561 if let Def::Trait(_) = path.def {
4562 let principal = hir::PolyTraitRef {
4563 bound_generic_params: hir::HirVec::new(),
4564 trait_ref: hir::TraitRef {
4565 path: path.and_then(|path| path),
4571 // The original ID is taken by the `PolyTraitRef`,
4572 // so the `Ty` itself needs a different one.
4573 id = self.next_id();
4574 hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4576 hir::TyPath(hir::QPath::Resolved(None, path))
4579 _ => hir::TyPath(qpath),
4589 /// Invoked to create the lifetime argument for a type `&T`
4590 /// with no explicit lifetime.
4591 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4592 match self.anonymous_lifetime_mode {
4593 // Intercept when we are in an impl header and introduce an in-band lifetime.
4594 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4596 AnonymousLifetimeMode::CreateParameter => {
4597 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4599 id: self.next_id().node_id,
4601 name: hir::LifetimeName::Param(fresh_name),
4605 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4609 /// Invoked to create the lifetime argument(s) for a path like
4610 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4611 /// sorts of cases are deprecated. This may therefore report a warning or an
4612 /// error, depending on the mode.
4613 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4614 match self.anonymous_lifetime_mode {
4615 // NB. We intentionally ignore the create-parameter mode here
4616 // and instead "pass through" to resolve-lifetimes, which will then
4617 // report an error. This is because we don't want to support
4618 // impl elision for deprecated forms like
4620 // impl Foo for std::cell::Ref<u32> // note lack of '_
4621 AnonymousLifetimeMode::CreateParameter => {}
4623 // This is the normal case.
4624 AnonymousLifetimeMode::PassThrough => {}
4628 .map(|_| self.new_implicit_lifetime(span))
4632 /// Invoked to create the lifetime argument(s) for an elided trait object
4633 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4634 /// when the bound is written, even if it is written with `'_` like in
4635 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4636 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4637 match self.anonymous_lifetime_mode {
4638 // NB. We intentionally ignore the create-parameter mode here.
4639 // and instead "pass through" to resolve-lifetimes, which will apply
4640 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4641 // do not act like other elided lifetimes. In other words, given this:
4643 // impl Foo for Box<dyn Debug>
4645 // we do not introduce a fresh `'_` to serve as the bound, but instead
4646 // ultimately translate to the equivalent of:
4648 // impl Foo for Box<dyn Debug + 'static>
4650 // `resolve_lifetime` has the code to make that happen.
4651 AnonymousLifetimeMode::CreateParameter => {}
4653 // This is the normal case.
4654 AnonymousLifetimeMode::PassThrough => {}
4657 self.new_implicit_lifetime(span)
4660 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4662 id: self.next_id().node_id,
4664 name: hir::LifetimeName::Implicit,
4668 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4669 self.sess.buffer_lint_with_diagnostic(
4670 builtin::BARE_TRAIT_OBJECTS,
4673 "trait objects without an explicit `dyn` are deprecated",
4674 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4678 fn wrap_in_try_constructor(
4680 method: &'static str,
4682 unstable_span: Span,
4684 let path = &["ops", "Try", method];
4685 let from_err = P(self.expr_std_path(unstable_span, path, None,
4687 P(self.expr_call(e.span, from_err, hir_vec![e]))
4691 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4692 // Sorting by span ensures that we get things in order within a
4693 // file, and also puts the files in a sensible order.
4694 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4695 body_ids.sort_by_key(|b| bodies[b].value.span);