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>,
175 #[derive(Clone, Copy, Debug)]
176 enum ImplTraitContext {
177 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
178 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
179 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
181 /// We store a DefId here so we can look up necessary information later
184 /// Treat `impl Trait` as shorthand for a new universal existential parameter.
185 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
186 /// equivalent to a fresh existential parameter like `abstract type T; fn foo() -> T`.
188 /// We store a DefId here so we can look up necessary information later
191 /// `impl Trait` is not accepted in this position.
198 dep_graph: &DepGraph,
200 resolver: &mut Resolver,
202 // We're constructing the HIR here; we don't care what we will
203 // read, since we haven't even constructed the *input* to
205 dep_graph.assert_ignored();
208 crate_root: std_inject::injected_crate_name(),
212 name_map: FxHashMap(),
213 items: BTreeMap::new(),
214 trait_items: BTreeMap::new(),
215 impl_items: BTreeMap::new(),
216 bodies: BTreeMap::new(),
217 trait_impls: BTreeMap::new(),
218 trait_auto_impl: BTreeMap::new(),
219 exported_macros: Vec::new(),
220 catch_scopes: Vec::new(),
221 loop_scopes: Vec::new(),
222 is_in_loop_condition: false,
223 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
224 type_def_lifetime_params: DefIdMap(),
225 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
226 item_local_id_counters: NodeMap(),
227 node_id_to_hir_id: IndexVec::new(),
229 is_in_trait_impl: false,
230 in_band_ty_params: Vec::new(),
231 lifetimes_to_define: Vec::new(),
232 is_collecting_in_band_lifetimes: false,
233 in_scope_lifetimes: Vec::new(),
237 #[derive(Copy, Clone, PartialEq, Eq)]
239 /// Any path in a type context.
241 /// The `module::Type` in `module::Type::method` in an expression.
246 struct LoweredNodeId {
251 enum ParenthesizedGenericArgs {
257 /// What to do when we encounter an **anonymous** lifetime
258 /// reference. Anonymous lifetime references come in two flavors. You
259 /// have implicit, or fully elided, references to lifetimes, like the
260 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
261 /// or `Ref<'_, T>`. These often behave the same, but not always:
263 /// - certain usages of implicit references are deprecated, like
264 /// `Ref<T>`, and we sometimes just give hard errors in those cases
266 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
267 /// the same as `Box<dyn Foo + '_>`.
269 /// We describe the effects of the various modes in terms of three cases:
271 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
272 /// of a `&` (e.g., the missing lifetime in something like `&T`)
273 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
274 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
275 /// elided bounds follow special rules. Note that this only covers
276 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
277 /// '_>` is a case of "modern" elision.
278 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
279 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
280 /// non-deprecated equivalent.
282 /// Currently, the handling of lifetime elision is somewhat spread out
283 /// between HIR lowering and -- as described below -- the
284 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
285 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
286 /// everything into HIR lowering.
287 #[derive(Copy, Clone)]
288 enum AnonymousLifetimeMode {
289 /// For **Modern** cases, create a new anonymous region parameter
290 /// and reference that.
292 /// For **Dyn Bound** cases, pass responsibility to
293 /// `resolve_lifetime` code.
295 /// For **Deprecated** cases, report an error.
298 /// Pass responsibility to `resolve_lifetime` code for all cases.
302 impl<'a> LoweringContext<'a> {
303 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
304 /// Full-crate AST visitor that inserts into a fresh
305 /// `LoweringContext` any information that may be
306 /// needed from arbitrary locations in the crate.
307 /// E.g. The number of lifetime generic parameters
308 /// declared for every type and trait definition.
309 struct MiscCollector<'lcx, 'interner: 'lcx> {
310 lctx: &'lcx mut LoweringContext<'interner>,
313 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
314 fn visit_item(&mut self, item: &'lcx Item) {
315 self.lctx.allocate_hir_id_counter(item.id, item);
318 ItemKind::Struct(_, ref generics)
319 | ItemKind::Union(_, ref generics)
320 | ItemKind::Enum(_, ref generics)
321 | ItemKind::Ty(_, ref generics)
322 | ItemKind::Trait(_, _, ref generics, ..) => {
323 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
327 .filter(|param| match param.kind {
328 ast::GenericParamKind::Lifetime { .. } => true,
332 self.lctx.type_def_lifetime_params.insert(def_id, count);
336 visit::walk_item(self, item);
339 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
340 self.lctx.allocate_hir_id_counter(item.id, item);
341 visit::walk_trait_item(self, item);
344 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
345 self.lctx.allocate_hir_id_counter(item.id, item);
346 visit::walk_impl_item(self, item);
350 struct ItemLowerer<'lcx, 'interner: 'lcx> {
351 lctx: &'lcx mut LoweringContext<'interner>,
354 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
355 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
357 F: FnOnce(&mut Self),
359 let old = self.lctx.is_in_trait_impl;
360 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
366 self.lctx.is_in_trait_impl = old;
370 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
371 fn visit_item(&mut self, item: &'lcx Item) {
372 let mut item_lowered = true;
373 self.lctx.with_hir_id_owner(item.id, |lctx| {
374 if let Some(hir_item) = lctx.lower_item(item) {
375 lctx.items.insert(item.id, hir_item);
377 item_lowered = false;
382 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
383 hir::Item_::ItemImpl(_, _, _, ref generics, ..)
384 | hir::Item_::ItemTrait(_, _, ref generics, ..) => {
385 generics.params.clone()
390 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
391 let this = &mut ItemLowerer { lctx: this };
392 if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
393 this.with_trait_impl_ref(opt_trait_ref, |this| {
394 visit::walk_item(this, item)
397 visit::walk_item(this, item);
403 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
404 self.lctx.with_hir_id_owner(item.id, |lctx| {
405 let id = hir::TraitItemId { node_id: item.id };
406 let hir_item = lctx.lower_trait_item(item);
407 lctx.trait_items.insert(id, hir_item);
410 visit::walk_trait_item(self, item);
413 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
414 self.lctx.with_hir_id_owner(item.id, |lctx| {
415 let id = hir::ImplItemId { node_id: item.id };
416 let hir_item = lctx.lower_impl_item(item);
417 lctx.impl_items.insert(id, hir_item);
419 visit::walk_impl_item(self, item);
423 self.lower_node_id(CRATE_NODE_ID);
424 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
426 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
427 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
429 let module = self.lower_mod(&c.module);
430 let attrs = self.lower_attrs(&c.attrs);
431 let body_ids = body_ids(&self.bodies);
435 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
441 exported_macros: hir::HirVec::from(self.exported_macros),
443 trait_items: self.trait_items,
444 impl_items: self.impl_items,
447 trait_impls: self.trait_impls,
448 trait_auto_impl: self.trait_auto_impl,
452 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
453 if self.item_local_id_counters.insert(owner, 0).is_some() {
455 "Tried to allocate item_local_id_counter for {:?} twice",
459 // Always allocate the first HirId for the owner itself
460 self.lower_node_id_with_owner(owner, owner)
463 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
465 F: FnOnce(&mut Self) -> hir::HirId,
467 if ast_node_id == DUMMY_NODE_ID {
468 return LoweredNodeId {
469 node_id: DUMMY_NODE_ID,
470 hir_id: hir::DUMMY_HIR_ID,
474 let min_size = ast_node_id.as_usize() + 1;
476 if min_size > self.node_id_to_hir_id.len() {
477 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
480 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
482 if existing_hir_id == hir::DUMMY_HIR_ID {
483 // Generate a new HirId
484 let hir_id = alloc_hir_id(self);
485 self.node_id_to_hir_id[ast_node_id] = hir_id;
487 node_id: ast_node_id,
492 node_id: ast_node_id,
493 hir_id: existing_hir_id,
498 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
500 F: FnOnce(&mut Self) -> T,
502 let counter = self.item_local_id_counters
503 .insert(owner, HIR_ID_COUNTER_LOCKED)
504 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
505 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
506 self.current_hir_id_owner.push((def_index, counter));
508 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
510 debug_assert!(def_index == new_def_index);
511 debug_assert!(new_counter >= counter);
513 let prev = self.item_local_id_counters
514 .insert(owner, new_counter)
516 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
520 /// This method allocates a new HirId for the given NodeId and stores it in
521 /// the LoweringContext's NodeId => HirId map.
522 /// Take care not to call this method if the resulting HirId is then not
523 /// actually used in the HIR, as that would trigger an assertion in the
524 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
525 /// properly. Calling the method twice with the same NodeId is fine though.
526 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
527 self.lower_node_id_generic(ast_node_id, |this| {
528 let &mut (def_index, ref mut local_id_counter) =
529 this.current_hir_id_owner.last_mut().unwrap();
530 let local_id = *local_id_counter;
531 *local_id_counter += 1;
534 local_id: hir::ItemLocalId(local_id),
539 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
540 self.lower_node_id_generic(ast_node_id, |this| {
541 let local_id_counter = this
542 .item_local_id_counters
544 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
545 let local_id = *local_id_counter;
547 // We want to be sure not to modify the counter in the map while it
548 // is also on the stack. Otherwise we'll get lost updates when writing
549 // back from the stack to the map.
550 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
552 *local_id_counter += 1;
556 .opt_def_index(owner)
557 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
558 that do not belong to the current owner");
562 local_id: hir::ItemLocalId(local_id),
567 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
568 let body = hir::Body {
569 arguments: decl.map_or(hir_vec![], |decl| {
570 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
572 is_generator: self.is_generator,
576 self.bodies.insert(id, body);
580 fn next_id(&mut self) -> LoweredNodeId {
581 self.lower_node_id(self.sess.next_node_id())
584 fn expect_full_def(&mut self, id: NodeId) -> Def {
585 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
586 if pr.unresolved_segments() != 0 {
587 bug!("path not fully resolved: {:?}", pr);
593 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item=Def> {
594 self.resolver.get_import(id).present_items().map(|pr| {
595 if pr.unresolved_segments() != 0 {
596 bug!("path not fully resolved: {:?}", pr);
602 fn diagnostic(&self) -> &errors::Handler {
603 self.sess.diagnostic()
606 fn str_to_ident(&self, s: &'static str) -> Name {
610 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
611 let mark = Mark::fresh(Mark::root());
612 mark.set_expn_info(codemap::ExpnInfo {
614 callee: codemap::NameAndSpan {
615 format: codemap::CompilerDesugaring(reason),
617 allow_internal_unstable: true,
618 allow_internal_unsafe: false,
619 edition: codemap::hygiene::default_edition(),
622 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
625 fn with_anonymous_lifetime_mode<R>(
627 anonymous_lifetime_mode: AnonymousLifetimeMode,
628 op: impl FnOnce(&mut Self) -> R,
630 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
631 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
632 let result = op(self);
633 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
637 /// Creates a new hir::GenericParam for every new lifetime and
638 /// type parameter encountered while evaluating `f`. Definitions
639 /// are created with the parent provided. If no `parent_id` is
640 /// provided, no definitions will be returned.
642 /// Presuming that in-band lifetimes are enabled, then
643 /// `self.anonymous_lifetime_mode` will be updated to match the
644 /// argument while `f` is running (and restored afterwards).
645 fn collect_in_band_defs<T, F>(
648 anonymous_lifetime_mode: AnonymousLifetimeMode,
650 ) -> (Vec<hir::GenericParam>, T)
652 F: FnOnce(&mut LoweringContext) -> T,
654 assert!(!self.is_collecting_in_band_lifetimes);
655 assert!(self.lifetimes_to_define.is_empty());
656 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
658 self.is_collecting_in_band_lifetimes = self.sess.features_untracked().in_band_lifetimes;
659 if self.is_collecting_in_band_lifetimes {
660 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
663 assert!(self.in_band_ty_params.is_empty());
666 self.is_collecting_in_band_lifetimes = false;
667 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
669 let in_band_ty_params = self.in_band_ty_params.split_off(0);
670 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
672 let params = lifetimes_to_define
674 .map(|(span, hir_name)| {
675 let def_node_id = self.next_id().node_id;
677 // Get the name we'll use to make the def-path. Note
678 // that collisions are ok here and this shouldn't
679 // really show up for end-user.
680 let str_name = match hir_name {
681 ParamName::Plain(name) => name.as_str(),
682 ParamName::Fresh(_) => keywords::UnderscoreLifetime.name().as_str(),
685 // Add a definition for the in-band lifetime def
686 self.resolver.definitions().create_def_with_parent(
689 DefPathData::LifetimeParam(str_name.as_interned_str()),
690 DefIndexAddressSpace::High,
701 pure_wrt_drop: false,
702 kind: hir::GenericParamKind::Lifetime { in_band: true }
705 .chain(in_band_ty_params.into_iter())
711 /// When there is a reference to some lifetime `'a`, and in-band
712 /// lifetimes are enabled, then we want to push that lifetime into
713 /// the vector of names to define later. In that case, it will get
714 /// added to the appropriate generics.
715 fn maybe_collect_in_band_lifetime(&mut self, span: Span, name: Name) {
716 if !self.is_collecting_in_band_lifetimes {
720 if self.in_scope_lifetimes.contains(&name) {
724 let hir_name = ParamName::Plain(name);
726 if self.lifetimes_to_define.iter().any(|(_, lt_name)| *lt_name == hir_name) {
730 self.lifetimes_to_define.push((span, hir_name));
733 /// When we have either an elided or `'_` lifetime in an impl
734 /// header, we convert it to
735 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
736 assert!(self.is_collecting_in_band_lifetimes);
737 let index = self.lifetimes_to_define.len();
738 let hir_name = ParamName::Fresh(index);
739 self.lifetimes_to_define.push((span, hir_name));
743 // Evaluates `f` with the lifetimes in `params` in-scope.
744 // This is used to track which lifetimes have already been defined, and
745 // which are new in-band lifetimes that need to have a definition created
747 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &Vec<GenericParam>, f: F) -> T
749 F: FnOnce(&mut LoweringContext) -> T,
751 let old_len = self.in_scope_lifetimes.len();
752 let lt_def_names = params.iter().filter_map(|param| match param.kind {
753 GenericParamKind::Lifetime { .. } => Some(param.ident.name),
756 self.in_scope_lifetimes.extend(lt_def_names);
760 self.in_scope_lifetimes.truncate(old_len);
764 // Same as the method above, but accepts `hir::GenericParam`s
765 // instead of `ast::GenericParam`s.
766 // This should only be used with generics that have already had their
767 // in-band lifetimes added. In practice, this means that this function is
768 // only used when lowering a child item of a trait or impl.
769 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
770 params: &HirVec<hir::GenericParam>,
773 F: FnOnce(&mut LoweringContext) -> T,
775 let old_len = self.in_scope_lifetimes.len();
776 let lt_def_names = params.iter().filter_map(|param| match param.kind {
777 hir::GenericParamKind::Lifetime { .. } => Some(param.name.name()),
780 self.in_scope_lifetimes.extend(lt_def_names);
784 self.in_scope_lifetimes.truncate(old_len);
788 /// Appends in-band lifetime defs and argument-position `impl
789 /// Trait` defs to the existing set of generics.
791 /// Presuming that in-band lifetimes are enabled, then
792 /// `self.anonymous_lifetime_mode` will be updated to match the
793 /// argument while `f` is running (and restored afterwards).
794 fn add_in_band_defs<F, T>(
798 anonymous_lifetime_mode: AnonymousLifetimeMode,
800 ) -> (hir::Generics, T)
802 F: FnOnce(&mut LoweringContext) -> T,
804 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
807 let itctx = ImplTraitContext::Universal(parent_id);
808 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
809 (this.lower_generics(generics, itctx), f(this))
814 lowered_generics.params = lowered_generics
821 (lowered_generics, res)
824 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
826 F: FnOnce(&mut LoweringContext) -> T,
828 let len = self.catch_scopes.len();
829 self.catch_scopes.push(catch_id);
831 let result = f(self);
834 self.catch_scopes.len(),
835 "catch scopes should be added and removed in stack order"
838 self.catch_scopes.pop().unwrap();
845 capture_clause: CaptureBy,
846 closure_node_id: NodeId,
848 body: impl FnOnce(&mut LoweringContext) -> hir::Expr,
850 let prev_is_generator = mem::replace(&mut self.is_generator, true);
851 let body_expr = body(self);
852 let span = body_expr.span;
853 let output = match ret_ty {
854 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
855 None => FunctionRetTy::Default(span),
862 let body_id = self.record_body(body_expr, Some(&decl));
863 self.is_generator = prev_is_generator;
865 let capture_clause = self.lower_capture_clause(capture_clause);
866 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
867 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, false);
868 let generator = hir::Expr {
870 hir_id: closure_hir_id,
871 node: hir::ExprClosure(capture_clause, decl, body_id, span,
872 Some(hir::GeneratorMovability::Static)),
874 attrs: ThinVec::new(),
877 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
878 let gen_future = self.expr_std_path(
879 unstable_span, &["raw", "future_from_generator"], ThinVec::new());
880 hir::ExprCall(P(gen_future), hir_vec![generator])
883 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
885 F: FnOnce(&mut LoweringContext) -> hir::Expr,
887 let prev = mem::replace(&mut self.is_generator, false);
888 let result = f(self);
889 let r = self.record_body(result, decl);
890 self.is_generator = prev;
894 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
896 F: FnOnce(&mut LoweringContext) -> T,
898 // We're no longer in the base loop's condition; we're in another loop.
899 let was_in_loop_condition = self.is_in_loop_condition;
900 self.is_in_loop_condition = false;
902 let len = self.loop_scopes.len();
903 self.loop_scopes.push(loop_id);
905 let result = f(self);
908 self.loop_scopes.len(),
909 "Loop scopes should be added and removed in stack order"
912 self.loop_scopes.pop().unwrap();
914 self.is_in_loop_condition = was_in_loop_condition;
919 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
921 F: FnOnce(&mut LoweringContext) -> T,
923 let was_in_loop_condition = self.is_in_loop_condition;
924 self.is_in_loop_condition = true;
926 let result = f(self);
928 self.is_in_loop_condition = was_in_loop_condition;
933 fn with_new_scopes<T, F>(&mut self, f: F) -> T
935 F: FnOnce(&mut LoweringContext) -> T,
937 let was_in_loop_condition = self.is_in_loop_condition;
938 self.is_in_loop_condition = false;
940 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
941 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
942 let result = f(self);
943 self.catch_scopes = catch_scopes;
944 self.loop_scopes = loop_scopes;
946 self.is_in_loop_condition = was_in_loop_condition;
951 fn def_key(&mut self, id: DefId) -> DefKey {
953 self.resolver.definitions().def_key(id.index)
955 self.cstore.def_key(id)
959 fn lower_ident(&mut self, ident: Ident) -> Name {
960 let ident = ident.modern();
961 if ident.span.ctxt() == SyntaxContext::empty() {
966 .or_insert_with(|| Symbol::from_ident(ident))
969 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
970 label.map(|label| hir::Label {
971 name: label.ident.name,
972 span: label.ident.span,
976 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
978 Some((id, label)) => {
979 let target_id = if let Def::Label(loop_id) = self.expect_full_def(id) {
980 Ok(self.lower_node_id(loop_id).node_id)
982 Err(hir::LoopIdError::UnresolvedLabel)
985 label: self.lower_label(Some(label)),
990 let target_id = self.loop_scopes
992 .map(|innermost_loop_id| *innermost_loop_id)
993 .map(|id| Ok(self.lower_node_id(id).node_id))
994 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1005 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1008 .map(|a| self.lower_attr(a))
1009 .collect::<Vec<_>>()
1013 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1017 path: attr.path.clone(),
1018 tokens: self.lower_token_stream(attr.tokens.clone()),
1019 is_sugared_doc: attr.is_sugared_doc,
1024 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1027 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1031 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1033 TokenTree::Token(span, token) => self.lower_token(token, span),
1034 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1037 delim: delimited.delim,
1038 tts: self.lower_token_stream(delimited.tts.into()).into(),
1044 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1046 Token::Interpolated(_) => {}
1047 other => return TokenTree::Token(span, other).into(),
1050 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1051 self.lower_token_stream(tts)
1054 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1056 attrs: self.lower_attrs(&arm.attrs),
1057 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1058 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1059 body: P(self.lower_expr(&arm.body)),
1063 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1065 id: self.lower_node_id(b.id).node_id,
1066 name: self.lower_ident(b.ident),
1067 ty: self.lower_ty(&b.ty, itctx),
1072 fn lower_generic_arg(&mut self,
1073 arg: &ast::GenericArg,
1074 itctx: ImplTraitContext)
1075 -> hir::GenericArg {
1077 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1078 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty(&ty, itctx)),
1082 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1083 let kind = match t.node {
1084 TyKind::Infer => hir::TyInfer,
1085 TyKind::Err => hir::TyErr,
1086 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty, itctx)),
1087 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt, itctx)),
1088 TyKind::Rptr(ref region, ref mt) => {
1089 let span = t.span.shrink_to_lo();
1090 let lifetime = match *region {
1091 Some(ref lt) => self.lower_lifetime(lt),
1092 None => self.elided_ref_lifetime(span),
1094 hir::TyRptr(lifetime, self.lower_mt(mt, itctx))
1096 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1099 this.with_anonymous_lifetime_mode(
1100 AnonymousLifetimeMode::PassThrough,
1102 hir::TyBareFn(P(hir::BareFnTy {
1103 generic_params: this.lower_generic_params(
1106 ImplTraitContext::Disallowed,
1108 unsafety: this.lower_unsafety(f.unsafety),
1110 decl: this.lower_fn_decl(&f.decl, None, false, false),
1111 arg_names: this.lower_fn_args_to_names(&f.decl),
1117 TyKind::Never => hir::TyNever,
1118 TyKind::Tup(ref tys) => {
1119 hir::TyTup(tys.iter().map(|ty| self.lower_ty(ty, itctx)).collect())
1121 TyKind::Paren(ref ty) => {
1122 return self.lower_ty(ty, itctx);
1124 TyKind::Path(ref qself, ref path) => {
1125 let id = self.lower_node_id(t.id);
1126 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1127 let ty = self.ty_path(id, t.span, qpath);
1128 if let hir::TyTraitObject(..) = ty.node {
1129 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1133 TyKind::ImplicitSelf => hir::TyPath(hir::QPath::Resolved(
1136 def: self.expect_full_def(t.id),
1137 segments: hir_vec![hir::PathSegment::from_name(keywords::SelfType.name())],
1141 TyKind::Array(ref ty, ref length) => {
1142 hir::TyArray(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1144 TyKind::Typeof(ref expr) => {
1145 hir::TyTypeof(self.lower_anon_const(expr))
1147 TyKind::TraitObject(ref bounds, kind) => {
1148 let mut lifetime_bound = None;
1151 .filter_map(|bound| match *bound {
1152 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1153 Some(self.lower_poly_trait_ref(ty, itctx))
1155 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1156 GenericBound::Outlives(ref lifetime) => {
1157 if lifetime_bound.is_none() {
1158 lifetime_bound = Some(self.lower_lifetime(lifetime));
1164 let lifetime_bound =
1165 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1166 if kind != TraitObjectSyntax::Dyn {
1167 self.maybe_lint_bare_trait(t.span, t.id, false);
1169 hir::TyTraitObject(bounds, lifetime_bound)
1171 TyKind::ImplTrait(ref bounds) => {
1174 ImplTraitContext::Existential(fn_def_id) => {
1175 // Set the name to `impl Bound1 + Bound2`
1176 let exist_ty_name = Symbol::intern(&pprust::ty_to_string(t));
1177 self.lower_existential_impl_trait(
1178 span, fn_def_id, exist_ty_name, |this| this.lower_bounds(bounds, itctx))
1180 ImplTraitContext::Universal(def_id) => {
1181 let def_node_id = self.next_id().node_id;
1183 // Add a definition for the in-band TyParam
1184 let def_index = self.resolver.definitions().create_def_with_parent(
1187 DefPathData::UniversalImplTrait,
1188 DefIndexAddressSpace::High,
1193 let hir_bounds = self.lower_param_bounds(bounds, itctx);
1194 // Set the name to `impl Bound1 + Bound2`
1195 let name = Symbol::intern(&pprust::ty_to_string(t));
1196 self.in_band_ty_params.push(hir::GenericParam {
1198 name: ParamName::Plain(name),
1200 pure_wrt_drop: false,
1203 kind: hir::GenericParamKind::Type {
1205 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1209 hir::TyPath(hir::QPath::Resolved(
1213 def: Def::TyParam(DefId::local(def_index)),
1214 segments: hir_vec![hir::PathSegment::from_name(name)],
1218 ImplTraitContext::Disallowed => {
1223 "`impl Trait` not allowed outside of function \
1224 and inherent method return types"
1230 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1233 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1242 fn lower_existential_impl_trait(
1246 exist_ty_name: Name,
1247 lower_bounds: impl FnOnce(&mut LoweringContext) -> hir::TyParamBounds,
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: exist_ty_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 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 = 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(ty, DISALLOWED)).collect();
1810 let mk_tup = |this: &mut Self, tys, span| {
1811 let LoweredNodeId { node_id, hir_id } = this.next_id();
1812 P(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(|| 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(&arg.ty, ImplTraitContext::Universal(def_id))
1903 self.lower_ty(&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(
1943 inputs: &[P<hir::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_path_parameters(&mut self, span: Span, parameters: &'v hir::PathParameters) {
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_path_parameters(self, span, parameters);
1978 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1980 hir::intravisit::walk_path_parameters(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::GenericParam::Lifetime(ref lt_def) = *param {
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 self.currently_bound_lifetimes.push(lt_def.lifetime.name);
2022 hir::intravisit::walk_generic_param(self, param);
2025 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2026 let name = match lifetime.name {
2027 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2028 if self.collect_elided_lifetimes {
2029 // Use `'_` for both implicit and underscore lifetimes in
2030 // `abstract type Foo<'_>: SomeTrait<'_>;`
2031 hir::LifetimeName::Underscore
2036 name @ hir::LifetimeName::Fresh(_) => name,
2037 name @ hir::LifetimeName::Name(_) => 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 output_ty_name_owned;
2092 let (output_ty_name, span) = match output {
2093 FunctionRetTy::Ty(ty) => {
2094 output_ty_name_owned = pprust::ty_to_string(ty);
2095 (&*output_ty_name_owned, ty.span)
2097 FunctionRetTy::Default(span) => ("()", *span),
2100 // FIXME(cramertj) add lifetimes (see FIXME below) to the name
2101 let exist_ty_name = Symbol::intern(&format!("impl Future<Output = {}>", output_ty_name));
2102 let impl_trait_ty = self.lower_existential_impl_trait(
2103 span, fn_def_id, exist_ty_name, |this| {
2104 let output_ty = match output {
2105 FunctionRetTy::Ty(ty) =>
2106 this.lower_ty(ty, ImplTraitContext::Existential(fn_def_id)),
2107 FunctionRetTy::Default(span) => {
2108 let LoweredNodeId { node_id, hir_id } = this.next_id();
2112 node: hir::TyTup(hir_vec![]),
2118 let hir::Path { def, segments, .. } = this.std_path(span, &["future", "Future"], false);
2119 let future_path = hir::Path {
2120 segments: segments.map_slice(|mut v| {
2121 v.last_mut().unwrap().parameters = Some(P(hir::PathParameters {
2122 lifetimes: hir_vec![],
2124 bindings: hir_vec![hir::TypeBinding {
2125 name: Symbol::intern(FN_OUTPUT_NAME),
2127 id: this.next_id().node_id,
2130 parenthesized: false,
2137 // FIXME(cramertj) collect input lifetimes to function and add them to
2138 // the output `impl Trait` type here.
2139 let mut bounds = vec![
2140 hir::TyParamBound::TraitTyParamBound(
2142 trait_ref: hir::TraitRef {
2144 ref_id: this.next_id().node_id,
2146 bound_generic_params: hir_vec![],
2149 hir::TraitBoundModifier::None
2153 if let Some((name, span)) = bound_lifetime {
2154 bounds.push(hir::RegionTyParamBound(
2155 hir::Lifetime { id: this.next_id().node_id, name, span }));
2158 hir::HirVec::from(bounds)
2161 let LoweredNodeId { node_id, hir_id } = self.next_id();
2162 let impl_trait_ty = P(hir::Ty {
2164 node: impl_trait_ty,
2169 hir::FunctionRetTy::Return(impl_trait_ty)
2172 fn lower_param_bound(
2175 itctx: ImplTraitContext,
2176 ) -> hir::GenericBound {
2178 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2179 self.lower_poly_trait_ref(ty, itctx),
2180 self.lower_trait_bound_modifier(modifier),
2182 GenericBound::Outlives(ref lifetime) => {
2183 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2188 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2189 let span = l.ident.span;
2190 match self.lower_ident(l.ident) {
2191 x if x == "'static" => self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2192 x if x == "'_" => match self.anonymous_lifetime_mode {
2193 AnonymousLifetimeMode::CreateParameter => {
2194 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2195 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2198 AnonymousLifetimeMode::PassThrough => {
2199 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2203 self.maybe_collect_in_band_lifetime(span, name);
2204 let param_name = ParamName::Plain(name);
2205 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2210 fn new_named_lifetime(
2214 name: hir::LifetimeName,
2215 ) -> hir::Lifetime {
2217 id: self.lower_node_id(id).node_id,
2223 fn lower_generic_params(
2225 params: &Vec<GenericParam>,
2226 add_bounds: &NodeMap<Vec<GenericBound>>,
2227 itctx: ImplTraitContext,
2228 ) -> hir::HirVec<hir::GenericParam> {
2229 params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect()
2232 fn lower_generic_param(&mut self,
2233 param: &GenericParam,
2234 add_bounds: &NodeMap<Vec<GenericBound>>,
2235 itctx: ImplTraitContext)
2236 -> hir::GenericParam {
2237 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx);
2239 GenericParamKind::Lifetime => {
2240 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2241 self.is_collecting_in_band_lifetimes = false;
2243 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
2244 let param_name = match lt.name {
2245 hir::LifetimeName::Param(param_name) => param_name,
2246 _ => hir::ParamName::Plain(lt.name.name()),
2248 let param = hir::GenericParam {
2252 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2253 attrs: self.lower_attrs(¶m.attrs),
2255 kind: hir::GenericParamKind::Lifetime { in_band: false }
2258 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2262 GenericParamKind::Type { ref default, .. } => {
2263 let mut name = self.lower_ident(param.ident);
2265 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2266 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2267 // Instead, use gensym("Self") to create a distinct name that looks the same.
2268 if name == keywords::SelfType.name() {
2269 name = Symbol::gensym("Self");
2272 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2273 if !add_bounds.is_empty() {
2274 bounds = bounds.into_iter()
2275 .chain(self.lower_param_bounds(add_bounds, itctx).into_iter())
2280 id: self.lower_node_id(param.id).node_id,
2281 name: hir::ParamName::Plain(name),
2282 span: param.ident.span,
2283 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2284 attrs: self.lower_attrs(¶m.attrs),
2286 kind: hir::GenericParamKind::Type {
2287 default: default.as_ref().map(|x| {
2288 self.lower_ty(x, ImplTraitContext::Disallowed)
2290 synthetic: param.attrs.iter()
2291 .filter(|attr| attr.check_name("rustc_synthetic"))
2292 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2302 generics: &Generics,
2303 itctx: ImplTraitContext)
2306 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2307 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2308 // paths where report_error is called are also the only paths that advance to after
2309 // the match statement, so the error reporting could probably just be moved there.
2310 let mut add_bounds = NodeMap();
2311 for pred in &generics.where_clause.predicates {
2312 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2313 'next_bound: for bound in &bound_pred.bounds {
2314 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2315 let report_error = |this: &mut Self| {
2316 this.diagnostic().span_err(
2317 bound_pred.bounded_ty.span,
2318 "`?Trait` bounds are only permitted at the \
2319 point where a type parameter is declared",
2322 // Check if the where clause type is a plain type parameter.
2323 match bound_pred.bounded_ty.node {
2324 TyKind::Path(None, ref path)
2325 if path.segments.len() == 1
2326 && bound_pred.bound_generic_params.is_empty() =>
2328 if let Some(Def::TyParam(def_id)) = self.resolver
2329 .get_resolution(bound_pred.bounded_ty.id)
2330 .map(|d| d.base_def())
2332 if let Some(node_id) =
2333 self.resolver.definitions().as_local_node_id(def_id)
2335 for param in &generics.params {
2337 GenericParamKind::Type { .. } => {
2338 if node_id == param.id {
2339 add_bounds.entry(param.id)
2340 .or_insert(Vec::new())
2341 .push(bound.clone());
2342 continue 'next_bound;
2352 _ => report_error(self),
2360 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2361 where_clause: self.lower_where_clause(&generics.where_clause),
2362 span: generics.span,
2366 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2368 id: self.lower_node_id(wc.id).node_id,
2369 predicates: wc.predicates
2371 .map(|predicate| self.lower_where_predicate(predicate))
2376 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2378 WherePredicate::BoundPredicate(WhereBoundPredicate {
2379 ref bound_generic_params,
2384 self.with_in_scope_lifetime_defs(
2385 &bound_generic_params,
2387 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2388 bound_generic_params: this.lower_generic_params(
2389 bound_generic_params,
2391 ImplTraitContext::Disallowed,
2393 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2396 .filter_map(|bound| match *bound {
2397 // Ignore `?Trait` bounds.
2398 // Tthey were copied into type parameters already.
2399 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2400 _ => Some(this.lower_param_bound(
2402 ImplTraitContext::Disallowed,
2411 WherePredicate::RegionPredicate(WhereRegionPredicate {
2415 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2417 lifetime: self.lower_lifetime(lifetime),
2418 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2420 WherePredicate::EqPredicate(WhereEqPredicate {
2425 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2426 id: self.lower_node_id(id).node_id,
2427 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2428 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2434 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2436 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2440 .map(|f| self.lower_struct_field(f))
2442 self.lower_node_id(id).node_id,
2444 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2448 .map(|f| self.lower_struct_field(f))
2450 self.lower_node_id(id).node_id,
2452 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2456 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2457 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2458 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2459 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2463 ref_id: self.lower_node_id(p.ref_id).node_id,
2467 fn lower_poly_trait_ref(
2470 itctx: ImplTraitContext,
2471 ) -> hir::PolyTraitRef {
2472 let bound_generic_params =
2473 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx);
2474 let trait_ref = self.with_parent_impl_lifetime_defs(
2475 &bound_generic_params,
2476 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2480 bound_generic_params,
2486 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2489 id: self.lower_node_id(f.id).node_id,
2490 ident: match f.ident {
2491 Some(ident) => ident,
2492 // FIXME(jseyfried) positional field hygiene
2493 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2495 vis: self.lower_visibility(&f.vis, None),
2496 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2497 attrs: self.lower_attrs(&f.attrs),
2501 fn lower_field(&mut self, f: &Field) -> hir::Field {
2503 id: self.next_id().node_id,
2505 expr: P(self.lower_expr(&f.expr)),
2507 is_shorthand: f.is_shorthand,
2511 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2513 ty: self.lower_ty(&mt.ty, itctx),
2514 mutbl: self.lower_mutability(mt.mutbl),
2518 fn lower_param_bounds(&mut self, bounds: &[GenericBound], itctx: ImplTraitContext)
2519 -> hir::GenericBounds {
2520 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx)).collect()
2523 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2524 let mut expr = None;
2526 let mut stmts = vec![];
2528 for (index, stmt) in b.stmts.iter().enumerate() {
2529 if index == b.stmts.len() - 1 {
2530 if let StmtKind::Expr(ref e) = stmt.node {
2531 expr = Some(P(self.lower_expr(e)));
2533 stmts.extend(self.lower_stmt(stmt));
2536 stmts.extend(self.lower_stmt(stmt));
2540 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2545 stmts: stmts.into(),
2547 rules: self.lower_block_check_mode(&b.rules),
2550 recovered: b.recovered,
2558 attrs: &hir::HirVec<Attribute>,
2559 vis: &mut hir::Visibility,
2563 ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2564 ItemKind::Use(ref use_tree) => {
2565 // Start with an empty prefix
2568 span: use_tree.span,
2571 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2573 ItemKind::Static(ref t, m, ref e) => {
2574 let value = self.lower_body(None, |this| this.lower_expr(e));
2576 self.lower_ty(t, ImplTraitContext::Disallowed),
2577 self.lower_mutability(m),
2581 ItemKind::Const(ref t, ref e) => {
2582 let value = self.lower_body(None, |this| this.lower_expr(e));
2583 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2585 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2586 let fn_def_id = self.resolver.definitions().local_def_id(id);
2588 self.with_new_scopes(|this| {
2589 // Note: we can use non-async decl here because lower_body
2590 // only cares about the input argument patterns,
2591 // not the return types.
2592 let body_id = this.lower_body(Some(decl), |this| {
2593 if let IsAsync::Async(async_node_id) = header.asyncness {
2594 let async_expr = this.make_async_expr(
2595 CaptureBy::Value, async_node_id, None,
2597 let body = this.lower_block(body, false);
2598 this.expr_block(body, ThinVec::new())
2600 this.expr(body.span, async_expr, ThinVec::new())
2602 let body = this.lower_block(body, false);
2603 this.expr_block(body, ThinVec::new())
2607 let (generics, fn_decl) = this.add_in_band_defs(
2610 AnonymousLifetimeMode::PassThrough,
2611 |this| this.lower_fn_decl(
2612 decl, Some(fn_def_id), true, header.asyncness.is_async())
2617 this.lower_fn_header(header),
2623 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2624 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2625 ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2626 ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2627 self.lower_ty(t, ImplTraitContext::Disallowed),
2628 self.lower_generics(generics, ImplTraitContext::Disallowed),
2630 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2632 variants: enum_definition
2635 .map(|x| self.lower_variant(x))
2638 self.lower_generics(generics, ImplTraitContext::Disallowed),
2640 ItemKind::Struct(ref struct_def, ref generics) => {
2641 let struct_def = self.lower_variant_data(struct_def);
2644 self.lower_generics(generics, ImplTraitContext::Disallowed),
2647 ItemKind::Union(ref vdata, ref generics) => {
2648 let vdata = self.lower_variant_data(vdata);
2651 self.lower_generics(generics, ImplTraitContext::Disallowed),
2663 let def_id = self.resolver.definitions().local_def_id(id);
2665 // Lower the "impl header" first. This ordering is important
2666 // for in-band lifetimes! Consider `'a` here:
2668 // impl Foo<'a> for u32 {
2669 // fn method(&'a self) { .. }
2672 // Because we start by lowering the `Foo<'a> for u32`
2673 // part, we will add `'a` to the list of generics on
2674 // the impl. When we then encounter it later in the
2675 // method, it will not be considered an in-band
2676 // lifetime to be added, but rather a reference to a
2678 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2681 AnonymousLifetimeMode::CreateParameter,
2683 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2684 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2687 if let Some(ref trait_ref) = trait_ref {
2688 if let Def::Trait(def_id) = trait_ref.path.def {
2689 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2693 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2695 (trait_ref, lowered_ty)
2699 let new_impl_items = self.with_in_scope_lifetime_defs(
2700 &ast_generics.params,
2704 .map(|item| this.lower_impl_item_ref(item))
2710 self.lower_unsafety(unsafety),
2711 self.lower_impl_polarity(polarity),
2712 self.lower_defaultness(defaultness, true /* [1] */),
2719 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2720 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2723 .map(|item| self.lower_trait_item_ref(item))
2726 self.lower_is_auto(is_auto),
2727 self.lower_unsafety(unsafety),
2728 self.lower_generics(generics, ImplTraitContext::Disallowed),
2733 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2734 self.lower_generics(generics, ImplTraitContext::Disallowed),
2735 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2737 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2740 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2741 // not cause an assertion failure inside the `lower_defaultness` function
2749 vis: &mut hir::Visibility,
2751 attrs: &hir::HirVec<Attribute>,
2753 let path = &tree.prefix;
2756 UseTreeKind::Simple(rename, id1, id2) => {
2757 *name = tree.ident().name;
2759 // First apply the prefix to the path
2760 let mut path = Path {
2764 .chain(path.segments.iter())
2770 // Correctly resolve `self` imports
2771 if path.segments.len() > 1
2772 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2774 let _ = path.segments.pop();
2775 if rename.is_none() {
2776 *name = path.segments.last().unwrap().ident.name;
2780 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2781 let mut defs = self.expect_full_def_from_use(id);
2782 // we want to return *something* from this function, so hang onto the first item
2784 let mut ret_def = defs.next().unwrap_or(Def::Err);
2786 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2787 let vis = vis.clone();
2788 let name = name.clone();
2789 let span = path.span;
2790 self.resolver.definitions().create_def_with_parent(
2794 DefIndexAddressSpace::High,
2797 self.allocate_hir_id_counter(new_node_id, &path);
2799 self.with_hir_id_owner(new_node_id, |this| {
2800 let new_id = this.lower_node_id(new_node_id);
2801 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2802 let item = hir::ItemUse(P(path), hir::UseKind::Single);
2803 let vis = match vis {
2804 hir::Visibility::Public => hir::Visibility::Public,
2805 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2806 hir::Visibility::Inherited => hir::Visibility::Inherited,
2807 hir::Visibility::Restricted { ref path, id: _ } => {
2808 hir::Visibility::Restricted {
2810 // We are allocating a new NodeId here
2811 id: this.next_id().node_id,
2820 hir_id: new_id.hir_id,
2822 attrs: attrs.clone(),
2831 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2832 hir::ItemUse(path, hir::UseKind::Single)
2834 UseTreeKind::Glob => {
2835 let path = P(self.lower_path(
2841 .chain(path.segments.iter())
2846 ParamMode::Explicit,
2848 hir::ItemUse(path, hir::UseKind::Glob)
2850 UseTreeKind::Nested(ref trees) => {
2855 .chain(path.segments.iter())
2858 span: prefix.span.to(path.span),
2861 // Add all the nested PathListItems in the HIR
2862 for &(ref use_tree, id) in trees {
2863 self.allocate_hir_id_counter(id, &use_tree);
2867 } = self.lower_node_id(id);
2869 let mut vis = vis.clone();
2870 let mut name = name.clone();
2872 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2874 self.with_hir_id_owner(new_id, |this| {
2875 let vis = match vis {
2876 hir::Visibility::Public => hir::Visibility::Public,
2877 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2878 hir::Visibility::Inherited => hir::Visibility::Inherited,
2879 hir::Visibility::Restricted { ref path, id: _ } => {
2880 hir::Visibility::Restricted {
2882 // We are allocating a new NodeId here
2883 id: this.next_id().node_id,
2894 attrs: attrs.clone(),
2897 span: use_tree.span,
2903 // Privatize the degenerate import base, used only to check
2904 // the stability of `use a::{};`, to avoid it showing up as
2905 // a re-export by accident when `pub`, e.g. in documentation.
2906 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2907 *vis = hir::Inherited;
2908 hir::ItemUse(path, hir::UseKind::ListStem)
2913 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2914 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2915 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2917 let (generics, node) = match i.node {
2918 TraitItemKind::Const(ref ty, ref default) => (
2919 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2920 hir::TraitItemKind::Const(
2921 self.lower_ty(ty, ImplTraitContext::Disallowed),
2924 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2927 TraitItemKind::Method(ref sig, None) => {
2928 let names = self.lower_fn_args_to_names(&sig.decl);
2929 self.add_in_band_defs(
2932 AnonymousLifetimeMode::PassThrough,
2934 hir::TraitItemKind::Method(
2935 this.lower_method_sig(sig, trait_item_def_id, false, false),
2936 hir::TraitMethod::Required(names),
2941 TraitItemKind::Method(ref sig, Some(ref body)) => {
2942 let body_id = self.lower_body(Some(&sig.decl), |this| {
2943 let body = this.lower_block(body, false);
2944 this.expr_block(body, ThinVec::new())
2947 self.add_in_band_defs(
2950 AnonymousLifetimeMode::PassThrough,
2952 hir::TraitItemKind::Method(
2953 this.lower_method_sig(sig, trait_item_def_id, false, false),
2954 hir::TraitMethod::Provided(body_id),
2959 TraitItemKind::Type(ref bounds, ref default) => (
2960 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2961 hir::TraitItemKind::Type(
2962 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2965 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2968 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2974 name: self.lower_ident(i.ident),
2975 attrs: self.lower_attrs(&i.attrs),
2982 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2983 let (kind, has_default) = match i.node {
2984 TraitItemKind::Const(_, ref default) => {
2985 (hir::AssociatedItemKind::Const, default.is_some())
2987 TraitItemKind::Type(_, ref default) => {
2988 (hir::AssociatedItemKind::Type, default.is_some())
2990 TraitItemKind::Method(ref sig, ref default) => (
2991 hir::AssociatedItemKind::Method {
2992 has_self: sig.decl.has_self(),
2996 TraitItemKind::Macro(..) => unimplemented!(),
2999 id: hir::TraitItemId { node_id: i.id },
3000 name: self.lower_ident(i.ident),
3002 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3007 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3008 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3009 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3011 let (generics, node) = match i.node {
3012 ImplItemKind::Const(ref ty, ref expr) => {
3013 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3015 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3016 hir::ImplItemKind::Const(
3017 self.lower_ty(ty, ImplTraitContext::Disallowed),
3022 ImplItemKind::Method(ref sig, ref body) => {
3023 let body_id = self.lower_body(Some(&sig.decl), |this| {
3024 if let IsAsync::Async(async_node_id) = sig.header.asyncness {
3025 let async_expr = this.make_async_expr(
3026 CaptureBy::Value, async_node_id, None,
3028 let body = this.lower_block(body, false);
3029 this.expr_block(body, ThinVec::new())
3031 this.expr(body.span, async_expr, ThinVec::new())
3033 let body = this.lower_block(body, false);
3034 this.expr_block(body, ThinVec::new())
3037 let impl_trait_return_allow = !self.is_in_trait_impl;
3039 self.add_in_band_defs(
3042 AnonymousLifetimeMode::PassThrough,
3044 hir::ImplItemKind::Method(
3045 this.lower_method_sig(
3048 impl_trait_return_allow,
3049 sig.header.asyncness.is_async(),
3056 ImplItemKind::Type(ref ty) => (
3057 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3058 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
3060 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3066 name: self.lower_ident(i.ident),
3067 attrs: self.lower_attrs(&i.attrs),
3069 vis: self.lower_visibility(&i.vis, None),
3070 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3075 // [1] since `default impl` is not yet implemented, this is always true in impls
3078 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3080 id: hir::ImplItemId { node_id: i.id },
3081 name: self.lower_ident(i.ident),
3083 vis: self.lower_visibility(&i.vis, Some(i.id)),
3084 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3085 kind: match i.node {
3086 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3087 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3088 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3089 has_self: sig.decl.has_self(),
3091 ImplItemKind::Macro(..) => unimplemented!(),
3095 // [1] since `default impl` is not yet implemented, this is always true in impls
3098 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3101 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3105 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
3107 ItemKind::Use(ref use_tree) => {
3108 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
3109 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3112 ItemKind::MacroDef(..) => return SmallVector::new(),
3115 SmallVector::one(hir::ItemId { id: i.id })
3118 fn lower_item_id_use_tree(&mut self,
3121 vec: &mut SmallVector<hir::ItemId>)
3124 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3125 vec.push(hir::ItemId { id });
3126 self.lower_item_id_use_tree(nested, id, vec);
3128 UseTreeKind::Glob => {}
3129 UseTreeKind::Simple(_, id1, id2) => {
3130 for (_, &id) in self.expect_full_def_from_use(base_id)
3132 .zip([id1, id2].iter())
3134 vec.push(hir::ItemId { id });
3140 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3141 let mut name = i.ident.name;
3142 let mut vis = self.lower_visibility(&i.vis, None);
3143 let attrs = self.lower_attrs(&i.attrs);
3144 if let ItemKind::MacroDef(ref def) = i.node {
3145 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
3146 let body = self.lower_token_stream(def.stream());
3147 self.exported_macros.push(hir::MacroDef {
3160 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3162 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3175 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3176 let node_id = self.lower_node_id(i.id).node_id;
3177 let def_id = self.resolver.definitions().local_def_id(node_id);
3181 attrs: self.lower_attrs(&i.attrs),
3182 node: match i.node {
3183 ForeignItemKind::Fn(ref fdec, ref generics) => {
3184 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3187 AnonymousLifetimeMode::PassThrough,
3190 // Disallow impl Trait in foreign items
3191 this.lower_fn_decl(fdec, None, false, false),
3192 this.lower_fn_args_to_names(fdec),
3197 hir::ForeignItemFn(fn_dec, fn_args, generics)
3199 ForeignItemKind::Static(ref t, m) => {
3200 hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
3202 ForeignItemKind::Ty => hir::ForeignItemType,
3203 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3205 vis: self.lower_visibility(&i.vis, None),
3210 fn lower_method_sig(
3214 impl_trait_return_allow: bool,
3216 ) -> hir::MethodSig {
3218 header: self.lower_fn_header(sig.header),
3219 decl: self.lower_fn_decl(&sig.decl, Some(fn_def_id), impl_trait_return_allow, is_async),
3223 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3225 IsAuto::Yes => hir::IsAuto::Yes,
3226 IsAuto::No => hir::IsAuto::No,
3230 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3232 unsafety: self.lower_unsafety(h.unsafety),
3233 asyncness: self.lower_asyncness(h.asyncness),
3234 constness: self.lower_constness(h.constness),
3239 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3241 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3242 Unsafety::Normal => hir::Unsafety::Normal,
3246 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3248 Constness::Const => hir::Constness::Const,
3249 Constness::NotConst => hir::Constness::NotConst,
3253 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3255 IsAsync::Async(_) => hir::IsAsync::Async,
3256 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3260 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3262 UnOp::Deref => hir::UnDeref,
3263 UnOp::Not => hir::UnNot,
3264 UnOp::Neg => hir::UnNeg,
3268 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3270 node: match b.node {
3271 BinOpKind::Add => hir::BiAdd,
3272 BinOpKind::Sub => hir::BiSub,
3273 BinOpKind::Mul => hir::BiMul,
3274 BinOpKind::Div => hir::BiDiv,
3275 BinOpKind::Rem => hir::BiRem,
3276 BinOpKind::And => hir::BiAnd,
3277 BinOpKind::Or => hir::BiOr,
3278 BinOpKind::BitXor => hir::BiBitXor,
3279 BinOpKind::BitAnd => hir::BiBitAnd,
3280 BinOpKind::BitOr => hir::BiBitOr,
3281 BinOpKind::Shl => hir::BiShl,
3282 BinOpKind::Shr => hir::BiShr,
3283 BinOpKind::Eq => hir::BiEq,
3284 BinOpKind::Lt => hir::BiLt,
3285 BinOpKind::Le => hir::BiLe,
3286 BinOpKind::Ne => hir::BiNe,
3287 BinOpKind::Ge => hir::BiGe,
3288 BinOpKind::Gt => hir::BiGt,
3294 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3295 let node = match p.node {
3296 PatKind::Wild => hir::PatKind::Wild,
3297 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3298 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3299 // `None` can occur in body-less function signatures
3300 def @ None | def @ Some(Def::Local(_)) => {
3301 let canonical_id = match def {
3302 Some(Def::Local(id)) => id,
3305 hir::PatKind::Binding(
3306 self.lower_binding_mode(binding_mode),
3308 respan(ident.span, ident.name),
3309 sub.as_ref().map(|x| self.lower_pat(x)),
3312 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3317 segments: hir_vec![hir::PathSegment::from_name(ident.name)],
3322 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3323 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3324 let qpath = self.lower_qpath(
3328 ParamMode::Optional,
3329 ImplTraitContext::Disallowed,
3331 hir::PatKind::TupleStruct(
3333 pats.iter().map(|x| self.lower_pat(x)).collect(),
3337 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3341 ParamMode::Optional,
3342 ImplTraitContext::Disallowed,
3344 PatKind::Struct(ref path, ref fields, etc) => {
3345 let qpath = self.lower_qpath(
3349 ParamMode::Optional,
3350 ImplTraitContext::Disallowed,
3357 node: hir::FieldPat {
3358 id: self.next_id().node_id,
3359 ident: f.node.ident,
3360 pat: self.lower_pat(&f.node.pat),
3361 is_shorthand: f.node.is_shorthand,
3365 hir::PatKind::Struct(qpath, fs, etc)
3367 PatKind::Tuple(ref elts, ddpos) => {
3368 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3370 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3371 PatKind::Ref(ref inner, mutbl) => {
3372 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3374 PatKind::Range(ref e1, ref e2, ref end) => hir::PatKind::Range(
3375 P(self.lower_expr(e1)),
3376 P(self.lower_expr(e2)),
3377 self.lower_range_end(end),
3379 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3380 before.iter().map(|x| self.lower_pat(x)).collect(),
3381 slice.as_ref().map(|x| self.lower_pat(x)),
3382 after.iter().map(|x| self.lower_pat(x)).collect(),
3384 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3385 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3388 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3397 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3399 RangeEnd::Included(_) => hir::RangeEnd::Included,
3400 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3404 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3405 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3410 body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3414 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3415 let kind = match e.node {
3416 ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
3417 ExprKind::ObsoleteInPlace(..) => {
3418 self.sess.abort_if_errors();
3419 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3421 ExprKind::Array(ref exprs) => {
3422 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
3424 ExprKind::Repeat(ref expr, ref count) => {
3425 let expr = P(self.lower_expr(expr));
3426 let count = self.lower_anon_const(count);
3427 hir::ExprRepeat(expr, count)
3429 ExprKind::Tup(ref elts) => {
3430 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
3432 ExprKind::Call(ref f, ref args) => {
3433 let f = P(self.lower_expr(f));
3434 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
3436 ExprKind::MethodCall(ref seg, ref args) => {
3437 let hir_seg = self.lower_path_segment(
3440 ParamMode::Optional,
3442 ParenthesizedGenericArgs::Err,
3443 ImplTraitContext::Disallowed,
3445 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3446 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
3448 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3449 let binop = self.lower_binop(binop);
3450 let lhs = P(self.lower_expr(lhs));
3451 let rhs = P(self.lower_expr(rhs));
3452 hir::ExprBinary(binop, lhs, rhs)
3454 ExprKind::Unary(op, ref ohs) => {
3455 let op = self.lower_unop(op);
3456 let ohs = P(self.lower_expr(ohs));
3457 hir::ExprUnary(op, ohs)
3459 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
3460 ExprKind::Cast(ref expr, ref ty) => {
3461 let expr = P(self.lower_expr(expr));
3462 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3464 ExprKind::Type(ref expr, ref ty) => {
3465 let expr = P(self.lower_expr(expr));
3466 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3468 ExprKind::AddrOf(m, ref ohs) => {
3469 let m = self.lower_mutability(m);
3470 let ohs = P(self.lower_expr(ohs));
3471 hir::ExprAddrOf(m, ohs)
3473 // More complicated than you might expect because the else branch
3474 // might be `if let`.
3475 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3476 let else_opt = else_opt.as_ref().map(|els| {
3478 ExprKind::IfLet(..) => {
3479 // wrap the if-let expr in a block
3480 let span = els.span;
3481 let els = P(self.lower_expr(els));
3482 let LoweredNodeId { node_id, hir_id } = self.next_id();
3483 let blk = P(hir::Block {
3488 rules: hir::DefaultBlock,
3490 targeted_by_break: false,
3491 recovered: blk.recovered,
3493 P(self.expr_block(blk, ThinVec::new()))
3495 _ => P(self.lower_expr(els)),
3499 let then_blk = self.lower_block(blk, false);
3500 let then_expr = self.expr_block(then_blk, ThinVec::new());
3502 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3504 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3506 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3507 this.lower_block(body, false),
3508 this.lower_label(opt_label),
3511 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3513 this.lower_block(body, false),
3514 this.lower_label(opt_label),
3515 hir::LoopSource::Loop,
3518 ExprKind::Catch(ref body) => {
3519 self.with_catch_scope(body.id, |this| {
3521 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3522 let mut block = this.lower_block(body, true).into_inner();
3523 let tail = block.expr.take().map_or_else(
3525 let LoweredNodeId { node_id, hir_id } = this.next_id();
3526 let span = this.sess.codemap().end_point(unstable_span);
3530 node: hir::ExprTup(hir_vec![]),
3531 attrs: ThinVec::new(),
3535 |x: P<hir::Expr>| x.into_inner(),
3537 block.expr = Some(this.wrap_in_try_constructor(
3538 "from_ok", tail, unstable_span));
3539 hir::ExprBlock(P(block), None)
3542 ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3543 P(self.lower_expr(expr)),
3544 arms.iter().map(|x| self.lower_arm(x)).collect(),
3545 hir::MatchSource::Normal,
3547 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3548 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3549 this.with_new_scopes(|this| {
3550 let block = this.lower_block(block, false);
3551 this.expr_block(block, ThinVec::new())
3556 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span) =>
3558 self.with_new_scopes(|this| {
3559 if let IsAsync::Async(async_closure_node_id) = asyncness {
3560 // FIXME(cramertj) allow `async` non-`move` closures with
3561 if capture_clause == CaptureBy::Ref &&
3562 !decl.inputs.is_empty()
3568 "`async` non-`move` closures with arguments \
3569 are not currently supported",
3571 .help("consider using `let` statements to manually capture \
3572 variables by reference before entering an \
3573 `async move` closure")
3577 // Transform `async |x: u8| -> X { ... }` into
3578 // `|x: u8| future_from_generator(|| -> X { ... })`
3579 let outer_decl = FnDecl {
3580 inputs: decl.inputs.clone(),
3581 output: FunctionRetTy::Default(fn_decl_span),
3584 let body_id = this.lower_body(Some(&outer_decl), |this| {
3585 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3588 let async_body = this.make_async_expr(
3589 capture_clause, async_closure_node_id, async_ret_ty,
3591 this.with_new_scopes(|this| this.lower_expr(body))
3593 this.expr(fn_decl_span, async_body, ThinVec::new())
3596 this.lower_capture_clause(capture_clause),
3597 this.lower_fn_decl(&outer_decl, None, false, false),
3603 let mut is_generator = false;
3604 let body_id = this.lower_body(Some(decl), |this| {
3605 let e = this.lower_expr(body);
3606 is_generator = this.is_generator;
3609 let generator_option = if is_generator {
3610 if !decl.inputs.is_empty() {
3615 "generators cannot have explicit arguments"
3617 this.sess.abort_if_errors();
3619 Some(match movability {
3620 Movability::Movable => hir::GeneratorMovability::Movable,
3621 Movability::Static => hir::GeneratorMovability::Static,
3624 if movability == Movability::Static {
3629 "closures cannot be static"
3635 this.lower_capture_clause(capture_clause),
3636 this.lower_fn_decl(decl, None, false, false),
3644 ExprKind::Block(ref blk, opt_label) => {
3645 hir::ExprBlock(self.lower_block(blk,
3646 opt_label.is_some()),
3647 self.lower_label(opt_label))
3649 ExprKind::Assign(ref el, ref er) => {
3650 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3652 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3653 self.lower_binop(op),
3654 P(self.lower_expr(el)),
3655 P(self.lower_expr(er)),
3657 ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3658 ExprKind::Index(ref el, ref er) => {
3659 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3661 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3662 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3663 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3664 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3665 let id = self.next_id();
3666 let e1 = self.lower_expr(e1);
3667 let e2 = self.lower_expr(e2);
3668 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], false));
3669 let ty = self.ty_path(id, span, hir::QPath::Resolved(None, ty_path));
3670 let new_seg = P(hir::PathSegment::from_name(Symbol::intern("new")));
3671 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3672 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3673 hir::ExprCall(new, hir_vec![e1, e2])
3675 ExprKind::Range(ref e1, ref e2, lims) => {
3676 use syntax::ast::RangeLimits::*;
3678 let path = match (e1, e2, lims) {
3679 (&None, &None, HalfOpen) => "RangeFull",
3680 (&Some(..), &None, HalfOpen) => "RangeFrom",
3681 (&None, &Some(..), HalfOpen) => "RangeTo",
3682 (&Some(..), &Some(..), HalfOpen) => "Range",
3683 (&None, &Some(..), Closed) => "RangeToInclusive",
3684 (&Some(..), &Some(..), Closed) => unreachable!(),
3685 (_, &None, Closed) => self.diagnostic()
3686 .span_fatal(e.span, "inclusive range with no end")
3690 let fields = e1.iter()
3691 .map(|e| ("start", e))
3692 .chain(e2.iter().map(|e| ("end", e)))
3694 let expr = P(self.lower_expr(&e));
3696 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3697 let ident = Ident::new(Symbol::intern(s), unstable_span);
3698 self.field(ident, expr, unstable_span)
3700 .collect::<P<[hir::Field]>>();
3702 let is_unit = fields.is_empty();
3704 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3705 let struct_path = iter::once("ops")
3706 .chain(iter::once(path))
3707 .collect::<Vec<_>>();
3708 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
3709 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3711 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3717 hir::ExprPath(struct_path)
3719 hir::ExprStruct(struct_path, fields, None)
3721 span: unstable_span,
3722 attrs: e.attrs.clone(),
3725 ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3729 ParamMode::Optional,
3730 ImplTraitContext::Disallowed,
3732 ExprKind::Break(opt_label, ref opt_expr) => {
3733 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3736 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3739 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3743 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3746 ExprKind::Continue(opt_label) => {
3747 hir::ExprAgain(if self.is_in_loop_condition && opt_label.is_none() {
3750 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3753 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3756 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3757 ExprKind::InlineAsm(ref asm) => {
3758 let hir_asm = hir::InlineAsm {
3759 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3760 outputs: asm.outputs
3762 .map(|out| hir::InlineAsmOutput {
3763 constraint: out.constraint.clone(),
3765 is_indirect: out.is_indirect,
3768 asm: asm.asm.clone(),
3769 asm_str_style: asm.asm_str_style,
3770 clobbers: asm.clobbers.clone().into(),
3771 volatile: asm.volatile,
3772 alignstack: asm.alignstack,
3773 dialect: asm.dialect,
3776 let outputs = asm.outputs
3778 .map(|out| self.lower_expr(&out.expr))
3780 let inputs = asm.inputs
3782 .map(|&(_, ref input)| self.lower_expr(input))
3784 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3786 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3791 ParamMode::Optional,
3792 ImplTraitContext::Disallowed,
3794 fields.iter().map(|x| self.lower_field(x)).collect(),
3795 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3797 ExprKind::Paren(ref ex) => {
3798 let mut ex = self.lower_expr(ex);
3799 // include parens in span, but only if it is a super-span.
3800 if e.span.contains(ex.span) {
3803 // merge attributes into the inner expression.
3804 let mut attrs = e.attrs.clone();
3805 attrs.extend::<Vec<_>>(ex.attrs.into());
3810 ExprKind::Yield(ref opt_expr) => {
3811 self.is_generator = true;
3814 .map(|x| self.lower_expr(x))
3815 .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3816 hir::ExprYield(P(expr))
3819 // Desugar ExprIfLet
3820 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3821 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3824 // match <sub_expr> {
3826 // _ => [<else_opt> | ()]
3829 let mut arms = vec![];
3831 // `<pat> => <body>`
3833 let body = self.lower_block(body, false);
3834 let body_expr = P(self.expr_block(body, ThinVec::new()));
3835 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3836 arms.push(self.arm(pats, body_expr));
3839 // _ => [<else_opt>|()]
3841 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3842 let wildcard_pattern = self.pat_wild(e.span);
3843 let body = if let Some(else_expr) = wildcard_arm {
3844 P(self.lower_expr(else_expr))
3846 self.expr_tuple(e.span, hir_vec![])
3848 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3851 let contains_else_clause = else_opt.is_some();
3853 let sub_expr = P(self.lower_expr(sub_expr));
3858 hir::MatchSource::IfLetDesugar {
3859 contains_else_clause,
3864 // Desugar ExprWhileLet
3865 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3866 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3869 // [opt_ident]: loop {
3870 // match <sub_expr> {
3876 // Note that the block AND the condition are evaluated in the loop scope.
3877 // This is done to allow `break` from inside the condition of the loop.
3878 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3880 this.lower_block(body, false),
3881 this.expr_break(e.span, ThinVec::new()),
3882 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3886 // `<pat> => <body>`
3888 let body_expr = P(self.expr_block(body, ThinVec::new()));
3889 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3890 self.arm(pats, body_expr)
3895 let pat_under = self.pat_wild(e.span);
3896 self.arm(hir_vec![pat_under], break_expr)
3899 // `match <sub_expr> { ... }`
3900 let arms = hir_vec![pat_arm, break_arm];
3901 let match_expr = self.expr(
3903 hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3907 // `[opt_ident]: loop { ... }`
3908 let loop_block = P(self.block_expr(P(match_expr)));
3909 let loop_expr = hir::ExprLoop(
3911 self.lower_label(opt_label),
3912 hir::LoopSource::WhileLet,
3914 // add attributes to the outer returned expr node
3918 // Desugar ExprForLoop
3919 // From: `[opt_ident]: for <pat> in <head> <body>`
3920 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3924 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3926 // [opt_ident]: loop {
3928 // match ::std::iter::Iterator::next(&mut iter) {
3929 // ::std::option::Option::Some(val) => __next = val,
3930 // ::std::option::Option::None => break
3932 // let <pat> = __next;
3933 // StmtExpr(<body>);
3941 let head = self.lower_expr(head);
3942 let head_sp = head.span;
3944 let iter = self.str_to_ident("iter");
3946 let next_ident = self.str_to_ident("__next");
3947 let next_pat = self.pat_ident_binding_mode(
3950 hir::BindingAnnotation::Mutable,
3953 // `::std::option::Option::Some(val) => next = val`
3955 let val_ident = self.str_to_ident("val");
3956 let val_pat = self.pat_ident(pat.span, val_ident);
3957 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
3958 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
3959 let assign = P(self.expr(
3961 hir::ExprAssign(next_expr, val_expr),
3964 let some_pat = self.pat_some(pat.span, val_pat);
3965 self.arm(hir_vec![some_pat], assign)
3968 // `::std::option::Option::None => break`
3971 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
3972 let pat = self.pat_none(e.span);
3973 self.arm(hir_vec![pat], break_expr)
3978 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
3980 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
3982 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
3983 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
3984 let next_path = &["iter", "Iterator", "next"];
3985 let next_path = P(self.expr_std_path(head_sp, next_path, ThinVec::new()));
3986 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
3987 let arms = hir_vec![pat_arm, break_arm];
3991 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
3995 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
3997 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4001 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
4003 // `let <pat> = __next`
4004 let pat = self.lower_pat(pat);
4005 let pat_let = self.stmt_let_pat(
4009 hir::LocalSource::ForLoopDesugar,
4012 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4013 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4014 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
4016 let loop_block = P(self.block_all(
4018 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4022 // `[opt_ident]: loop { ... }`
4023 let loop_expr = hir::ExprLoop(
4025 self.lower_label(opt_label),
4026 hir::LoopSource::ForLoop,
4028 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4029 let loop_expr = P(hir::Expr {
4034 attrs: ThinVec::new(),
4037 // `mut iter => { ... }`
4038 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4040 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4041 let into_iter_expr = {
4042 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4043 let into_iter = P(self.expr_std_path(head_sp, into_iter_path, 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(unstable_span, path, ThinVec::new()));
4090 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4093 // #[allow(unreachable_code)]
4095 // allow(unreachable_code)
4097 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4098 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4099 let uc_nested = attr::mk_nested_word_item(uc_ident);
4100 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4102 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4104 let attrs = vec![attr];
4106 // Ok(val) => #[allow(unreachable_code)] val,
4108 let val_ident = self.str_to_ident("val");
4109 let val_pat = self.pat_ident(e.span, val_ident);
4110 let val_expr = P(self.expr_ident_with_attrs(
4114 ThinVec::from(attrs.clone()),
4116 let ok_pat = self.pat_ok(e.span, val_pat);
4118 self.arm(hir_vec![ok_pat], val_expr)
4121 // Err(err) => #[allow(unreachable_code)]
4122 // return Try::from_error(From::from(err)),
4124 let err_ident = self.str_to_ident("err");
4125 let err_local = self.pat_ident(e.span, err_ident);
4127 let path = &["convert", "From", "from"];
4128 let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
4129 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4131 self.expr_call(e.span, from, hir_vec![err_expr])
4134 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4135 let thin_attrs = ThinVec::from(attrs);
4136 let catch_scope = self.catch_scopes.last().map(|x| *x);
4137 let ret_expr = if let Some(catch_node) = catch_scope {
4143 target_id: Ok(catch_node),
4145 Some(from_err_expr),
4150 P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
4153 let err_pat = self.pat_err(e.span, err_local);
4154 self.arm(hir_vec![err_pat], ret_expr)
4159 hir_vec![err_arm, ok_arm],
4160 hir::MatchSource::TryDesugar,
4164 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4167 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4174 attrs: e.attrs.clone(),
4178 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
4179 SmallVector::one(match s.node {
4180 StmtKind::Local(ref l) => Spanned {
4181 node: hir::StmtDecl(
4183 node: hir::DeclLocal(self.lower_local(l)),
4186 self.lower_node_id(s.id).node_id,
4190 StmtKind::Item(ref it) => {
4191 // Can only use the ID once.
4192 let mut id = Some(s.id);
4193 return self.lower_item_id(it)
4195 .map(|item_id| Spanned {
4196 node: hir::StmtDecl(
4198 node: hir::DeclItem(item_id),
4202 .map(|id| self.lower_node_id(id).node_id)
4203 .unwrap_or_else(|| self.next_id().node_id),
4209 StmtKind::Expr(ref e) => Spanned {
4210 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4213 StmtKind::Semi(ref e) => Spanned {
4214 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4217 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4221 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4223 CaptureBy::Value => hir::CaptureByValue,
4224 CaptureBy::Ref => hir::CaptureByRef,
4228 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4229 /// the address space of that item instead of the item currently being
4230 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4231 /// lower a `Visibility` value although we haven't lowered the owning
4232 /// `ImplItem` in question yet.
4233 fn lower_visibility(
4236 explicit_owner: Option<NodeId>,
4237 ) -> hir::Visibility {
4239 VisibilityKind::Public => hir::Public,
4240 VisibilityKind::Crate(sugar) => hir::Visibility::Crate(sugar),
4241 VisibilityKind::Restricted { ref path, id, .. } => hir::Visibility::Restricted {
4242 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4243 id: if let Some(owner) = explicit_owner {
4244 self.lower_node_id_with_owner(id, owner).node_id
4246 self.lower_node_id(id).node_id
4249 VisibilityKind::Inherited => hir::Inherited,
4253 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4255 Defaultness::Default => hir::Defaultness::Default {
4256 has_value: has_value,
4258 Defaultness::Final => {
4260 hir::Defaultness::Final
4265 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4267 BlockCheckMode::Default => hir::DefaultBlock,
4268 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4272 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4274 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4275 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4276 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4277 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4281 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4283 CompilerGenerated => hir::CompilerGenerated,
4284 UserProvided => hir::UserProvided,
4288 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4290 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4291 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4295 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4297 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4298 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4302 // Helper methods for building HIR.
4304 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4313 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4315 id: self.next_id().node_id,
4319 is_shorthand: false,
4323 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4324 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
4325 P(self.expr(span, expr_break, attrs))
4332 args: hir::HirVec<hir::Expr>,
4334 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
4337 fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
4338 self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
4341 fn expr_ident_with_attrs(
4346 attrs: ThinVec<Attribute>,
4348 let expr_path = hir::ExprPath(hir::QPath::Resolved(
4352 def: Def::Local(binding),
4353 segments: hir_vec![hir::PathSegment::from_name(id)],
4357 self.expr(span, expr_path, attrs)
4360 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4361 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
4367 components: &[&str],
4368 attrs: ThinVec<Attribute>,
4370 let path = self.std_path(span, components, true);
4373 hir::ExprPath(hir::QPath::Resolved(None, P(path))),
4382 arms: hir::HirVec<hir::Arm>,
4383 source: hir::MatchSource,
4385 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
4388 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4389 self.expr(b.span, hir::ExprBlock(b, None), attrs)
4392 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4393 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
4396 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
4397 let LoweredNodeId { node_id, hir_id } = self.next_id();
4410 ex: Option<P<hir::Expr>>,
4412 source: hir::LocalSource,
4414 let LoweredNodeId { node_id, hir_id } = self.next_id();
4416 let local = P(hir::Local {
4423 attrs: ThinVec::new(),
4426 let decl = respan(sp, hir::DeclLocal(local));
4427 respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
4436 ) -> (hir::Stmt, NodeId) {
4437 let pat = if mutbl {
4438 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4440 self.pat_ident(sp, ident)
4442 let pat_id = pat.id;
4444 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4449 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4450 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4456 stmts: hir::HirVec<hir::Stmt>,
4457 expr: Option<P<hir::Expr>>,
4459 let LoweredNodeId { node_id, hir_id } = self.next_id();
4466 rules: hir::DefaultBlock,
4468 targeted_by_break: false,
4473 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4474 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4477 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4478 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4481 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4482 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4485 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4486 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4492 components: &[&str],
4493 subpats: hir::HirVec<P<hir::Pat>>,
4495 let path = self.std_path(span, components, true);
4496 let qpath = hir::QPath::Resolved(None, P(path));
4497 let pt = if subpats.is_empty() {
4498 hir::PatKind::Path(qpath)
4500 hir::PatKind::TupleStruct(qpath, subpats, None)
4505 fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
4506 self.pat_ident_binding_mode(span, name, hir::BindingAnnotation::Unannotated)
4509 fn pat_ident_binding_mode(
4513 bm: hir::BindingAnnotation,
4515 let LoweredNodeId { node_id, hir_id } = self.next_id();
4520 node: hir::PatKind::Binding(bm, node_id, Spanned { span, node: name }, None),
4525 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4526 self.pat(span, hir::PatKind::Wild)
4529 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4530 let LoweredNodeId { node_id, hir_id } = self.next_id();
4539 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4540 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4541 /// The path is also resolved according to `is_value`.
4542 fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
4544 .resolve_str_path(span, self.crate_root, components, is_value)
4547 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
4549 let node = match qpath {
4550 hir::QPath::Resolved(None, path) => {
4551 // Turn trait object paths into `TyTraitObject` instead.
4552 if let Def::Trait(_) = path.def {
4553 let principal = hir::PolyTraitRef {
4554 bound_generic_params: hir::HirVec::new(),
4555 trait_ref: hir::TraitRef {
4556 path: path.and_then(|path| path),
4562 // The original ID is taken by the `PolyTraitRef`,
4563 // so the `Ty` itself needs a different one.
4564 id = self.next_id();
4565 hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4567 hir::TyPath(hir::QPath::Resolved(None, path))
4570 _ => hir::TyPath(qpath),
4580 /// Invoked to create the lifetime argument for a type `&T`
4581 /// with no explicit lifetime.
4582 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4583 match self.anonymous_lifetime_mode {
4584 // Intercept when we are in an impl header and introduce an in-band lifetime.
4585 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4587 AnonymousLifetimeMode::CreateParameter => {
4588 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4590 id: self.next_id().node_id,
4592 name: hir::LifetimeName::Param(fresh_name),
4596 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4600 /// Invoked to create the lifetime argument(s) for a path like
4601 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4602 /// sorts of cases are deprecated. This may therefore report a warning or an
4603 /// error, depending on the mode.
4604 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4605 match self.anonymous_lifetime_mode {
4606 // NB. We intentionally ignore the create-parameter mode here
4607 // and instead "pass through" to resolve-lifetimes, which will then
4608 // report an error. This is because we don't want to support
4609 // impl elision for deprecated forms like
4611 // impl Foo for std::cell::Ref<u32> // note lack of '_
4612 AnonymousLifetimeMode::CreateParameter => {}
4614 // This is the normal case.
4615 AnonymousLifetimeMode::PassThrough => {}
4619 .map(|_| self.new_implicit_lifetime(span))
4623 /// Invoked to create the lifetime argument(s) for an elided trait object
4624 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4625 /// when the bound is written, even if it is written with `'_` like in
4626 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4627 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4628 match self.anonymous_lifetime_mode {
4629 // NB. We intentionally ignore the create-parameter mode here.
4630 // and instead "pass through" to resolve-lifetimes, which will apply
4631 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4632 // do not act like other elided lifetimes. In other words, given this:
4634 // impl Foo for Box<dyn Debug>
4636 // we do not introduce a fresh `'_` to serve as the bound, but instead
4637 // ultimately translate to the equivalent of:
4639 // impl Foo for Box<dyn Debug + 'static>
4641 // `resolve_lifetime` has the code to make that happen.
4642 AnonymousLifetimeMode::CreateParameter => {}
4644 // This is the normal case.
4645 AnonymousLifetimeMode::PassThrough => {}
4648 self.new_implicit_lifetime(span)
4651 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4653 id: self.next_id().node_id,
4655 name: hir::LifetimeName::Implicit,
4659 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4660 self.sess.buffer_lint_with_diagnostic(
4661 builtin::BARE_TRAIT_OBJECTS,
4664 "trait objects without an explicit `dyn` are deprecated",
4665 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4669 fn wrap_in_try_constructor(
4671 method: &'static str,
4673 unstable_span: Span,
4675 let path = &["ops", "Try", method];
4676 let from_err = P(self.expr_std_path(unstable_span, path,
4678 P(self.expr_call(e.span, from_err, hir_vec![e]))
4682 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4683 // Sorting by span ensures that we get things in order within a
4684 // file, and also puts the files in a sensible order.
4685 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4686 body_ids.sort_by_key(|b| bodies[b].value.span);