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;
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, hir::LifetimeName)>,
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| param.is_lifetime_param())
329 self.lctx.type_def_lifetime_params.insert(def_id, count);
333 visit::walk_item(self, item);
336 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
337 self.lctx.allocate_hir_id_counter(item.id, item);
338 visit::walk_trait_item(self, item);
341 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
342 self.lctx.allocate_hir_id_counter(item.id, item);
343 visit::walk_impl_item(self, item);
347 struct ItemLowerer<'lcx, 'interner: 'lcx> {
348 lctx: &'lcx mut LoweringContext<'interner>,
351 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
352 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
354 F: FnOnce(&mut Self),
356 let old = self.lctx.is_in_trait_impl;
357 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
363 self.lctx.is_in_trait_impl = old;
367 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
368 fn visit_item(&mut self, item: &'lcx Item) {
369 let mut item_lowered = true;
370 self.lctx.with_hir_id_owner(item.id, |lctx| {
371 if let Some(hir_item) = lctx.lower_item(item) {
372 lctx.items.insert(item.id, hir_item);
374 item_lowered = false;
379 let item_lifetimes = match self.lctx.items.get(&item.id).unwrap().node {
380 hir::Item_::ItemImpl(_, _, _, ref generics, ..)
381 | hir::Item_::ItemTrait(_, _, ref generics, ..) => {
384 .filter_map(|param| match param.kind {
385 hir::GenericParamKind::Lifetime { .. } => {
395 self.lctx.with_parent_impl_lifetime_defs(&item_lifetimes, |this| {
396 let this = &mut ItemLowerer { lctx: this };
397 if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
398 this.with_trait_impl_ref(opt_trait_ref, |this| {
399 visit::walk_item(this, item)
402 visit::walk_item(this, item);
408 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
409 self.lctx.with_hir_id_owner(item.id, |lctx| {
410 let id = hir::TraitItemId { node_id: item.id };
411 let hir_item = lctx.lower_trait_item(item);
412 lctx.trait_items.insert(id, hir_item);
415 visit::walk_trait_item(self, item);
418 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
419 self.lctx.with_hir_id_owner(item.id, |lctx| {
420 let id = hir::ImplItemId { node_id: item.id };
421 let hir_item = lctx.lower_impl_item(item);
422 lctx.impl_items.insert(id, hir_item);
424 visit::walk_impl_item(self, item);
428 self.lower_node_id(CRATE_NODE_ID);
429 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
431 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
432 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
434 let module = self.lower_mod(&c.module);
435 let attrs = self.lower_attrs(&c.attrs);
436 let body_ids = body_ids(&self.bodies);
440 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
446 exported_macros: hir::HirVec::from(self.exported_macros),
448 trait_items: self.trait_items,
449 impl_items: self.impl_items,
452 trait_impls: self.trait_impls,
453 trait_auto_impl: self.trait_auto_impl,
457 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) {
458 if self.item_local_id_counters.insert(owner, 0).is_some() {
460 "Tried to allocate item_local_id_counter for {:?} twice",
464 // Always allocate the first HirId for the owner itself
465 self.lower_node_id_with_owner(owner, owner);
468 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
470 F: FnOnce(&mut Self) -> hir::HirId,
472 if ast_node_id == DUMMY_NODE_ID {
473 return LoweredNodeId {
474 node_id: DUMMY_NODE_ID,
475 hir_id: hir::DUMMY_HIR_ID,
479 let min_size = ast_node_id.as_usize() + 1;
481 if min_size > self.node_id_to_hir_id.len() {
482 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
485 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
487 if existing_hir_id == hir::DUMMY_HIR_ID {
488 // Generate a new HirId
489 let hir_id = alloc_hir_id(self);
490 self.node_id_to_hir_id[ast_node_id] = hir_id;
492 node_id: ast_node_id,
497 node_id: ast_node_id,
498 hir_id: existing_hir_id,
503 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
505 F: FnOnce(&mut Self) -> T,
507 let counter = self.item_local_id_counters
508 .insert(owner, HIR_ID_COUNTER_LOCKED)
510 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
511 self.current_hir_id_owner.push((def_index, counter));
513 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
515 debug_assert!(def_index == new_def_index);
516 debug_assert!(new_counter >= counter);
518 let prev = self.item_local_id_counters
519 .insert(owner, new_counter)
521 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
525 /// This method allocates a new HirId for the given NodeId and stores it in
526 /// the LoweringContext's NodeId => HirId map.
527 /// Take care not to call this method if the resulting HirId is then not
528 /// actually used in the HIR, as that would trigger an assertion in the
529 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
530 /// properly. Calling the method twice with the same NodeId is fine though.
531 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
532 self.lower_node_id_generic(ast_node_id, |this| {
533 let &mut (def_index, ref mut local_id_counter) =
534 this.current_hir_id_owner.last_mut().unwrap();
535 let local_id = *local_id_counter;
536 *local_id_counter += 1;
539 local_id: hir::ItemLocalId(local_id),
544 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
545 self.lower_node_id_generic(ast_node_id, |this| {
546 let local_id_counter = this
547 .item_local_id_counters
549 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
550 let local_id = *local_id_counter;
552 // We want to be sure not to modify the counter in the map while it
553 // is also on the stack. Otherwise we'll get lost updates when writing
554 // back from the stack to the map.
555 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
557 *local_id_counter += 1;
561 .opt_def_index(owner)
562 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
563 that do not belong to the current owner");
567 local_id: hir::ItemLocalId(local_id),
572 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
573 let body = hir::Body {
574 arguments: decl.map_or(hir_vec![], |decl| {
575 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
577 is_generator: self.is_generator,
581 self.bodies.insert(id, body);
585 fn next_id(&mut self) -> LoweredNodeId {
586 self.lower_node_id(self.sess.next_node_id())
589 fn expect_full_def(&mut self, id: NodeId) -> Def {
590 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
591 if pr.unresolved_segments() != 0 {
592 bug!("path not fully resolved: {:?}", pr);
598 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item=Def> {
599 self.resolver.get_import(id).present_items().map(|pr| {
600 if pr.unresolved_segments() != 0 {
601 bug!("path not fully resolved: {:?}", pr);
607 fn diagnostic(&self) -> &errors::Handler {
608 self.sess.diagnostic()
611 fn str_to_ident(&self, s: &'static str) -> Name {
615 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
616 let mark = Mark::fresh(Mark::root());
617 mark.set_expn_info(codemap::ExpnInfo {
619 callee: codemap::NameAndSpan {
620 format: codemap::CompilerDesugaring(reason),
622 allow_internal_unstable: true,
623 allow_internal_unsafe: false,
624 edition: codemap::hygiene::default_edition(),
627 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
630 fn with_anonymous_lifetime_mode<R>(
632 anonymous_lifetime_mode: AnonymousLifetimeMode,
633 op: impl FnOnce(&mut Self) -> R,
635 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
636 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
637 let result = op(self);
638 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
642 /// Creates a new hir::GenericParam for every new lifetime and
643 /// type parameter encountered while evaluating `f`. Definitions
644 /// are created with the parent provided. If no `parent_id` is
645 /// provided, no definitions will be returned.
647 /// Presuming that in-band lifetimes are enabled, then
648 /// `self.anonymous_lifetime_mode` will be updated to match the
649 /// argument while `f` is running (and restored afterwards).
650 fn collect_in_band_defs<T, F>(
653 anonymous_lifetime_mode: AnonymousLifetimeMode,
655 ) -> (Vec<hir::GenericParam>, T)
657 F: FnOnce(&mut LoweringContext) -> T,
659 assert!(!self.is_collecting_in_band_lifetimes);
660 assert!(self.lifetimes_to_define.is_empty());
661 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
663 self.is_collecting_in_band_lifetimes = self.sess.features_untracked().in_band_lifetimes;
664 if self.is_collecting_in_band_lifetimes {
665 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
668 assert!(self.in_band_ty_params.is_empty());
671 self.is_collecting_in_band_lifetimes = false;
672 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
674 let in_band_ty_params = self.in_band_ty_params.split_off(0);
675 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
677 let params = lifetimes_to_define
679 .map(|(span, hir_name)| {
680 let def_node_id = self.next_id().node_id;
682 // Get the name we'll use to make the def-path. Note
683 // that collisions are ok here and this shouldn't
684 // really show up for end-user.
685 let str_name = match hir_name {
686 hir::LifetimeName::Name(n) => n.as_str(),
687 hir::LifetimeName::Fresh(_) => keywords::UnderscoreLifetime.name().as_str(),
688 hir::LifetimeName::Implicit
689 | hir::LifetimeName::Underscore
690 | hir::LifetimeName::Static => {
691 span_bug!(span, "unexpected in-band lifetime name: {:?}", hir_name)
695 // Add a definition for the in-band lifetime def
696 self.resolver.definitions().create_def_with_parent(
699 DefPathData::LifetimeDef(str_name.as_interned_str()),
700 DefIndexAddressSpace::High,
708 pure_wrt_drop: false,
709 kind: hir::GenericParamKind::Lifetime {
711 bounds: vec![].into(),
713 lifetime_deprecated: hir::Lifetime {
721 .chain(in_band_ty_params.into_iter())
727 /// When there is a reference to some lifetime `'a`, and in-band
728 /// lifetimes are enabled, then we want to push that lifetime into
729 /// the vector of names to define later. In that case, it will get
730 /// added to the appropriate generics.
731 fn maybe_collect_in_band_lifetime(&mut self, span: Span, name: Name) {
732 if !self.is_collecting_in_band_lifetimes {
736 if self.in_scope_lifetimes.contains(&name) {
740 let hir_name = hir::LifetimeName::Name(name);
742 if self.lifetimes_to_define
744 .any(|(_, lt_name)| *lt_name == hir_name)
749 self.lifetimes_to_define.push((span, hir_name));
752 /// When we have either an elided or `'_` lifetime in an impl
753 /// header, we convert it to
754 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> hir::LifetimeName {
755 assert!(self.is_collecting_in_band_lifetimes);
756 let index = self.lifetimes_to_define.len();
757 let hir_name = hir::LifetimeName::Fresh(index);
758 self.lifetimes_to_define.push((span, hir_name));
762 // Evaluates `f` with the lifetimes in `params` in-scope.
763 // This is used to track which lifetimes have already been defined, and
764 // which are new in-band lifetimes that need to have a definition created
766 fn with_in_scope_lifetime_defs<'l, T, F>(
768 params: impl Iterator<Item = &'l GenericParamAST>,
772 F: FnOnce(&mut LoweringContext) -> T,
774 let old_len = self.in_scope_lifetimes.len();
775 let lt_def_names = params.map(|param| param.ident.name);
776 self.in_scope_lifetimes.extend(lt_def_names);
780 self.in_scope_lifetimes.truncate(old_len);
784 // Same as the method above, but accepts `hir::GenericParam`s
785 // instead of `ast::GenericParam`s.
786 // This should only be used with generics that have already had their
787 // in-band lifetimes added. In practice, this means that this function is
788 // only used when lowering a child item of a trait or impl.
789 fn with_parent_impl_lifetime_defs<T, F>(&mut self, params: &[hir::GenericParam], f: F) -> T
791 F: FnOnce(&mut LoweringContext) -> T,
793 let old_len = self.in_scope_lifetimes.len();
794 let lt_def_names = params.iter().map(|param| param.name());
795 self.in_scope_lifetimes.extend(lt_def_names);
799 self.in_scope_lifetimes.truncate(old_len);
803 /// Appends in-band lifetime defs and argument-position `impl
804 /// Trait` defs to the existing set of generics.
806 /// Presuming that in-band lifetimes are enabled, then
807 /// `self.anonymous_lifetime_mode` will be updated to match the
808 /// argument while `f` is running (and restored afterwards).
809 fn add_in_band_defs<F, T>(
813 anonymous_lifetime_mode: AnonymousLifetimeMode,
815 ) -> (hir::Generics, T)
817 F: FnOnce(&mut LoweringContext) -> T,
819 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
820 generics.params.iter().filter_map(|param| match param.kind {
821 GenericParamKindAST::Lifetime { .. } => Some(param),
825 let itctx = ImplTraitContext::Universal(parent_id);
826 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
827 (this.lower_generics(generics, itctx), f(this))
832 lowered_generics.params = lowered_generics
839 (lowered_generics, res)
842 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
844 F: FnOnce(&mut LoweringContext) -> T,
846 let len = self.catch_scopes.len();
847 self.catch_scopes.push(catch_id);
849 let result = f(self);
852 self.catch_scopes.len(),
853 "catch scopes should be added and removed in stack order"
856 self.catch_scopes.pop().unwrap();
861 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
863 F: FnOnce(&mut LoweringContext) -> hir::Expr,
865 let prev = mem::replace(&mut self.is_generator, false);
866 let result = f(self);
867 let r = self.record_body(result, decl);
868 self.is_generator = prev;
872 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
874 F: FnOnce(&mut LoweringContext) -> T,
876 // We're no longer in the base loop's condition; we're in another loop.
877 let was_in_loop_condition = self.is_in_loop_condition;
878 self.is_in_loop_condition = false;
880 let len = self.loop_scopes.len();
881 self.loop_scopes.push(loop_id);
883 let result = f(self);
886 self.loop_scopes.len(),
887 "Loop scopes should be added and removed in stack order"
890 self.loop_scopes.pop().unwrap();
892 self.is_in_loop_condition = was_in_loop_condition;
897 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
899 F: FnOnce(&mut LoweringContext) -> T,
901 let was_in_loop_condition = self.is_in_loop_condition;
902 self.is_in_loop_condition = true;
904 let result = f(self);
906 self.is_in_loop_condition = was_in_loop_condition;
911 fn with_new_scopes<T, F>(&mut self, f: F) -> T
913 F: FnOnce(&mut LoweringContext) -> T,
915 let was_in_loop_condition = self.is_in_loop_condition;
916 self.is_in_loop_condition = false;
918 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
919 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
920 let result = f(self);
921 self.catch_scopes = catch_scopes;
922 self.loop_scopes = loop_scopes;
924 self.is_in_loop_condition = was_in_loop_condition;
929 fn def_key(&mut self, id: DefId) -> DefKey {
931 self.resolver.definitions().def_key(id.index)
933 self.cstore.def_key(id)
937 fn lower_ident(&mut self, ident: Ident) -> Name {
938 let ident = ident.modern();
939 if ident.span.ctxt() == SyntaxContext::empty() {
944 .or_insert_with(|| Symbol::from_ident(ident))
947 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
948 label.map(|label| hir::Label {
949 name: label.ident.name,
950 span: label.ident.span,
954 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
956 Some((id, label)) => {
957 let target_id = if let Def::Label(loop_id) = self.expect_full_def(id) {
958 Ok(self.lower_node_id(loop_id).node_id)
960 Err(hir::LoopIdError::UnresolvedLabel)
963 label: self.lower_label(Some(label)),
968 let target_id = self.loop_scopes
970 .map(|innermost_loop_id| *innermost_loop_id)
971 .map(|id| Ok(self.lower_node_id(id).node_id))
972 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
983 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
986 .map(|a| self.lower_attr(a))
991 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
995 path: attr.path.clone(),
996 tokens: self.lower_token_stream(attr.tokens.clone()),
997 is_sugared_doc: attr.is_sugared_doc,
1002 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1005 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1009 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1011 TokenTree::Token(span, token) => self.lower_token(token, span),
1012 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1015 delim: delimited.delim,
1016 tts: self.lower_token_stream(delimited.tts.into()).into(),
1022 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1024 Token::Interpolated(_) => {}
1025 other => return TokenTree::Token(span, other).into(),
1028 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1029 self.lower_token_stream(tts)
1032 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1034 attrs: self.lower_attrs(&arm.attrs),
1035 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1036 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1037 body: P(self.lower_expr(&arm.body)),
1041 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1043 id: self.lower_node_id(b.id).node_id,
1044 name: self.lower_ident(b.ident),
1045 ty: self.lower_ty(&b.ty, itctx),
1050 fn lower_generic_arg(&mut self,
1051 p: &ast::GenericArgAST,
1052 itctx: ImplTraitContext)
1053 -> hir::GenericArg {
1055 ast::GenericArgAST::Lifetime(lt) => {
1056 GenericArg::Lifetime(self.lower_lifetime(<))
1058 ast::GenericArgAST::Type(ty) => {
1059 GenericArg::Type(self.lower_ty(&ty, itctx))
1064 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1065 let kind = match t.node {
1066 TyKind::Infer => hir::TyInfer,
1067 TyKind::Err => hir::TyErr,
1068 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty, itctx)),
1069 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt, itctx)),
1070 TyKind::Rptr(ref region, ref mt) => {
1071 let span = t.span.shrink_to_lo();
1072 let lifetime = match *region {
1073 Some(ref lt) => self.lower_lifetime(lt),
1074 None => self.elided_ref_lifetime(span),
1076 hir::TyRptr(lifetime, self.lower_mt(mt, itctx))
1078 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1079 f.generic_params.iter().filter_map(|param| match param.kind {
1080 GenericParamKindAST::Lifetime { .. } => Some(param),
1084 this.with_anonymous_lifetime_mode(
1085 AnonymousLifetimeMode::PassThrough,
1087 hir::TyBareFn(P(hir::BareFnTy {
1088 generic_params: this.lower_generic_params(
1091 ImplTraitContext::Disallowed,
1093 unsafety: this.lower_unsafety(f.unsafety),
1095 decl: this.lower_fn_decl(&f.decl, None, false),
1096 arg_names: this.lower_fn_args_to_names(&f.decl),
1102 TyKind::Never => hir::TyNever,
1103 TyKind::Tup(ref tys) => {
1104 hir::TyTup(tys.iter().map(|ty| self.lower_ty(ty, itctx)).collect())
1106 TyKind::Paren(ref ty) => {
1107 return self.lower_ty(ty, itctx);
1109 TyKind::Path(ref qself, ref path) => {
1110 let id = self.lower_node_id(t.id);
1111 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1112 let ty = self.ty_path(id, t.span, qpath);
1113 if let hir::TyTraitObject(..) = ty.node {
1114 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1118 TyKind::ImplicitSelf => hir::TyPath(hir::QPath::Resolved(
1121 def: self.expect_full_def(t.id),
1122 segments: hir_vec![hir::PathSegment::from_name(keywords::SelfType.name())],
1126 TyKind::Array(ref ty, ref length) => {
1127 hir::TyArray(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1129 TyKind::Typeof(ref expr) => {
1130 hir::TyTypeof(self.lower_anon_const(expr))
1132 TyKind::TraitObject(ref bounds, kind) => {
1133 let mut lifetime_bound = None;
1136 .filter_map(|bound| match *bound {
1137 TraitTyParamBound(ref ty, TraitBoundModifier::None) => {
1138 Some(self.lower_poly_trait_ref(ty, itctx))
1140 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
1141 RegionTyParamBound(ref lifetime) => {
1142 if lifetime_bound.is_none() {
1143 lifetime_bound = Some(self.lower_lifetime(lifetime));
1149 let lifetime_bound =
1150 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1151 if kind != TraitObjectSyntax::Dyn {
1152 self.maybe_lint_bare_trait(t.span, t.id, false);
1154 hir::TyTraitObject(bounds, lifetime_bound)
1156 TyKind::ImplTrait(ref bounds) => {
1159 ImplTraitContext::Existential(fn_def_id) => {
1161 // We need to manually repeat the code of `next_id` because the lowering
1162 // needs to happen while the owner_id is pointing to the item itself,
1163 // because items are their own owners
1164 let exist_ty_node_id = self.sess.next_node_id();
1166 // Make sure we know that some funky desugaring has been going on here.
1167 // This is a first: there is code in other places like for loop
1168 // desugaring that explicitly states that we don't want to track that.
1169 // Not tracking it makes lints in rustc and clippy very fragile as
1170 // frequently opened issues show.
1171 let exist_ty_span = self.allow_internal_unstable(
1172 CompilerDesugaringKind::ExistentialReturnType,
1176 // Pull a new definition from the ether
1177 let exist_ty_def_index = self
1180 .create_def_with_parent(
1183 DefPathData::ExistentialImplTrait,
1184 DefIndexAddressSpace::High,
1189 // the `t` is just for printing debug messages
1190 self.allocate_hir_id_counter(exist_ty_node_id, t);
1192 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1193 lctx.lower_bounds(bounds, itctx)
1196 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1202 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1203 let exist_ty_item_kind = hir::ItemExistential(hir::ExistTy {
1204 generics: hir::Generics {
1205 params: lifetime_defs,
1206 where_clause: hir::WhereClause {
1207 id: lctx.next_id().node_id,
1208 predicates: Vec::new().into(),
1213 impl_trait_fn: Some(fn_def_id),
1215 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1216 // Generate an `existential type Foo: Trait;` declaration
1217 trace!("creating existential type with id {:#?}", exist_ty_id);
1218 // Set the name to `impl Bound1 + Bound2`
1219 let exist_ty_name = Symbol::intern(&pprust::ty_to_string(t));
1221 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1222 let exist_ty_item = hir::Item {
1223 id: exist_ty_id.node_id,
1224 hir_id: exist_ty_id.hir_id,
1225 name: exist_ty_name,
1226 attrs: Default::default(),
1227 node: exist_ty_item_kind,
1228 vis: hir::Visibility::Inherited,
1229 span: exist_ty_span,
1232 // Insert the item into the global list. This usually happens
1233 // automatically for all AST items. But this existential type item
1234 // does not actually exist in the AST.
1235 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1237 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1238 hir::TyImplTraitExistential(
1240 id: exist_ty_id.node_id
1242 DefId::local(exist_ty_def_index),
1247 ImplTraitContext::Universal(def_id) => {
1248 let def_node_id = self.next_id().node_id;
1250 // Add a definition for the in-band TyParam
1251 let def_index = self.resolver.definitions().create_def_with_parent(
1254 DefPathData::UniversalImplTrait,
1255 DefIndexAddressSpace::High,
1260 let hir_bounds = self.lower_bounds(bounds, itctx);
1261 // Set the name to `impl Bound1 + Bound2`
1262 let name = Symbol::intern(&pprust::ty_to_string(t));
1263 self.in_band_ty_params.push(hir::GenericParam {
1266 pure_wrt_drop: false,
1267 kind: hir::GenericParamKind::Type {
1271 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1276 hir::TyPath(hir::QPath::Resolved(
1280 def: Def::TyParam(DefId::local(def_index)),
1281 segments: hir_vec![hir::PathSegment::from_name(name)],
1285 ImplTraitContext::Disallowed => {
1290 "`impl Trait` not allowed outside of function \
1291 and inherent method return types"
1297 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1300 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1309 fn lifetimes_from_impl_trait_bounds(
1311 exist_ty_id: NodeId,
1312 parent_index: DefIndex,
1313 bounds: &hir::TyParamBounds,
1314 ) -> (HirVec<hir::Lifetime>, HirVec<hir::GenericParam>) {
1315 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1316 // appear in the bounds, excluding lifetimes that are created within the bounds.
1317 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1318 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1319 context: &'r mut LoweringContext<'a>,
1321 exist_ty_id: NodeId,
1322 collect_elided_lifetimes: bool,
1323 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1324 already_defined_lifetimes: HashSet<hir::LifetimeName>,
1325 output_lifetimes: Vec<hir::Lifetime>,
1326 output_lifetime_params: Vec<hir::GenericParam>,
1329 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1330 fn nested_visit_map<'this>(
1332 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1333 hir::intravisit::NestedVisitorMap::None
1336 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1337 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1338 if parameters.parenthesized {
1339 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1340 self.collect_elided_lifetimes = false;
1341 hir::intravisit::walk_generic_args(self, span, parameters);
1342 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1344 hir::intravisit::walk_generic_args(self, span, parameters);
1348 fn visit_ty(&mut self, t: &'v hir::Ty) {
1349 // Don't collect elided lifetimes used inside of `fn()` syntax
1350 if let &hir::Ty_::TyBareFn(_) = &t.node {
1351 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1352 self.collect_elided_lifetimes = false;
1354 // Record the "stack height" of `for<'a>` lifetime bindings
1355 // to be able to later fully undo their introduction.
1356 let old_len = self.currently_bound_lifetimes.len();
1357 hir::intravisit::walk_ty(self, t);
1358 self.currently_bound_lifetimes.truncate(old_len);
1360 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1362 hir::intravisit::walk_ty(self, t);
1366 fn visit_poly_trait_ref(
1368 trait_ref: &'v hir::PolyTraitRef,
1369 modifier: hir::TraitBoundModifier,
1371 // Record the "stack height" of `for<'a>` lifetime bindings
1372 // to be able to later fully undo their introduction.
1373 let old_len = self.currently_bound_lifetimes.len();
1374 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1375 self.currently_bound_lifetimes.truncate(old_len);
1378 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1379 // Record the introduction of 'a in `for<'a> ...`
1380 if let hir::GenericParamKind::Lifetime { name, .. } = param.kind {
1381 // Introduce lifetimes one at a time so that we can handle
1382 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1383 self.currently_bound_lifetimes.push(name);
1386 hir::intravisit::walk_generic_param(self, param);
1389 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1390 let name = match lifetime.name {
1391 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1392 if self.collect_elided_lifetimes {
1393 // Use `'_` for both implicit and underscore lifetimes in
1394 // `abstract type Foo<'_>: SomeTrait<'_>;`
1395 hir::LifetimeName::Underscore
1400 name @ hir::LifetimeName::Fresh(_) => name,
1401 name @ hir::LifetimeName::Name(_) => name,
1402 hir::LifetimeName::Static => return,
1405 if !self.currently_bound_lifetimes.contains(&name)
1406 && !self.already_defined_lifetimes.contains(&name)
1408 self.already_defined_lifetimes.insert(name);
1410 self.output_lifetimes.push(hir::Lifetime {
1411 id: self.context.next_id().node_id,
1412 span: lifetime.span,
1416 // We need to manually create the ids here, because the
1417 // definitions will go into the explicit `existential type`
1418 // declaration and thus need to have their owner set to that item
1419 let def_node_id = self.context.sess.next_node_id();
1420 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1421 self.context.resolver.definitions().create_def_with_parent(
1424 DefPathData::LifetimeDef(name.name().as_interned_str()),
1425 DefIndexAddressSpace::High,
1430 self.output_lifetime_params.push(hir::GenericParam {
1432 span: lifetime.span,
1433 pure_wrt_drop: false,
1434 kind: hir::GenericParamKind::Lifetime {
1436 bounds: vec![].into(),
1438 lifetime_deprecated: hir::Lifetime {
1440 span: lifetime.span,
1449 let mut lifetime_collector = ImplTraitLifetimeCollector {
1451 parent: parent_index,
1453 collect_elided_lifetimes: true,
1454 currently_bound_lifetimes: Vec::new(),
1455 already_defined_lifetimes: HashSet::new(),
1456 output_lifetimes: Vec::new(),
1457 output_lifetime_params: Vec::new(),
1460 for bound in bounds {
1461 hir::intravisit::walk_ty_param_bound(&mut lifetime_collector, &bound);
1465 lifetime_collector.output_lifetimes.into(),
1466 lifetime_collector.output_lifetime_params.into(),
1470 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1475 .map(|x| self.lower_foreign_item(x))
1480 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1487 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1489 node: hir::Variant_ {
1490 name: v.node.ident.name,
1491 attrs: self.lower_attrs(&v.node.attrs),
1492 data: self.lower_variant_data(&v.node.data),
1493 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1502 qself: &Option<QSelf>,
1504 param_mode: ParamMode,
1505 itctx: ImplTraitContext,
1507 let qself_position = qself.as_ref().map(|q| q.position);
1508 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx));
1510 let resolution = self.resolver
1512 .unwrap_or(PathResolution::new(Def::Err));
1514 let proj_start = p.segments.len() - resolution.unresolved_segments();
1515 let path = P(hir::Path {
1516 def: resolution.base_def(),
1517 segments: p.segments[..proj_start]
1520 .map(|(i, segment)| {
1521 let param_mode = match (qself_position, param_mode) {
1522 (Some(j), ParamMode::Optional) if i < j => {
1523 // This segment is part of the trait path in a
1524 // qualified path - one of `a`, `b` or `Trait`
1525 // in `<X as a::b::Trait>::T::U::method`.
1531 // Figure out if this is a type/trait segment,
1532 // which may need lifetime elision performed.
1533 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1534 krate: def_id.krate,
1535 index: this.def_key(def_id).parent.expect("missing parent"),
1537 let type_def_id = match resolution.base_def() {
1538 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1539 Some(parent_def_id(self, def_id))
1541 Def::Variant(def_id) if i + 1 == proj_start => {
1542 Some(parent_def_id(self, def_id))
1545 | Def::Union(def_id)
1547 | Def::TyAlias(def_id)
1548 | Def::Trait(def_id) if i + 1 == proj_start =>
1554 let parenthesized_generic_args = match resolution.base_def() {
1555 // `a::b::Trait(Args)`
1556 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1557 // `a::b::Trait(Args)::TraitItem`
1558 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1559 if i + 2 == proj_start =>
1561 ParenthesizedGenericArgs::Ok
1563 // Avoid duplicated errors
1564 Def::Err => ParenthesizedGenericArgs::Ok,
1570 | Def::Variant(..) if i + 1 == proj_start =>
1572 ParenthesizedGenericArgs::Err
1574 // A warning for now, for compatibility reasons
1575 _ => ParenthesizedGenericArgs::Warn,
1578 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1579 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1582 assert!(!def_id.is_local());
1584 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1585 let n = item_generics.own_counts().lifetimes;
1586 self.type_def_lifetime_params.insert(def_id, n);
1589 self.lower_path_segment(
1594 parenthesized_generic_args,
1602 // Simple case, either no projections, or only fully-qualified.
1603 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1604 if resolution.unresolved_segments() == 0 {
1605 return hir::QPath::Resolved(qself, path);
1608 // Create the innermost type that we're projecting from.
1609 let mut ty = if path.segments.is_empty() {
1610 // If the base path is empty that means there exists a
1611 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1612 qself.expect("missing QSelf for <T>::...")
1614 // Otherwise, the base path is an implicit `Self` type path,
1615 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1616 // `<I as Iterator>::Item::default`.
1617 let new_id = self.next_id();
1618 self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))
1621 // Anything after the base path are associated "extensions",
1622 // out of which all but the last one are associated types,
1623 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1624 // * base path is `std::vec::Vec<T>`
1625 // * "extensions" are `IntoIter`, `Item` and `clone`
1626 // * type nodes are:
1627 // 1. `std::vec::Vec<T>` (created above)
1628 // 2. `<std::vec::Vec<T>>::IntoIter`
1629 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1630 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1631 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1632 let segment = P(self.lower_path_segment(
1637 ParenthesizedGenericArgs::Warn,
1640 let qpath = hir::QPath::TypeRelative(ty, segment);
1642 // It's finished, return the extension of the right node type.
1643 if i == p.segments.len() - 1 {
1647 // Wrap the associated extension in another type node.
1648 let new_id = self.next_id();
1649 ty = self.ty_path(new_id, p.span, qpath);
1652 // Should've returned in the for loop above.
1655 "lower_qpath: no final extension segment in {}..{}",
1661 fn lower_path_extra(
1666 param_mode: ParamMode,
1670 segments: p.segments
1673 self.lower_path_segment(
1678 ParenthesizedGenericArgs::Err,
1679 ImplTraitContext::Disallowed,
1682 .chain(name.map(|name| hir::PathSegment::from_name(name)))
1688 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1689 let def = self.expect_full_def(id);
1690 self.lower_path_extra(def, p, None, param_mode)
1693 fn lower_path_segment(
1696 segment: &PathSegment,
1697 param_mode: ParamMode,
1698 expected_lifetimes: usize,
1699 parenthesized_generic_args: ParenthesizedGenericArgs,
1700 itctx: ImplTraitContext,
1701 ) -> hir::PathSegment {
1702 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1703 let msg = "parenthesized parameters may only be used with a trait";
1704 match **generic_args {
1705 GenericArgs::AngleBracketed(ref data) => {
1706 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1708 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1709 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1710 ParenthesizedGenericArgs::Warn => {
1711 self.sess.buffer_lint(
1712 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1717 (hir::GenericArgs::none(), true)
1719 ParenthesizedGenericArgs::Err => {
1720 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1721 .span_label(data.span, "only traits may use parentheses")
1723 (hir::GenericArgs::none(), true)
1728 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1731 if !generic_args.parenthesized && generic_args.lifetimes().count() == 0 {
1733 self.elided_path_lifetimes(path_span, expected_lifetimes)
1735 .map(|lt| GenericArg::Lifetime(lt))
1736 .chain(generic_args.args.into_iter())
1740 hir::PathSegment::new(
1741 self.lower_ident(segment.ident),
1747 fn lower_angle_bracketed_parameter_data(
1749 data: &AngleBracketedArgs,
1750 param_mode: ParamMode,
1751 itctx: ImplTraitContext,
1752 ) -> (hir::GenericArgs, bool) {
1753 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1755 args: args.iter().map(|a| self.lower_generic_arg(a, itctx)).collect(),
1756 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(),
1757 parenthesized: false,
1759 data.types().count() == 0 && param_mode == ParamMode::Optional)
1762 fn lower_parenthesized_parameter_data(
1764 data: &ParenthesizedParameterData,
1765 ) -> (hir::PathParameters, bool) {
1766 // Switch to `PassThrough` mode for anonymous lifetimes: this
1767 // means that we permit things like `&Ref<T>`, where `Ref` has
1768 // a hidden lifetime parameter. This is needed for backwards
1769 // compatibility, even in contexts like an impl header where
1770 // we generally don't permit such things (see #51008).
1771 self.with_anonymous_lifetime_mode(
1772 AnonymousLifetimeMode::PassThrough,
1774 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1775 let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
1776 let inputs = inputs.iter().map(|ty| this.lower_ty(ty, DISALLOWED)).collect();
1777 let mk_tup = |this: &mut Self, tys, span| {
1778 let LoweredNodeId { node_id, hir_id } = this.next_id();
1779 P(hir::Ty { node: hir::TyTup(tys), id: node_id, hir_id, span })
1784 parameters: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1787 id: this.next_id().node_id,
1788 name: Symbol::intern(FN_OUTPUT_NAME),
1791 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1792 .unwrap_or_else(|| mk_tup(this, hir::HirVec::new(), span)),
1793 span: output.as_ref().map_or(span, |ty| ty.span),
1796 parenthesized: true,
1804 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1805 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1811 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1812 pat: self.lower_pat(&l.pat),
1813 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1815 attrs: l.attrs.clone(),
1816 source: hir::LocalSource::Normal,
1820 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1822 Mutability::Mutable => hir::MutMutable,
1823 Mutability::Immutable => hir::MutImmutable,
1827 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1828 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1832 pat: self.lower_pat(&arg.pat),
1836 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Spanned<Name>> {
1839 .map(|arg| match arg.pat.node {
1840 PatKind::Ident(_, ident, None) => respan(ident.span, ident.name),
1841 _ => respan(arg.pat.span, keywords::Invalid.name()),
1849 fn_def_id: Option<DefId>,
1850 impl_trait_return_allow: bool,
1851 ) -> P<hir::FnDecl> {
1852 // NOTE: The two last parameters here have to do with impl Trait. If fn_def_id is Some,
1853 // then impl Trait arguments are lowered into generic parameters on the given
1854 // fn_def_id, otherwise impl Trait is disallowed. (for now)
1856 // Furthermore, if impl_trait_return_allow is true, then impl Trait may be used in
1857 // return positions as well. This guards against trait declarations and their impls
1858 // where impl Trait is disallowed. (again for now)
1863 if let Some(def_id) = fn_def_id {
1864 self.lower_ty(&arg.ty, ImplTraitContext::Universal(def_id))
1866 self.lower_ty(&arg.ty, ImplTraitContext::Disallowed)
1870 output: match decl.output {
1871 FunctionRetTy::Ty(ref ty) => match fn_def_id {
1872 Some(def_id) if impl_trait_return_allow => {
1873 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1875 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1877 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1879 variadic: decl.variadic,
1880 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1881 TyKind::ImplicitSelf => true,
1882 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1888 fn lower_ty_param_bound(
1891 itctx: ImplTraitContext,
1892 ) -> hir::TyParamBound {
1894 TraitTyParamBound(ref ty, modifier) => hir::TraitTyParamBound(
1895 self.lower_poly_trait_ref(ty, itctx),
1896 self.lower_trait_bound_modifier(modifier),
1898 RegionTyParamBound(ref lifetime) => {
1899 hir::RegionTyParamBound(self.lower_lifetime(lifetime))
1904 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1905 let span = l.ident.span;
1906 match self.lower_ident(l.ident) {
1907 x if x == "'static" => self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
1908 x if x == "'_" => match self.anonymous_lifetime_mode {
1909 AnonymousLifetimeMode::CreateParameter => {
1910 let fresh_name = self.collect_fresh_in_band_lifetime(span);
1911 self.new_named_lifetime(l.id, span, fresh_name)
1914 AnonymousLifetimeMode::PassThrough => {
1915 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
1919 self.maybe_collect_in_band_lifetime(span, name);
1920 self.new_named_lifetime(l.id, span, hir::LifetimeName::Name(name))
1925 fn new_named_lifetime(
1929 name: hir::LifetimeName,
1930 ) -> hir::Lifetime {
1932 id: self.lower_node_id(id).node_id,
1938 fn lower_generic_param(&mut self,
1939 param: &GenericParamAST,
1940 add_bounds: &NodeMap<Vec<TyParamBound>>,
1941 itctx: ImplTraitContext)
1942 -> hir::GenericParam {
1944 GenericParamKindAST::Lifetime { ref bounds, ref lifetime, .. } => {
1945 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
1946 self.is_collecting_in_band_lifetimes = false;
1948 let lifetime = self.lower_lifetime(lifetime);
1949 let param = hir::GenericParam {
1951 span: lifetime.span,
1952 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
1953 kind: hir::GenericParamKind::Lifetime {
1954 name: lifetime.name,
1955 bounds: bounds.iter().map(|lt| self.lower_lifetime(lt)).collect(),
1957 lifetime_deprecated: lifetime,
1961 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
1965 GenericParamKindAST::Type { ref bounds, ref default } => {
1966 let mut name = self.lower_ident(param.ident);
1968 // Don't expose `Self` (recovered "keyword used as ident" parse error).
1969 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
1970 // Instead, use gensym("Self") to create a distinct name that looks the same.
1971 if name == keywords::SelfType.name() {
1972 name = Symbol::gensym("Self");
1975 let mut bounds = self.lower_bounds(bounds, itctx);
1976 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
1977 if !add_bounds.is_empty() {
1980 .chain(self.lower_bounds(add_bounds, itctx).into_iter())
1985 id: self.lower_node_id(param.id).node_id,
1986 span: param.ident.span,
1987 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
1988 kind: hir::GenericParamKind::Type {
1991 default: default.as_ref().map(|x| {
1992 self.lower_ty(x, ImplTraitContext::Disallowed)
1994 synthetic: param.attrs.iter()
1995 .filter(|attr| attr.check_name("rustc_synthetic"))
1996 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
1998 attrs: self.lower_attrs(¶m.attrs),
2005 fn lower_generic_params(
2007 params: &Vec<GenericParamAST>,
2008 add_bounds: &NodeMap<Vec<TyParamBound>>,
2009 itctx: ImplTraitContext,
2010 ) -> hir::HirVec<hir::GenericParam> {
2011 params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect()
2016 generics: &Generics,
2017 itctx: ImplTraitContext)
2020 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2021 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2022 // paths where report_error is called are also the only paths that advance to after
2023 // the match statement, so the error reporting could probably just be moved there.
2024 let mut add_bounds = NodeMap();
2025 for pred in &generics.where_clause.predicates {
2026 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2027 'next_bound: for bound in &bound_pred.bounds {
2028 if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
2029 let report_error = |this: &mut Self| {
2030 this.diagnostic().span_err(
2031 bound_pred.bounded_ty.span,
2032 "`?Trait` bounds are only permitted at the \
2033 point where a type parameter is declared",
2036 // Check if the where clause type is a plain type parameter.
2037 match bound_pred.bounded_ty.node {
2038 TyKind::Path(None, ref path)
2039 if path.segments.len() == 1
2040 && bound_pred.bound_generic_params.is_empty() =>
2042 if let Some(Def::TyParam(def_id)) = self.resolver
2043 .get_resolution(bound_pred.bounded_ty.id)
2044 .map(|d| d.base_def())
2046 if let Some(node_id) =
2047 self.resolver.definitions().as_local_node_id(def_id)
2049 for param in &generics.params {
2051 GenericParamKindAST::Type { .. } => {
2052 if node_id == param.id {
2053 add_bounds.entry(param.id)
2054 .or_insert(Vec::new())
2055 .push(bound.clone());
2056 continue 'next_bound;
2066 _ => report_error(self),
2074 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2075 where_clause: self.lower_where_clause(&generics.where_clause),
2076 span: generics.span,
2080 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2082 id: self.lower_node_id(wc.id).node_id,
2083 predicates: wc.predicates
2085 .map(|predicate| self.lower_where_predicate(predicate))
2090 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2092 WherePredicate::BoundPredicate(WhereBoundPredicate {
2093 ref bound_generic_params,
2098 self.with_in_scope_lifetime_defs(
2099 bound_generic_params.iter().filter_map(|param| match param.kind {
2100 GenericParamKindAST::Lifetime { .. } => Some(param),
2104 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2105 bound_generic_params: this.lower_generic_params(
2106 bound_generic_params,
2108 ImplTraitContext::Disallowed,
2110 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2113 .filter_map(|bound| match *bound {
2114 // Ignore `?Trait` bounds.
2115 // Tthey were copied into type parameters already.
2116 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
2117 _ => Some(this.lower_ty_param_bound(
2119 ImplTraitContext::Disallowed,
2128 WherePredicate::RegionPredicate(WhereRegionPredicate {
2132 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2134 lifetime: self.lower_lifetime(lifetime),
2137 .map(|bound| self.lower_lifetime(bound))
2140 WherePredicate::EqPredicate(WhereEqPredicate {
2145 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2146 id: self.lower_node_id(id).node_id,
2147 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2148 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2154 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2156 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2160 .map(|f| self.lower_struct_field(f))
2162 self.lower_node_id(id).node_id,
2164 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2168 .map(|f| self.lower_struct_field(f))
2170 self.lower_node_id(id).node_id,
2172 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2176 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2177 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2178 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2179 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2183 ref_id: self.lower_node_id(p.ref_id).node_id,
2187 fn lower_poly_trait_ref(
2190 itctx: ImplTraitContext,
2191 ) -> hir::PolyTraitRef {
2192 let bound_generic_params =
2193 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx);
2194 let trait_ref = self.with_parent_impl_lifetime_defs(
2195 &bound_generic_params
2197 .filter_map(|param| match param.kind {
2198 hir::GenericParamKind::Lifetime { .. } => Some(param.clone()),
2201 .collect::<Vec<_>>(),
2202 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2206 bound_generic_params,
2212 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2215 id: self.lower_node_id(f.id).node_id,
2216 ident: match f.ident {
2217 Some(ident) => ident,
2218 // FIXME(jseyfried) positional field hygiene
2219 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2221 vis: self.lower_visibility(&f.vis, None),
2222 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2223 attrs: self.lower_attrs(&f.attrs),
2227 fn lower_field(&mut self, f: &Field) -> hir::Field {
2229 id: self.next_id().node_id,
2231 expr: P(self.lower_expr(&f.expr)),
2233 is_shorthand: f.is_shorthand,
2237 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2239 ty: self.lower_ty(&mt.ty, itctx),
2240 mutbl: self.lower_mutability(mt.mutbl),
2246 bounds: &[TyParamBound],
2247 itctx: ImplTraitContext,
2248 ) -> hir::TyParamBounds {
2251 .map(|bound| self.lower_ty_param_bound(bound, itctx))
2255 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2256 let mut expr = None;
2258 let mut stmts = vec![];
2260 for (index, stmt) in b.stmts.iter().enumerate() {
2261 if index == b.stmts.len() - 1 {
2262 if let StmtKind::Expr(ref e) = stmt.node {
2263 expr = Some(P(self.lower_expr(e)));
2265 stmts.extend(self.lower_stmt(stmt));
2268 stmts.extend(self.lower_stmt(stmt));
2272 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2277 stmts: stmts.into(),
2279 rules: self.lower_block_check_mode(&b.rules),
2282 recovered: b.recovered,
2290 attrs: &hir::HirVec<Attribute>,
2291 vis: &mut hir::Visibility,
2295 ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2296 ItemKind::Use(ref use_tree) => {
2297 // Start with an empty prefix
2300 span: use_tree.span,
2303 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2305 ItemKind::Static(ref t, m, ref e) => {
2306 let value = self.lower_body(None, |this| this.lower_expr(e));
2308 self.lower_ty(t, ImplTraitContext::Disallowed),
2309 self.lower_mutability(m),
2313 ItemKind::Const(ref t, ref e) => {
2314 let value = self.lower_body(None, |this| this.lower_expr(e));
2315 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2317 ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
2318 let fn_def_id = self.resolver.definitions().local_def_id(id);
2319 self.with_new_scopes(|this| {
2320 let body_id = this.lower_body(Some(decl), |this| {
2321 let body = this.lower_block(body, false);
2322 this.expr_block(body, ThinVec::new())
2324 let (generics, fn_decl) = this.add_in_band_defs(
2327 AnonymousLifetimeMode::PassThrough,
2328 |this| this.lower_fn_decl(decl, Some(fn_def_id), true),
2333 this.lower_unsafety(unsafety),
2334 this.lower_constness(constness),
2341 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2342 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2343 ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2344 ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2345 self.lower_ty(t, ImplTraitContext::Disallowed),
2346 self.lower_generics(generics, ImplTraitContext::Disallowed),
2348 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2350 variants: enum_definition
2353 .map(|x| self.lower_variant(x))
2356 self.lower_generics(generics, ImplTraitContext::Disallowed),
2358 ItemKind::Struct(ref struct_def, ref generics) => {
2359 let struct_def = self.lower_variant_data(struct_def);
2362 self.lower_generics(generics, ImplTraitContext::Disallowed),
2365 ItemKind::Union(ref vdata, ref generics) => {
2366 let vdata = self.lower_variant_data(vdata);
2369 self.lower_generics(generics, ImplTraitContext::Disallowed),
2381 let def_id = self.resolver.definitions().local_def_id(id);
2383 // Lower the "impl header" first. This ordering is important
2384 // for in-band lifetimes! Consider `'a` here:
2386 // impl Foo<'a> for u32 {
2387 // fn method(&'a self) { .. }
2390 // Because we start by lowering the `Foo<'a> for u32`
2391 // part, we will add `'a` to the list of generics on
2392 // the impl. When we then encounter it later in the
2393 // method, it will not be considered an in-band
2394 // lifetime to be added, but rather a reference to a
2396 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2399 AnonymousLifetimeMode::CreateParameter,
2401 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2402 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2405 if let Some(ref trait_ref) = trait_ref {
2406 if let Def::Trait(def_id) = trait_ref.path.def {
2407 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2411 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2413 (trait_ref, lowered_ty)
2417 let new_impl_items = self.with_in_scope_lifetime_defs(
2418 ast_generics.params.iter().filter_map(|param| match param.kind {
2419 GenericParamKindAST::Lifetime { .. } => Some(param),
2425 .map(|item| this.lower_impl_item_ref(item))
2431 self.lower_unsafety(unsafety),
2432 self.lower_impl_polarity(polarity),
2433 self.lower_defaultness(defaultness, true /* [1] */),
2440 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2441 let bounds = self.lower_bounds(bounds, ImplTraitContext::Disallowed);
2444 .map(|item| self.lower_trait_item_ref(item))
2447 self.lower_is_auto(is_auto),
2448 self.lower_unsafety(unsafety),
2449 self.lower_generics(generics, ImplTraitContext::Disallowed),
2454 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2455 self.lower_generics(generics, ImplTraitContext::Disallowed),
2456 self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2458 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2461 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2462 // not cause an assertion failure inside the `lower_defaultness` function
2470 vis: &mut hir::Visibility,
2472 attrs: &hir::HirVec<Attribute>,
2474 let path = &tree.prefix;
2477 UseTreeKind::Simple(rename, id1, id2) => {
2478 *name = tree.ident().name;
2480 // First apply the prefix to the path
2481 let mut path = Path {
2485 .chain(path.segments.iter())
2491 // Correctly resolve `self` imports
2492 if path.segments.len() > 1
2493 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2495 let _ = path.segments.pop();
2496 if rename.is_none() {
2497 *name = path.segments.last().unwrap().ident.name;
2501 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2502 let mut defs = self.expect_full_def_from_use(id);
2503 // we want to return *something* from this function, so hang onto the first item
2505 let mut ret_def = defs.next().unwrap_or(Def::Err);
2507 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2508 let vis = vis.clone();
2509 let name = name.clone();
2510 let span = path.span;
2511 self.resolver.definitions().create_def_with_parent(
2515 DefIndexAddressSpace::High,
2518 self.allocate_hir_id_counter(new_node_id, &path);
2520 self.with_hir_id_owner(new_node_id, |this| {
2521 let new_id = this.lower_node_id(new_node_id);
2522 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2523 let item = hir::ItemUse(P(path), hir::UseKind::Single);
2524 let vis = match vis {
2525 hir::Visibility::Public => hir::Visibility::Public,
2526 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2527 hir::Visibility::Inherited => hir::Visibility::Inherited,
2528 hir::Visibility::Restricted { ref path, id: _ } => {
2529 hir::Visibility::Restricted {
2531 // We are allocating a new NodeId here
2532 id: this.next_id().node_id,
2541 hir_id: new_id.hir_id,
2543 attrs: attrs.clone(),
2552 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2553 hir::ItemUse(path, hir::UseKind::Single)
2555 UseTreeKind::Glob => {
2556 let path = P(self.lower_path(
2562 .chain(path.segments.iter())
2567 ParamMode::Explicit,
2569 hir::ItemUse(path, hir::UseKind::Glob)
2571 UseTreeKind::Nested(ref trees) => {
2576 .chain(path.segments.iter())
2579 span: prefix.span.to(path.span),
2582 // Add all the nested PathListItems in the HIR
2583 for &(ref use_tree, id) in trees {
2584 self.allocate_hir_id_counter(id, &use_tree);
2588 } = self.lower_node_id(id);
2590 let mut vis = vis.clone();
2591 let mut name = name.clone();
2593 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2595 self.with_hir_id_owner(new_id, |this| {
2596 let vis = match vis {
2597 hir::Visibility::Public => hir::Visibility::Public,
2598 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2599 hir::Visibility::Inherited => hir::Visibility::Inherited,
2600 hir::Visibility::Restricted { ref path, id: _ } => {
2601 hir::Visibility::Restricted {
2603 // We are allocating a new NodeId here
2604 id: this.next_id().node_id,
2615 attrs: attrs.clone(),
2618 span: use_tree.span,
2624 // Privatize the degenerate import base, used only to check
2625 // the stability of `use a::{};`, to avoid it showing up as
2626 // a re-export by accident when `pub`, e.g. in documentation.
2627 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2628 *vis = hir::Inherited;
2629 hir::ItemUse(path, hir::UseKind::ListStem)
2634 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2635 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2636 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2638 let (generics, node) = match i.node {
2639 TraitItemKind::Const(ref ty, ref default) => (
2640 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2641 hir::TraitItemKind::Const(
2642 self.lower_ty(ty, ImplTraitContext::Disallowed),
2645 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2648 TraitItemKind::Method(ref sig, None) => {
2649 let names = self.lower_fn_args_to_names(&sig.decl);
2650 self.add_in_band_defs(
2653 AnonymousLifetimeMode::PassThrough,
2655 hir::TraitItemKind::Method(
2656 this.lower_method_sig(sig, trait_item_def_id, false),
2657 hir::TraitMethod::Required(names),
2662 TraitItemKind::Method(ref sig, Some(ref body)) => {
2663 let body_id = self.lower_body(Some(&sig.decl), |this| {
2664 let body = this.lower_block(body, false);
2665 this.expr_block(body, ThinVec::new())
2668 self.add_in_band_defs(
2671 AnonymousLifetimeMode::PassThrough,
2673 hir::TraitItemKind::Method(
2674 this.lower_method_sig(sig, trait_item_def_id, false),
2675 hir::TraitMethod::Provided(body_id),
2680 TraitItemKind::Type(ref bounds, ref default) => (
2681 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2682 hir::TraitItemKind::Type(
2683 self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2686 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2689 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2695 name: self.lower_ident(i.ident),
2696 attrs: self.lower_attrs(&i.attrs),
2703 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2704 let (kind, has_default) = match i.node {
2705 TraitItemKind::Const(_, ref default) => {
2706 (hir::AssociatedItemKind::Const, default.is_some())
2708 TraitItemKind::Type(_, ref default) => {
2709 (hir::AssociatedItemKind::Type, default.is_some())
2711 TraitItemKind::Method(ref sig, ref default) => (
2712 hir::AssociatedItemKind::Method {
2713 has_self: sig.decl.has_self(),
2717 TraitItemKind::Macro(..) => unimplemented!(),
2720 id: hir::TraitItemId { node_id: i.id },
2721 name: self.lower_ident(i.ident),
2723 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
2728 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
2729 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2730 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
2732 let (generics, node) = match i.node {
2733 ImplItemKind::Const(ref ty, ref expr) => {
2734 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
2736 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2737 hir::ImplItemKind::Const(
2738 self.lower_ty(ty, ImplTraitContext::Disallowed),
2743 ImplItemKind::Method(ref sig, ref body) => {
2744 let body_id = self.lower_body(Some(&sig.decl), |this| {
2745 let body = this.lower_block(body, false);
2746 this.expr_block(body, ThinVec::new())
2748 let impl_trait_return_allow = !self.is_in_trait_impl;
2750 self.add_in_band_defs(
2753 AnonymousLifetimeMode::PassThrough,
2755 hir::ImplItemKind::Method(
2756 this.lower_method_sig(
2759 impl_trait_return_allow,
2766 ImplItemKind::Type(ref ty) => (
2767 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2768 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
2770 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2776 name: self.lower_ident(i.ident),
2777 attrs: self.lower_attrs(&i.attrs),
2779 vis: self.lower_visibility(&i.vis, None),
2780 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2785 // [1] since `default impl` is not yet implemented, this is always true in impls
2788 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
2790 id: hir::ImplItemId { node_id: i.id },
2791 name: self.lower_ident(i.ident),
2793 vis: self.lower_visibility(&i.vis, Some(i.id)),
2794 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2795 kind: match i.node {
2796 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
2797 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
2798 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
2799 has_self: sig.decl.has_self(),
2801 ImplItemKind::Macro(..) => unimplemented!(),
2805 // [1] since `default impl` is not yet implemented, this is always true in impls
2808 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
2811 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
2815 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
2817 ItemKind::Use(ref use_tree) => {
2818 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
2819 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
2822 ItemKind::MacroDef(..) => return SmallVector::new(),
2825 SmallVector::one(hir::ItemId { id: i.id })
2828 fn lower_item_id_use_tree(&mut self,
2831 vec: &mut SmallVector<hir::ItemId>)
2834 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
2835 vec.push(hir::ItemId { id });
2836 self.lower_item_id_use_tree(nested, id, vec);
2838 UseTreeKind::Glob => {}
2839 UseTreeKind::Simple(_, id1, id2) => {
2840 for (_, &id) in self.expect_full_def_from_use(base_id)
2842 .zip([id1, id2].iter())
2844 vec.push(hir::ItemId { id });
2850 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
2851 let mut name = i.ident.name;
2852 let mut vis = self.lower_visibility(&i.vis, None);
2853 let attrs = self.lower_attrs(&i.attrs);
2854 if let ItemKind::MacroDef(ref def) = i.node {
2855 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
2856 let body = self.lower_token_stream(def.stream());
2857 self.exported_macros.push(hir::MacroDef {
2870 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
2872 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2885 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
2886 let node_id = self.lower_node_id(i.id).node_id;
2887 let def_id = self.resolver.definitions().local_def_id(node_id);
2891 attrs: self.lower_attrs(&i.attrs),
2892 node: match i.node {
2893 ForeignItemKind::Fn(ref fdec, ref generics) => {
2894 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
2897 AnonymousLifetimeMode::PassThrough,
2900 // Disallow impl Trait in foreign items
2901 this.lower_fn_decl(fdec, None, false),
2902 this.lower_fn_args_to_names(fdec),
2907 hir::ForeignItemFn(fn_dec, fn_args, generics)
2909 ForeignItemKind::Static(ref t, m) => {
2910 hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
2912 ForeignItemKind::Ty => hir::ForeignItemType,
2913 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
2915 vis: self.lower_visibility(&i.vis, None),
2920 fn lower_method_sig(
2924 impl_trait_return_allow: bool,
2925 ) -> hir::MethodSig {
2928 unsafety: self.lower_unsafety(sig.unsafety),
2929 constness: self.lower_constness(sig.constness),
2930 decl: self.lower_fn_decl(&sig.decl, Some(fn_def_id), impl_trait_return_allow),
2934 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
2936 IsAuto::Yes => hir::IsAuto::Yes,
2937 IsAuto::No => hir::IsAuto::No,
2941 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
2943 Unsafety::Unsafe => hir::Unsafety::Unsafe,
2944 Unsafety::Normal => hir::Unsafety::Normal,
2948 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
2950 Constness::Const => hir::Constness::Const,
2951 Constness::NotConst => hir::Constness::NotConst,
2955 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
2957 UnOp::Deref => hir::UnDeref,
2958 UnOp::Not => hir::UnNot,
2959 UnOp::Neg => hir::UnNeg,
2963 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
2965 node: match b.node {
2966 BinOpKind::Add => hir::BiAdd,
2967 BinOpKind::Sub => hir::BiSub,
2968 BinOpKind::Mul => hir::BiMul,
2969 BinOpKind::Div => hir::BiDiv,
2970 BinOpKind::Rem => hir::BiRem,
2971 BinOpKind::And => hir::BiAnd,
2972 BinOpKind::Or => hir::BiOr,
2973 BinOpKind::BitXor => hir::BiBitXor,
2974 BinOpKind::BitAnd => hir::BiBitAnd,
2975 BinOpKind::BitOr => hir::BiBitOr,
2976 BinOpKind::Shl => hir::BiShl,
2977 BinOpKind::Shr => hir::BiShr,
2978 BinOpKind::Eq => hir::BiEq,
2979 BinOpKind::Lt => hir::BiLt,
2980 BinOpKind::Le => hir::BiLe,
2981 BinOpKind::Ne => hir::BiNe,
2982 BinOpKind::Ge => hir::BiGe,
2983 BinOpKind::Gt => hir::BiGt,
2989 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2990 let node = match p.node {
2991 PatKind::Wild => hir::PatKind::Wild,
2992 PatKind::Ident(ref binding_mode, ident, ref sub) => {
2993 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
2994 // `None` can occur in body-less function signatures
2995 def @ None | def @ Some(Def::Local(_)) => {
2996 let canonical_id = match def {
2997 Some(Def::Local(id)) => id,
3000 hir::PatKind::Binding(
3001 self.lower_binding_mode(binding_mode),
3003 respan(ident.span, ident.name),
3004 sub.as_ref().map(|x| self.lower_pat(x)),
3007 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3012 segments: hir_vec![hir::PathSegment::from_name(ident.name)],
3017 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3018 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3019 let qpath = self.lower_qpath(
3023 ParamMode::Optional,
3024 ImplTraitContext::Disallowed,
3026 hir::PatKind::TupleStruct(
3028 pats.iter().map(|x| self.lower_pat(x)).collect(),
3032 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3036 ParamMode::Optional,
3037 ImplTraitContext::Disallowed,
3039 PatKind::Struct(ref path, ref fields, etc) => {
3040 let qpath = self.lower_qpath(
3044 ParamMode::Optional,
3045 ImplTraitContext::Disallowed,
3052 node: hir::FieldPat {
3053 id: self.next_id().node_id,
3054 ident: f.node.ident,
3055 pat: self.lower_pat(&f.node.pat),
3056 is_shorthand: f.node.is_shorthand,
3060 hir::PatKind::Struct(qpath, fs, etc)
3062 PatKind::Tuple(ref elts, ddpos) => {
3063 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3065 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3066 PatKind::Ref(ref inner, mutbl) => {
3067 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3069 PatKind::Range(ref e1, ref e2, ref end) => hir::PatKind::Range(
3070 P(self.lower_expr(e1)),
3071 P(self.lower_expr(e2)),
3072 self.lower_range_end(end),
3074 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3075 before.iter().map(|x| self.lower_pat(x)).collect(),
3076 slice.as_ref().map(|x| self.lower_pat(x)),
3077 after.iter().map(|x| self.lower_pat(x)).collect(),
3079 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3080 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3083 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3092 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3094 RangeEnd::Included(_) => hir::RangeEnd::Included,
3095 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3099 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3100 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3105 body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3109 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3110 let kind = match e.node {
3111 ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
3112 ExprKind::ObsoleteInPlace(..) => {
3113 self.sess.abort_if_errors();
3114 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3116 ExprKind::Array(ref exprs) => {
3117 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
3119 ExprKind::Repeat(ref expr, ref count) => {
3120 let expr = P(self.lower_expr(expr));
3121 let count = self.lower_anon_const(count);
3122 hir::ExprRepeat(expr, count)
3124 ExprKind::Tup(ref elts) => {
3125 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
3127 ExprKind::Call(ref f, ref args) => {
3128 let f = P(self.lower_expr(f));
3129 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
3131 ExprKind::MethodCall(ref seg, ref args) => {
3132 let hir_seg = self.lower_path_segment(
3135 ParamMode::Optional,
3137 ParenthesizedGenericArgs::Err,
3138 ImplTraitContext::Disallowed,
3140 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3141 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
3143 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3144 let binop = self.lower_binop(binop);
3145 let lhs = P(self.lower_expr(lhs));
3146 let rhs = P(self.lower_expr(rhs));
3147 hir::ExprBinary(binop, lhs, rhs)
3149 ExprKind::Unary(op, ref ohs) => {
3150 let op = self.lower_unop(op);
3151 let ohs = P(self.lower_expr(ohs));
3152 hir::ExprUnary(op, ohs)
3154 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
3155 ExprKind::Cast(ref expr, ref ty) => {
3156 let expr = P(self.lower_expr(expr));
3157 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3159 ExprKind::Type(ref expr, ref ty) => {
3160 let expr = P(self.lower_expr(expr));
3161 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3163 ExprKind::AddrOf(m, ref ohs) => {
3164 let m = self.lower_mutability(m);
3165 let ohs = P(self.lower_expr(ohs));
3166 hir::ExprAddrOf(m, ohs)
3168 // More complicated than you might expect because the else branch
3169 // might be `if let`.
3170 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3171 let else_opt = else_opt.as_ref().map(|els| {
3173 ExprKind::IfLet(..) => {
3174 // wrap the if-let expr in a block
3175 let span = els.span;
3176 let els = P(self.lower_expr(els));
3177 let LoweredNodeId { node_id, hir_id } = self.next_id();
3178 let blk = P(hir::Block {
3183 rules: hir::DefaultBlock,
3185 targeted_by_break: false,
3186 recovered: blk.recovered,
3188 P(self.expr_block(blk, ThinVec::new()))
3190 _ => P(self.lower_expr(els)),
3194 let then_blk = self.lower_block(blk, false);
3195 let then_expr = self.expr_block(then_blk, ThinVec::new());
3197 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3199 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3201 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3202 this.lower_block(body, false),
3203 this.lower_label(opt_label),
3206 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3208 this.lower_block(body, false),
3209 this.lower_label(opt_label),
3210 hir::LoopSource::Loop,
3213 ExprKind::Catch(ref body) => {
3214 self.with_catch_scope(body.id, |this| {
3216 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3217 let mut block = this.lower_block(body, true).into_inner();
3218 let tail = block.expr.take().map_or_else(
3220 let LoweredNodeId { node_id, hir_id } = this.next_id();
3221 let span = this.sess.codemap().end_point(unstable_span);
3225 node: hir::ExprTup(hir_vec![]),
3226 attrs: ThinVec::new(),
3230 |x: P<hir::Expr>| x.into_inner(),
3232 block.expr = Some(this.wrap_in_try_constructor(
3233 "from_ok", tail, unstable_span));
3234 hir::ExprBlock(P(block), None)
3237 ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3238 P(self.lower_expr(expr)),
3239 arms.iter().map(|x| self.lower_arm(x)).collect(),
3240 hir::MatchSource::Normal,
3242 ExprKind::Closure(capture_clause, movability, ref decl, ref body, fn_decl_span) => {
3243 self.with_new_scopes(|this| {
3244 let mut is_generator = false;
3245 let body_id = this.lower_body(Some(decl), |this| {
3246 let e = this.lower_expr(body);
3247 is_generator = this.is_generator;
3250 let generator_option = if is_generator {
3251 if !decl.inputs.is_empty() {
3256 "generators cannot have explicit arguments"
3258 this.sess.abort_if_errors();
3260 Some(match movability {
3261 Movability::Movable => hir::GeneratorMovability::Movable,
3262 Movability::Static => hir::GeneratorMovability::Static,
3265 if movability == Movability::Static {
3270 "closures cannot be static"
3276 this.lower_capture_clause(capture_clause),
3277 this.lower_fn_decl(decl, None, false),
3284 ExprKind::Block(ref blk, opt_label) => {
3285 hir::ExprBlock(self.lower_block(blk,
3286 opt_label.is_some()),
3287 self.lower_label(opt_label))
3289 ExprKind::Assign(ref el, ref er) => {
3290 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3292 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3293 self.lower_binop(op),
3294 P(self.lower_expr(el)),
3295 P(self.lower_expr(er)),
3297 ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3298 ExprKind::Index(ref el, ref er) => {
3299 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3301 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3302 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3303 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3304 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3305 let id = self.next_id();
3306 let e1 = self.lower_expr(e1);
3307 let e2 = self.lower_expr(e2);
3308 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], false));
3309 let ty = self.ty_path(id, span, hir::QPath::Resolved(None, ty_path));
3310 let new_seg = P(hir::PathSegment::from_name(Symbol::intern("new")));
3311 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3312 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3313 hir::ExprCall(new, hir_vec![e1, e2])
3315 ExprKind::Range(ref e1, ref e2, lims) => {
3316 use syntax::ast::RangeLimits::*;
3318 let path = match (e1, e2, lims) {
3319 (&None, &None, HalfOpen) => "RangeFull",
3320 (&Some(..), &None, HalfOpen) => "RangeFrom",
3321 (&None, &Some(..), HalfOpen) => "RangeTo",
3322 (&Some(..), &Some(..), HalfOpen) => "Range",
3323 (&None, &Some(..), Closed) => "RangeToInclusive",
3324 (&Some(..), &Some(..), Closed) => unreachable!(),
3325 (_, &None, Closed) => self.diagnostic()
3326 .span_fatal(e.span, "inclusive range with no end")
3330 let fields = e1.iter()
3331 .map(|e| ("start", e))
3332 .chain(e2.iter().map(|e| ("end", e)))
3334 let expr = P(self.lower_expr(&e));
3336 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3337 let ident = Ident::new(Symbol::intern(s), unstable_span);
3338 self.field(ident, expr, unstable_span)
3340 .collect::<P<[hir::Field]>>();
3342 let is_unit = fields.is_empty();
3344 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3345 let struct_path = iter::once("ops")
3346 .chain(iter::once(path))
3347 .collect::<Vec<_>>();
3348 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
3349 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3351 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3357 hir::ExprPath(struct_path)
3359 hir::ExprStruct(struct_path, fields, None)
3361 span: unstable_span,
3362 attrs: e.attrs.clone(),
3365 ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3369 ParamMode::Optional,
3370 ImplTraitContext::Disallowed,
3372 ExprKind::Break(opt_label, ref opt_expr) => {
3373 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3376 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3379 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3383 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3386 ExprKind::Continue(opt_label) => {
3387 hir::ExprAgain(if self.is_in_loop_condition && opt_label.is_none() {
3390 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3393 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3396 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3397 ExprKind::InlineAsm(ref asm) => {
3398 let hir_asm = hir::InlineAsm {
3399 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3400 outputs: asm.outputs
3402 .map(|out| hir::InlineAsmOutput {
3403 constraint: out.constraint.clone(),
3405 is_indirect: out.is_indirect,
3408 asm: asm.asm.clone(),
3409 asm_str_style: asm.asm_str_style,
3410 clobbers: asm.clobbers.clone().into(),
3411 volatile: asm.volatile,
3412 alignstack: asm.alignstack,
3413 dialect: asm.dialect,
3416 let outputs = asm.outputs
3418 .map(|out| self.lower_expr(&out.expr))
3420 let inputs = asm.inputs
3422 .map(|&(_, ref input)| self.lower_expr(input))
3424 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3426 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3431 ParamMode::Optional,
3432 ImplTraitContext::Disallowed,
3434 fields.iter().map(|x| self.lower_field(x)).collect(),
3435 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3437 ExprKind::Paren(ref ex) => {
3438 let mut ex = self.lower_expr(ex);
3439 // include parens in span, but only if it is a super-span.
3440 if e.span.contains(ex.span) {
3443 // merge attributes into the inner expression.
3444 let mut attrs = e.attrs.clone();
3445 attrs.extend::<Vec<_>>(ex.attrs.into());
3450 ExprKind::Yield(ref opt_expr) => {
3451 self.is_generator = true;
3454 .map(|x| self.lower_expr(x))
3455 .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3456 hir::ExprYield(P(expr))
3459 // Desugar ExprIfLet
3460 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3461 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3464 // match <sub_expr> {
3466 // _ => [<else_opt> | ()]
3469 let mut arms = vec![];
3471 // `<pat> => <body>`
3473 let body = self.lower_block(body, false);
3474 let body_expr = P(self.expr_block(body, ThinVec::new()));
3475 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3476 arms.push(self.arm(pats, body_expr));
3479 // _ => [<else_opt>|()]
3481 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3482 let wildcard_pattern = self.pat_wild(e.span);
3483 let body = if let Some(else_expr) = wildcard_arm {
3484 P(self.lower_expr(else_expr))
3486 self.expr_tuple(e.span, hir_vec![])
3488 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3491 let contains_else_clause = else_opt.is_some();
3493 let sub_expr = P(self.lower_expr(sub_expr));
3498 hir::MatchSource::IfLetDesugar {
3499 contains_else_clause,
3504 // Desugar ExprWhileLet
3505 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3506 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3509 // [opt_ident]: loop {
3510 // match <sub_expr> {
3516 // Note that the block AND the condition are evaluated in the loop scope.
3517 // This is done to allow `break` from inside the condition of the loop.
3518 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3520 this.lower_block(body, false),
3521 this.expr_break(e.span, ThinVec::new()),
3522 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3526 // `<pat> => <body>`
3528 let body_expr = P(self.expr_block(body, ThinVec::new()));
3529 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3530 self.arm(pats, body_expr)
3535 let pat_under = self.pat_wild(e.span);
3536 self.arm(hir_vec![pat_under], break_expr)
3539 // `match <sub_expr> { ... }`
3540 let arms = hir_vec![pat_arm, break_arm];
3541 let match_expr = self.expr(
3543 hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3547 // `[opt_ident]: loop { ... }`
3548 let loop_block = P(self.block_expr(P(match_expr)));
3549 let loop_expr = hir::ExprLoop(
3551 self.lower_label(opt_label),
3552 hir::LoopSource::WhileLet,
3554 // add attributes to the outer returned expr node
3558 // Desugar ExprForLoop
3559 // From: `[opt_ident]: for <pat> in <head> <body>`
3560 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3564 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3566 // [opt_ident]: loop {
3568 // match ::std::iter::Iterator::next(&mut iter) {
3569 // ::std::option::Option::Some(val) => __next = val,
3570 // ::std::option::Option::None => break
3572 // let <pat> = __next;
3573 // StmtExpr(<body>);
3581 let head = self.lower_expr(head);
3582 let head_sp = head.span;
3584 let iter = self.str_to_ident("iter");
3586 let next_ident = self.str_to_ident("__next");
3587 let next_pat = self.pat_ident_binding_mode(
3590 hir::BindingAnnotation::Mutable,
3593 // `::std::option::Option::Some(val) => next = val`
3595 let val_ident = self.str_to_ident("val");
3596 let val_pat = self.pat_ident(pat.span, val_ident);
3597 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
3598 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
3599 let assign = P(self.expr(
3601 hir::ExprAssign(next_expr, val_expr),
3604 let some_pat = self.pat_some(pat.span, val_pat);
3605 self.arm(hir_vec![some_pat], assign)
3608 // `::std::option::Option::None => break`
3611 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
3612 let pat = self.pat_none(e.span);
3613 self.arm(hir_vec![pat], break_expr)
3618 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
3620 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
3622 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
3623 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
3624 let next_path = &["iter", "Iterator", "next"];
3625 let next_path = P(self.expr_std_path(head_sp, next_path, ThinVec::new()));
3626 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
3627 let arms = hir_vec![pat_arm, break_arm];
3631 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
3635 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
3637 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
3641 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
3643 // `let <pat> = __next`
3644 let pat = self.lower_pat(pat);
3645 let pat_let = self.stmt_let_pat(
3649 hir::LocalSource::ForLoopDesugar,
3652 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
3653 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
3654 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
3656 let loop_block = P(self.block_all(
3658 hir_vec![next_let, match_stmt, pat_let, body_stmt],
3662 // `[opt_ident]: loop { ... }`
3663 let loop_expr = hir::ExprLoop(
3665 self.lower_label(opt_label),
3666 hir::LoopSource::ForLoop,
3668 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3669 let loop_expr = P(hir::Expr {
3674 attrs: ThinVec::new(),
3677 // `mut iter => { ... }`
3678 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
3680 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
3681 let into_iter_expr = {
3682 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
3683 let into_iter = P(self.expr_std_path(head_sp, into_iter_path, ThinVec::new()));
3684 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
3687 let match_expr = P(self.expr_match(
3691 hir::MatchSource::ForLoopDesugar,
3694 // `{ let _result = ...; _result }`
3695 // underscore prevents an unused_variables lint if the head diverges
3696 let result_ident = self.str_to_ident("_result");
3697 let (let_stmt, let_stmt_binding) =
3698 self.stmt_let(e.span, false, result_ident, match_expr);
3700 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
3701 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
3702 // add the attributes to the outer returned expr node
3703 return self.expr_block(block, e.attrs.clone());
3706 // Desugar ExprKind::Try
3708 ExprKind::Try(ref sub_expr) => {
3711 // match Try::into_result(<expr>) {
3712 // Ok(val) => #[allow(unreachable_code)] val,
3713 // Err(err) => #[allow(unreachable_code)]
3714 // // If there is an enclosing `catch {...}`
3715 // break 'catch_target Try::from_error(From::from(err)),
3717 // return Try::from_error(From::from(err)),
3721 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
3723 // Try::into_result(<expr>)
3726 let sub_expr = self.lower_expr(sub_expr);
3728 let path = &["ops", "Try", "into_result"];
3729 let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
3730 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
3733 // #[allow(unreachable_code)]
3735 // allow(unreachable_code)
3737 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
3738 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
3739 let uc_nested = attr::mk_nested_word_item(uc_ident);
3740 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
3742 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
3744 let attrs = vec![attr];
3746 // Ok(val) => #[allow(unreachable_code)] val,
3748 let val_ident = self.str_to_ident("val");
3749 let val_pat = self.pat_ident(e.span, val_ident);
3750 let val_expr = P(self.expr_ident_with_attrs(
3754 ThinVec::from(attrs.clone()),
3756 let ok_pat = self.pat_ok(e.span, val_pat);
3758 self.arm(hir_vec![ok_pat], val_expr)
3761 // Err(err) => #[allow(unreachable_code)]
3762 // return Try::from_error(From::from(err)),
3764 let err_ident = self.str_to_ident("err");
3765 let err_local = self.pat_ident(e.span, err_ident);
3767 let path = &["convert", "From", "from"];
3768 let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
3769 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
3771 self.expr_call(e.span, from, hir_vec![err_expr])
3774 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
3775 let thin_attrs = ThinVec::from(attrs);
3776 let catch_scope = self.catch_scopes.last().map(|x| *x);
3777 let ret_expr = if let Some(catch_node) = catch_scope {
3783 target_id: Ok(catch_node),
3785 Some(from_err_expr),
3790 P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
3793 let err_pat = self.pat_err(e.span, err_local);
3794 self.arm(hir_vec![err_pat], ret_expr)
3799 hir_vec![err_arm, ok_arm],
3800 hir::MatchSource::TryDesugar,
3804 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
3807 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3814 attrs: e.attrs.clone(),
3818 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
3819 SmallVector::one(match s.node {
3820 StmtKind::Local(ref l) => Spanned {
3821 node: hir::StmtDecl(
3823 node: hir::DeclLocal(self.lower_local(l)),
3826 self.lower_node_id(s.id).node_id,
3830 StmtKind::Item(ref it) => {
3831 // Can only use the ID once.
3832 let mut id = Some(s.id);
3833 return self.lower_item_id(it)
3835 .map(|item_id| Spanned {
3836 node: hir::StmtDecl(
3838 node: hir::DeclItem(item_id),
3842 .map(|id| self.lower_node_id(id).node_id)
3843 .unwrap_or_else(|| self.next_id().node_id),
3849 StmtKind::Expr(ref e) => Spanned {
3850 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3853 StmtKind::Semi(ref e) => Spanned {
3854 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3857 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
3861 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
3863 CaptureBy::Value => hir::CaptureByValue,
3864 CaptureBy::Ref => hir::CaptureByRef,
3868 /// If an `explicit_owner` is given, this method allocates the `HirId` in
3869 /// the address space of that item instead of the item currently being
3870 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
3871 /// lower a `Visibility` value although we haven't lowered the owning
3872 /// `ImplItem` in question yet.
3873 fn lower_visibility(
3876 explicit_owner: Option<NodeId>,
3877 ) -> hir::Visibility {
3879 VisibilityKind::Public => hir::Public,
3880 VisibilityKind::Crate(sugar) => hir::Visibility::Crate(sugar),
3881 VisibilityKind::Restricted { ref path, id, .. } => hir::Visibility::Restricted {
3882 path: P(self.lower_path(id, path, ParamMode::Explicit)),
3883 id: if let Some(owner) = explicit_owner {
3884 self.lower_node_id_with_owner(id, owner).node_id
3886 self.lower_node_id(id).node_id
3889 VisibilityKind::Inherited => hir::Inherited,
3893 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
3895 Defaultness::Default => hir::Defaultness::Default {
3896 has_value: has_value,
3898 Defaultness::Final => {
3900 hir::Defaultness::Final
3905 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3907 BlockCheckMode::Default => hir::DefaultBlock,
3908 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3912 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3914 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
3915 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
3916 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
3917 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
3921 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3923 CompilerGenerated => hir::CompilerGenerated,
3924 UserProvided => hir::UserProvided,
3928 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
3930 ImplPolarity::Positive => hir::ImplPolarity::Positive,
3931 ImplPolarity::Negative => hir::ImplPolarity::Negative,
3935 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3937 TraitBoundModifier::None => hir::TraitBoundModifier::None,
3938 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3942 // Helper methods for building HIR.
3944 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
3953 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
3955 id: self.next_id().node_id,
3959 is_shorthand: false,
3963 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
3964 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
3965 P(self.expr(span, expr_break, attrs))
3972 args: hir::HirVec<hir::Expr>,
3974 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
3977 fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
3978 self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
3981 fn expr_ident_with_attrs(
3986 attrs: ThinVec<Attribute>,
3988 let expr_path = hir::ExprPath(hir::QPath::Resolved(
3992 def: Def::Local(binding),
3993 segments: hir_vec![hir::PathSegment::from_name(id)],
3997 self.expr(span, expr_path, attrs)
4000 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4001 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
4007 components: &[&str],
4008 attrs: ThinVec<Attribute>,
4010 let path = self.std_path(span, components, true);
4013 hir::ExprPath(hir::QPath::Resolved(None, P(path))),
4022 arms: hir::HirVec<hir::Arm>,
4023 source: hir::MatchSource,
4025 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
4028 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4029 self.expr(b.span, hir::ExprBlock(b, None), attrs)
4032 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4033 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
4036 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
4037 let LoweredNodeId { node_id, hir_id } = self.next_id();
4050 ex: Option<P<hir::Expr>>,
4052 source: hir::LocalSource,
4054 let LoweredNodeId { node_id, hir_id } = self.next_id();
4056 let local = P(hir::Local {
4063 attrs: ThinVec::new(),
4066 let decl = respan(sp, hir::DeclLocal(local));
4067 respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
4076 ) -> (hir::Stmt, NodeId) {
4077 let pat = if mutbl {
4078 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4080 self.pat_ident(sp, ident)
4082 let pat_id = pat.id;
4084 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4089 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4090 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4096 stmts: hir::HirVec<hir::Stmt>,
4097 expr: Option<P<hir::Expr>>,
4099 let LoweredNodeId { node_id, hir_id } = self.next_id();
4106 rules: hir::DefaultBlock,
4108 targeted_by_break: false,
4113 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4114 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4117 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4118 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4121 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4122 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4125 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4126 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4132 components: &[&str],
4133 subpats: hir::HirVec<P<hir::Pat>>,
4135 let path = self.std_path(span, components, true);
4136 let qpath = hir::QPath::Resolved(None, P(path));
4137 let pt = if subpats.is_empty() {
4138 hir::PatKind::Path(qpath)
4140 hir::PatKind::TupleStruct(qpath, subpats, None)
4145 fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
4146 self.pat_ident_binding_mode(span, name, hir::BindingAnnotation::Unannotated)
4149 fn pat_ident_binding_mode(
4153 bm: hir::BindingAnnotation,
4155 let LoweredNodeId { node_id, hir_id } = self.next_id();
4160 node: hir::PatKind::Binding(bm, node_id, Spanned { span, node: name }, None),
4165 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4166 self.pat(span, hir::PatKind::Wild)
4169 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4170 let LoweredNodeId { node_id, hir_id } = self.next_id();
4179 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4180 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4181 /// The path is also resolved according to `is_value`.
4182 fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
4184 .resolve_str_path(span, self.crate_root, components, is_value)
4187 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
4189 let node = match qpath {
4190 hir::QPath::Resolved(None, path) => {
4191 // Turn trait object paths into `TyTraitObject` instead.
4192 if let Def::Trait(_) = path.def {
4193 let principal = hir::PolyTraitRef {
4194 bound_generic_params: hir::HirVec::new(),
4195 trait_ref: hir::TraitRef {
4196 path: path.and_then(|path| path),
4202 // The original ID is taken by the `PolyTraitRef`,
4203 // so the `Ty` itself needs a different one.
4204 id = self.next_id();
4205 hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4207 hir::TyPath(hir::QPath::Resolved(None, path))
4210 _ => hir::TyPath(qpath),
4220 /// Invoked to create the lifetime argument for a type `&T`
4221 /// with no explicit lifetime.
4222 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4223 match self.anonymous_lifetime_mode {
4224 // Intercept when we are in an impl header and introduce an in-band lifetime.
4225 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4227 AnonymousLifetimeMode::CreateParameter => {
4228 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4230 id: self.next_id().node_id,
4236 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4240 /// Invoked to create the lifetime argument(s) for a path like
4241 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4242 /// sorts of cases are deprecated. This may therefore report a warning or an
4243 /// error, depending on the mode.
4244 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4245 match self.anonymous_lifetime_mode {
4246 // NB. We intentionally ignore the create-parameter mode here
4247 // and instead "pass through" to resolve-lifetimes, which will then
4248 // report an error. This is because we don't want to support
4249 // impl elision for deprecated forms like
4251 // impl Foo for std::cell::Ref<u32> // note lack of '_
4252 AnonymousLifetimeMode::CreateParameter => {}
4254 // This is the normal case.
4255 AnonymousLifetimeMode::PassThrough => {}
4259 .map(|_| self.new_implicit_lifetime(span))
4263 /// Invoked to create the lifetime argument(s) for an elided trait object
4264 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4265 /// when the bound is written, even if it is written with `'_` like in
4266 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4267 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4268 match self.anonymous_lifetime_mode {
4269 // NB. We intentionally ignore the create-parameter mode here.
4270 // and instead "pass through" to resolve-lifetimes, which will apply
4271 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4272 // do not act like other elided lifetimes. In other words, given this:
4274 // impl Foo for Box<dyn Debug>
4276 // we do not introduce a fresh `'_` to serve as the bound, but instead
4277 // ultimately translate to the equivalent of:
4279 // impl Foo for Box<dyn Debug + 'static>
4281 // `resolve_lifetime` has the code to make that happen.
4282 AnonymousLifetimeMode::CreateParameter => {}
4284 // This is the normal case.
4285 AnonymousLifetimeMode::PassThrough => {}
4288 self.new_implicit_lifetime(span)
4291 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4293 id: self.next_id().node_id,
4295 name: hir::LifetimeName::Implicit,
4299 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4300 self.sess.buffer_lint_with_diagnostic(
4301 builtin::BARE_TRAIT_OBJECTS,
4304 "trait objects without an explicit `dyn` are deprecated",
4305 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4309 fn wrap_in_try_constructor(
4311 method: &'static str,
4313 unstable_span: Span,
4315 let path = &["ops", "Try", method];
4316 let from_err = P(self.expr_std_path(unstable_span, path,
4318 P(self.expr_call(e.span, from_err, hir_vec![e]))
4322 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4323 // Sorting by span ensures that we get things in order within a
4324 // file, and also puts the files in a sensible order.
4325 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4326 body_ids.sort_by_key(|b| bodies[b].value.span);