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};
49 use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES};
50 use middle::cstore::CrateStore;
51 use rustc_data_structures::indexed_vec::IndexVec;
53 use util::common::FN_OUTPUT_NAME;
54 use util::nodemap::{DefIdMap, FxHashMap, NodeMap};
56 use std::collections::{BTreeMap, HashSet};
63 use syntax::ext::hygiene::{Mark, SyntaxContext};
64 use syntax::print::pprust;
66 use syntax::codemap::{self, respan, CompilerDesugaringKind, Spanned};
67 use syntax::std_inject;
68 use syntax::symbol::{keywords, Symbol};
69 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
70 use syntax::parse::token::Token;
71 use syntax::util::small_vector::SmallVector;
72 use syntax::visit::{self, Visitor};
75 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
77 pub struct LoweringContext<'a> {
78 crate_root: Option<&'static str>,
80 // Use to assign ids to hir nodes that do not directly correspond to an ast node
83 cstore: &'a CrateStore,
85 resolver: &'a mut Resolver,
86 name_map: FxHashMap<Ident, Name>,
88 /// The items being lowered are collected here.
89 items: BTreeMap<NodeId, hir::Item>,
91 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
92 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
93 bodies: BTreeMap<hir::BodyId, hir::Body>,
94 exported_macros: Vec<hir::MacroDef>,
96 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
97 trait_auto_impl: BTreeMap<DefId, NodeId>,
101 catch_scopes: Vec<NodeId>,
102 loop_scopes: Vec<NodeId>,
103 is_in_loop_condition: bool,
104 is_in_trait_impl: bool,
106 /// What to do when we encounter either an "anonymous lifetime
107 /// reference". The term "anonymous" is meant to encompass both
108 /// `'_` lifetimes as well as fully elided cases where nothing is
109 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
110 anonymous_lifetime_mode: AnonymousLifetimeMode,
112 // This is a list of in-band type definitions being generated by
113 // Argument-position `impl Trait`.
114 // When traversing a signature such as `fn foo(x: impl Trait)`,
115 // we record `impl Trait` as a new type parameter, then later
116 // add it on to `foo`s generics.
117 in_band_ty_params: Vec<hir::TyParam>,
119 // Used to create lifetime definitions from in-band lifetime usages.
120 // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
121 // When a named lifetime is encountered in a function or impl header and
122 // has not been defined
123 // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
124 // to this list. The results of this list are then added to the list of
125 // lifetime definitions in the corresponding impl or function generics.
126 lifetimes_to_define: Vec<(Span, hir::LifetimeName)>,
128 // Whether or not in-band lifetimes are being collected. This is used to
129 // indicate whether or not we're in a place where new lifetimes will result
130 // in in-band lifetime definitions, such a function or an impl header.
131 // This will always be false unless the `in_band_lifetimes` feature is
133 is_collecting_in_band_lifetimes: bool,
135 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
136 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
137 // against this list to see if it is already in-scope, or if a definition
138 // needs to be created for it.
139 in_scope_lifetimes: Vec<Name>,
141 type_def_lifetime_params: DefIdMap<usize>,
143 current_hir_id_owner: Vec<(DefIndex, u32)>,
144 item_local_id_counters: NodeMap<u32>,
145 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
149 /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
150 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
152 /// Obtain the resolution for a node id
153 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
155 /// Obtain the possible resolutions for the given `use` statement.
156 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
158 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
159 /// This should only return `None` during testing.
160 fn definitions(&mut self) -> &mut Definitions;
162 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
163 /// it based on `is_value`.
167 crate_root: Option<&str>,
173 #[derive(Clone, Copy, Debug)]
174 enum ImplTraitContext {
175 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
176 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
177 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
179 /// We store a DefId here so we can look up necessary information later
182 /// Treat `impl Trait` as shorthand for a new universal existential parameter.
183 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
184 /// equivalent to a fresh existential parameter like `abstract type T; fn foo() -> T`.
186 /// We store a DefId here so we can look up necessary information later
189 /// `impl Trait` is not accepted in this position.
196 dep_graph: &DepGraph,
198 resolver: &mut Resolver,
200 // We're constructing the HIR here; we don't care what we will
201 // read, since we haven't even constructed the *input* to
203 dep_graph.assert_ignored();
206 crate_root: std_inject::injected_crate_name(),
210 name_map: FxHashMap(),
211 items: BTreeMap::new(),
212 trait_items: BTreeMap::new(),
213 impl_items: BTreeMap::new(),
214 bodies: BTreeMap::new(),
215 trait_impls: BTreeMap::new(),
216 trait_auto_impl: BTreeMap::new(),
217 exported_macros: Vec::new(),
218 catch_scopes: Vec::new(),
219 loop_scopes: Vec::new(),
220 is_in_loop_condition: false,
221 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
222 type_def_lifetime_params: DefIdMap(),
223 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
224 item_local_id_counters: NodeMap(),
225 node_id_to_hir_id: IndexVec::new(),
227 is_in_trait_impl: false,
228 in_band_ty_params: Vec::new(),
229 lifetimes_to_define: Vec::new(),
230 is_collecting_in_band_lifetimes: false,
231 in_scope_lifetimes: Vec::new(),
235 #[derive(Copy, Clone, PartialEq, Eq)]
237 /// Any path in a type context.
239 /// The `module::Type` in `module::Type::method` in an expression.
244 struct LoweredNodeId {
249 enum ParenthesizedGenericArgs {
255 /// What to do when we encounter an **anonymous** lifetime
256 /// reference. Anonymous lifetime references come in two flavors. You
257 /// have implicit, or fully elided, references to lifetimes, like the
258 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
259 /// or `Ref<'_, T>`. These often behave the same, but not always:
261 /// - certain usages of implicit references are deprecated, like
262 /// `Ref<T>`, and we sometimes just give hard errors in those cases
264 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
265 /// the same as `Box<dyn Foo + '_>`.
267 /// We describe the effects of the various modes in terms of three cases:
269 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
270 /// of a `&` (e.g., the missing lifetime in something like `&T`)
271 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
272 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
273 /// elided bounds follow special rules. Note that this only covers
274 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
275 /// '_>` is a case of "modern" elision.
276 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
277 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
278 /// non-deprecated equivalent.
280 /// Currently, the handling of lifetime elision is somewhat spread out
281 /// between HIR lowering and -- as described below -- the
282 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
283 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
284 /// everything into HIR lowering.
285 #[derive(Copy, Clone)]
286 enum AnonymousLifetimeMode {
287 /// For **Modern** cases, create a new anonymous region parameter
288 /// and reference that.
290 /// For **Dyn Bound** cases, pass responsibility to
291 /// `resolve_lifetime` code.
293 /// For **Deprecated** cases, report an error.
296 /// Pass responsibility to `resolve_lifetime` code for all cases.
300 impl<'a> LoweringContext<'a> {
301 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
302 /// Full-crate AST visitor that inserts into a fresh
303 /// `LoweringContext` any information that may be
304 /// needed from arbitrary locations in the crate.
305 /// E.g. The number of lifetime generic parameters
306 /// declared for every type and trait definition.
307 struct MiscCollector<'lcx, 'interner: 'lcx> {
308 lctx: &'lcx mut LoweringContext<'interner>,
311 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
312 fn visit_item(&mut self, item: &'lcx Item) {
313 self.lctx.allocate_hir_id_counter(item.id, item);
316 ItemKind::Struct(_, ref generics)
317 | ItemKind::Union(_, ref generics)
318 | ItemKind::Enum(_, ref generics)
319 | ItemKind::Ty(_, ref generics)
320 | ItemKind::Trait(_, _, ref generics, ..) => {
321 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
325 .filter(|param| param.is_lifetime_param())
327 self.lctx.type_def_lifetime_params.insert(def_id, count);
331 visit::walk_item(self, item);
334 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
335 self.lctx.allocate_hir_id_counter(item.id, item);
336 visit::walk_trait_item(self, item);
339 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
340 self.lctx.allocate_hir_id_counter(item.id, item);
341 visit::walk_impl_item(self, item);
345 struct ItemLowerer<'lcx, 'interner: 'lcx> {
346 lctx: &'lcx mut LoweringContext<'interner>,
349 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
350 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
352 F: FnOnce(&mut Self),
354 let old = self.lctx.is_in_trait_impl;
355 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
361 self.lctx.is_in_trait_impl = old;
365 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
366 fn visit_item(&mut self, item: &'lcx Item) {
367 let mut item_lowered = true;
368 self.lctx.with_hir_id_owner(item.id, |lctx| {
369 if let Some(hir_item) = lctx.lower_item(item) {
370 lctx.items.insert(item.id, hir_item);
372 item_lowered = false;
377 let item_lifetimes = match self.lctx.items.get(&item.id).unwrap().node {
378 hir::Item_::ItemImpl(_, _, _, ref generics, ..)
379 | hir::Item_::ItemTrait(_, _, ref generics, ..) => {
380 generics.lifetimes().cloned().collect::<Vec<_>>()
386 .with_parent_impl_lifetime_defs(&item_lifetimes, |this| {
387 let this = &mut ItemLowerer { lctx: this };
388 if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
389 this.with_trait_impl_ref(opt_trait_ref, |this| {
390 visit::walk_item(this, item)
393 visit::walk_item(this, item);
399 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
400 self.lctx.with_hir_id_owner(item.id, |lctx| {
401 let id = hir::TraitItemId { node_id: item.id };
402 let hir_item = lctx.lower_trait_item(item);
403 lctx.trait_items.insert(id, hir_item);
406 visit::walk_trait_item(self, item);
409 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
410 self.lctx.with_hir_id_owner(item.id, |lctx| {
411 let id = hir::ImplItemId { node_id: item.id };
412 let hir_item = lctx.lower_impl_item(item);
413 lctx.impl_items.insert(id, hir_item);
415 visit::walk_impl_item(self, item);
419 self.lower_node_id(CRATE_NODE_ID);
420 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
422 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
423 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
425 let module = self.lower_mod(&c.module);
426 let attrs = self.lower_attrs(&c.attrs);
427 let body_ids = body_ids(&self.bodies);
431 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
437 exported_macros: hir::HirVec::from(self.exported_macros),
439 trait_items: self.trait_items,
440 impl_items: self.impl_items,
443 trait_impls: self.trait_impls,
444 trait_auto_impl: self.trait_auto_impl,
448 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) {
449 if self.item_local_id_counters.insert(owner, 0).is_some() {
451 "Tried to allocate item_local_id_counter for {:?} twice",
455 // Always allocate the first HirId for the owner itself
456 self.lower_node_id_with_owner(owner, owner);
459 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
461 F: FnOnce(&mut Self) -> hir::HirId,
463 if ast_node_id == DUMMY_NODE_ID {
464 return LoweredNodeId {
465 node_id: DUMMY_NODE_ID,
466 hir_id: hir::DUMMY_HIR_ID,
470 let min_size = ast_node_id.as_usize() + 1;
472 if min_size > self.node_id_to_hir_id.len() {
473 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
476 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
478 if existing_hir_id == hir::DUMMY_HIR_ID {
479 // Generate a new HirId
480 let hir_id = alloc_hir_id(self);
481 self.node_id_to_hir_id[ast_node_id] = hir_id;
483 node_id: ast_node_id,
488 node_id: ast_node_id,
489 hir_id: existing_hir_id,
494 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
496 F: FnOnce(&mut Self) -> T,
498 let counter = self.item_local_id_counters
499 .insert(owner, HIR_ID_COUNTER_LOCKED)
501 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
502 self.current_hir_id_owner.push((def_index, counter));
504 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
506 debug_assert!(def_index == new_def_index);
507 debug_assert!(new_counter >= counter);
509 let prev = self.item_local_id_counters
510 .insert(owner, new_counter)
512 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
516 /// This method allocates a new HirId for the given NodeId and stores it in
517 /// the LoweringContext's NodeId => HirId map.
518 /// Take care not to call this method if the resulting HirId is then not
519 /// actually used in the HIR, as that would trigger an assertion in the
520 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
521 /// properly. Calling the method twice with the same NodeId is fine though.
522 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
523 self.lower_node_id_generic(ast_node_id, |this| {
524 let &mut (def_index, ref mut local_id_counter) =
525 this.current_hir_id_owner.last_mut().unwrap();
526 let local_id = *local_id_counter;
527 *local_id_counter += 1;
530 local_id: hir::ItemLocalId(local_id),
535 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
536 self.lower_node_id_generic(ast_node_id, |this| {
537 let local_id_counter = this
538 .item_local_id_counters
540 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
541 let local_id = *local_id_counter;
543 // We want to be sure not to modify the counter in the map while it
544 // is also on the stack. Otherwise we'll get lost updates when writing
545 // back from the stack to the map.
546 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
548 *local_id_counter += 1;
552 .opt_def_index(owner)
553 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
554 that do not belong to the current owner");
558 local_id: hir::ItemLocalId(local_id),
563 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
564 let body = hir::Body {
565 arguments: decl.map_or(hir_vec![], |decl| {
566 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
568 is_generator: self.is_generator,
572 self.bodies.insert(id, body);
576 fn next_id(&mut self) -> LoweredNodeId {
577 self.lower_node_id(self.sess.next_node_id())
580 fn expect_full_def(&mut self, id: NodeId) -> Def {
581 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
582 if pr.unresolved_segments() != 0 {
583 bug!("path not fully resolved: {:?}", pr);
589 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item=Def> {
590 self.resolver.get_import(id).present_items().map(|pr| {
591 if pr.unresolved_segments() != 0 {
592 bug!("path not fully resolved: {:?}", pr);
598 fn diagnostic(&self) -> &errors::Handler {
599 self.sess.diagnostic()
602 fn str_to_ident(&self, s: &'static str) -> Name {
606 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
607 let mark = Mark::fresh(Mark::root());
608 mark.set_expn_info(codemap::ExpnInfo {
610 callee: codemap::NameAndSpan {
611 format: codemap::CompilerDesugaring(reason),
613 allow_internal_unstable: true,
614 allow_internal_unsafe: false,
615 edition: codemap::hygiene::default_edition(),
618 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
621 fn with_anonymous_lifetime_mode<R>(
623 anonymous_lifetime_mode: AnonymousLifetimeMode,
624 op: impl FnOnce(&mut Self) -> R,
626 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
627 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
628 let result = op(self);
629 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
633 /// Creates a new hir::GenericParam for every new lifetime and
634 /// type parameter encountered while evaluating `f`. Definitions
635 /// are created with the parent provided. If no `parent_id` is
636 /// provided, no definitions will be returned.
638 /// Presuming that in-band lifetimes are enabled, then
639 /// `self.anonymous_lifetime_mode` will be updated to match the
640 /// argument while `f` is running (and restored afterwards).
641 fn collect_in_band_defs<T, F>(
644 anonymous_lifetime_mode: AnonymousLifetimeMode,
646 ) -> (Vec<hir::GenericParam>, T)
648 F: FnOnce(&mut LoweringContext) -> T,
650 assert!(!self.is_collecting_in_band_lifetimes);
651 assert!(self.lifetimes_to_define.is_empty());
652 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
654 self.is_collecting_in_band_lifetimes = self.sess.features_untracked().in_band_lifetimes;
655 if self.is_collecting_in_band_lifetimes {
656 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
659 assert!(self.in_band_ty_params.is_empty());
662 self.is_collecting_in_band_lifetimes = false;
663 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
665 let in_band_ty_params = self.in_band_ty_params.split_off(0);
666 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
668 let params = lifetimes_to_define
670 .map(|(span, hir_name)| {
671 let def_node_id = self.next_id().node_id;
673 // Get the name we'll use to make the def-path. Note
674 // that collisions are ok here and this shouldn't
675 // really show up for end-user.
676 let str_name = match hir_name {
677 hir::LifetimeName::Name(n) => n.as_str(),
678 hir::LifetimeName::Fresh(_) => keywords::UnderscoreLifetime.name().as_str(),
679 hir::LifetimeName::Implicit
680 | hir::LifetimeName::Underscore
681 | hir::LifetimeName::Static => {
682 span_bug!(span, "unexpected in-band lifetime name: {:?}", hir_name)
686 // Add a definition for the in-band lifetime def
687 self.resolver.definitions().create_def_with_parent(
690 DefPathData::LifetimeDef(str_name.as_interned_str()),
691 DefIndexAddressSpace::High,
696 hir::GenericParam::Lifetime(hir::LifetimeDef {
697 lifetime: hir::Lifetime {
702 bounds: Vec::new().into(),
703 pure_wrt_drop: false,
710 .map(|tp| hir::GenericParam::Type(tp)),
717 /// When there is a reference to some lifetime `'a`, and in-band
718 /// lifetimes are enabled, then we want to push that lifetime into
719 /// the vector of names to define later. In that case, it will get
720 /// added to the appropriate generics.
721 fn maybe_collect_in_band_lifetime(&mut self, span: Span, name: Name) {
722 if !self.is_collecting_in_band_lifetimes {
726 if self.in_scope_lifetimes.contains(&name) {
730 let hir_name = hir::LifetimeName::Name(name);
732 if self.lifetimes_to_define
734 .any(|(_, lt_name)| *lt_name == hir_name)
739 self.lifetimes_to_define.push((span, hir_name));
742 /// When we have either an elided or `'_` lifetime in an impl
743 /// header, we convert it to
744 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> hir::LifetimeName {
745 assert!(self.is_collecting_in_band_lifetimes);
746 let index = self.lifetimes_to_define.len();
747 let hir_name = hir::LifetimeName::Fresh(index);
748 self.lifetimes_to_define.push((span, hir_name));
752 // Evaluates `f` with the lifetimes in `lt_defs` in-scope.
753 // This is used to track which lifetimes have already been defined, and
754 // which are new in-band lifetimes that need to have a definition created
756 fn with_in_scope_lifetime_defs<'l, T, F>(
758 lt_defs: impl Iterator<Item = &'l LifetimeDef>,
762 F: FnOnce(&mut LoweringContext) -> T,
764 let old_len = self.in_scope_lifetimes.len();
765 let lt_def_names = lt_defs.map(|lt_def| lt_def.lifetime.ident.name);
766 self.in_scope_lifetimes.extend(lt_def_names);
770 self.in_scope_lifetimes.truncate(old_len);
774 // Same as the method above, but accepts `hir::LifetimeDef`s
775 // instead of `ast::LifetimeDef`s.
776 // This should only be used with generics that have already had their
777 // in-band lifetimes added. In practice, this means that this function is
778 // only used when lowering a child item of a trait or impl.
779 fn with_parent_impl_lifetime_defs<T, F>(&mut self, lt_defs: &[hir::LifetimeDef], f: F) -> T
781 F: FnOnce(&mut LoweringContext) -> T,
783 let old_len = self.in_scope_lifetimes.len();
784 let lt_def_names = lt_defs.iter().map(|lt_def| lt_def.lifetime.name.name());
785 self.in_scope_lifetimes.extend(lt_def_names);
789 self.in_scope_lifetimes.truncate(old_len);
793 /// Appends in-band lifetime defs and argument-position `impl
794 /// Trait` defs to the existing set of generics.
796 /// Presuming that in-band lifetimes are enabled, then
797 /// `self.anonymous_lifetime_mode` will be updated to match the
798 /// argument while `f` is running (and restored afterwards).
799 fn add_in_band_defs<F, T>(
803 anonymous_lifetime_mode: AnonymousLifetimeMode,
805 ) -> (hir::Generics, T)
807 F: FnOnce(&mut LoweringContext) -> T,
809 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
810 generics.params.iter().filter_map(|p| match p {
811 GenericParam::Lifetime(ld) => Some(ld),
815 let itctx = ImplTraitContext::Universal(parent_id);
816 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
817 (this.lower_generics(generics, itctx), f(this))
822 lowered_generics.params = lowered_generics
829 (lowered_generics, res)
832 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
834 F: FnOnce(&mut LoweringContext) -> T,
836 let len = self.catch_scopes.len();
837 self.catch_scopes.push(catch_id);
839 let result = f(self);
842 self.catch_scopes.len(),
843 "catch scopes should be added and removed in stack order"
846 self.catch_scopes.pop().unwrap();
851 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
853 F: FnOnce(&mut LoweringContext) -> hir::Expr,
855 let prev = mem::replace(&mut self.is_generator, false);
856 let result = f(self);
857 let r = self.record_body(result, decl);
858 self.is_generator = prev;
862 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
864 F: FnOnce(&mut LoweringContext) -> T,
866 // We're no longer in the base loop's condition; we're in another loop.
867 let was_in_loop_condition = self.is_in_loop_condition;
868 self.is_in_loop_condition = false;
870 let len = self.loop_scopes.len();
871 self.loop_scopes.push(loop_id);
873 let result = f(self);
876 self.loop_scopes.len(),
877 "Loop scopes should be added and removed in stack order"
880 self.loop_scopes.pop().unwrap();
882 self.is_in_loop_condition = was_in_loop_condition;
887 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
889 F: FnOnce(&mut LoweringContext) -> T,
891 let was_in_loop_condition = self.is_in_loop_condition;
892 self.is_in_loop_condition = true;
894 let result = f(self);
896 self.is_in_loop_condition = was_in_loop_condition;
901 fn with_new_scopes<T, F>(&mut self, f: F) -> T
903 F: FnOnce(&mut LoweringContext) -> T,
905 let was_in_loop_condition = self.is_in_loop_condition;
906 self.is_in_loop_condition = false;
908 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
909 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
910 let result = f(self);
911 self.catch_scopes = catch_scopes;
912 self.loop_scopes = loop_scopes;
914 self.is_in_loop_condition = was_in_loop_condition;
919 fn def_key(&mut self, id: DefId) -> DefKey {
921 self.resolver.definitions().def_key(id.index)
923 self.cstore.def_key(id)
927 fn lower_ident(&mut self, ident: Ident) -> Name {
928 let ident = ident.modern();
929 if ident.span.ctxt() == SyntaxContext::empty() {
934 .or_insert_with(|| Symbol::from_ident(ident))
937 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
938 label.map(|label| hir::Label {
939 name: label.ident.name,
940 span: label.ident.span,
944 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
946 Some((id, label)) => {
947 let target_id = if let Def::Label(loop_id) = self.expect_full_def(id) {
948 Ok(self.lower_node_id(loop_id).node_id)
950 Err(hir::LoopIdError::UnresolvedLabel)
953 label: self.lower_label(Some(label)),
958 let target_id = self.loop_scopes
960 .map(|innermost_loop_id| *innermost_loop_id)
961 .map(|id| Ok(self.lower_node_id(id).node_id))
962 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
973 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
976 .map(|a| self.lower_attr(a))
981 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
985 path: attr.path.clone(),
986 tokens: self.lower_token_stream(attr.tokens.clone()),
987 is_sugared_doc: attr.is_sugared_doc,
992 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
995 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
999 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1001 TokenTree::Token(span, token) => self.lower_token(token, span),
1002 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1005 delim: delimited.delim,
1006 tts: self.lower_token_stream(delimited.tts.into()).into(),
1012 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1014 Token::Interpolated(_) => {}
1015 other => return TokenTree::Token(span, other).into(),
1018 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1019 self.lower_token_stream(tts)
1022 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1024 attrs: self.lower_attrs(&arm.attrs),
1025 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1026 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1027 body: P(self.lower_expr(&arm.body)),
1031 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1033 id: self.lower_node_id(b.id).node_id,
1034 name: self.lower_ident(b.ident),
1035 ty: self.lower_ty(&b.ty, itctx),
1040 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1041 let kind = match t.node {
1042 TyKind::Infer => hir::TyInfer,
1043 TyKind::Err => hir::TyErr,
1044 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty, itctx)),
1045 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt, itctx)),
1046 TyKind::Rptr(ref region, ref mt) => {
1047 let span = t.span.shrink_to_lo();
1048 let lifetime = match *region {
1049 Some(ref lt) => self.lower_lifetime(lt),
1050 None => self.elided_ref_lifetime(span),
1052 hir::TyRptr(lifetime, self.lower_mt(mt, itctx))
1054 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1055 f.generic_params.iter().filter_map(|p| match p {
1056 GenericParam::Lifetime(ld) => Some(ld),
1060 this.with_anonymous_lifetime_mode(
1061 AnonymousLifetimeMode::PassThrough,
1063 hir::TyBareFn(P(hir::BareFnTy {
1064 generic_params: this.lower_generic_params(
1067 ImplTraitContext::Disallowed,
1069 unsafety: this.lower_unsafety(f.unsafety),
1071 decl: this.lower_fn_decl(&f.decl, None, false),
1072 arg_names: this.lower_fn_args_to_names(&f.decl),
1078 TyKind::Never => hir::TyNever,
1079 TyKind::Tup(ref tys) => {
1080 hir::TyTup(tys.iter().map(|ty| self.lower_ty(ty, itctx)).collect())
1082 TyKind::Paren(ref ty) => {
1083 return self.lower_ty(ty, itctx);
1085 TyKind::Path(ref qself, ref path) => {
1086 let id = self.lower_node_id(t.id);
1087 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1088 let ty = self.ty_path(id, t.span, qpath);
1089 if let hir::TyTraitObject(..) = ty.node {
1090 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1094 TyKind::ImplicitSelf => hir::TyPath(hir::QPath::Resolved(
1097 def: self.expect_full_def(t.id),
1098 segments: hir_vec![hir::PathSegment::from_name(keywords::SelfType.name())],
1102 TyKind::Array(ref ty, ref length) => {
1103 hir::TyArray(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1105 TyKind::Typeof(ref expr) => {
1106 hir::TyTypeof(self.lower_anon_const(expr))
1108 TyKind::TraitObject(ref bounds, kind) => {
1109 let mut lifetime_bound = None;
1112 .filter_map(|bound| match *bound {
1113 TraitTyParamBound(ref ty, TraitBoundModifier::None) => {
1114 Some(self.lower_poly_trait_ref(ty, itctx))
1116 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
1117 RegionTyParamBound(ref lifetime) => {
1118 if lifetime_bound.is_none() {
1119 lifetime_bound = Some(self.lower_lifetime(lifetime));
1125 let lifetime_bound =
1126 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1127 if kind != TraitObjectSyntax::Dyn {
1128 self.maybe_lint_bare_trait(t.span, t.id, false);
1130 hir::TyTraitObject(bounds, lifetime_bound)
1132 TyKind::ImplTrait(ref bounds) => {
1135 ImplTraitContext::Existential(fn_def_id) => {
1137 // We need to manually repeat the code of `next_id` because the lowering
1138 // needs to happen while the owner_id is pointing to the item itself,
1139 // because items are their own owners
1140 let exist_ty_node_id = self.sess.next_node_id();
1142 // Make sure we know that some funky desugaring has been going on here.
1143 // This is a first: there is code in other places like for loop
1144 // desugaring that explicitly states that we don't want to track that.
1145 // Not tracking it makes lints in rustc and clippy very fragile as
1146 // frequently opened issues show.
1147 let exist_ty_span = self.allow_internal_unstable(
1148 CompilerDesugaringKind::ExistentialReturnType,
1152 // Pull a new definition from the ether
1153 let exist_ty_def_index = self
1156 .create_def_with_parent(
1159 DefPathData::ExistentialImplTrait,
1160 DefIndexAddressSpace::High,
1165 // the `t` is just for printing debug messages
1166 self.allocate_hir_id_counter(exist_ty_node_id, t);
1168 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1169 lctx.lower_bounds(bounds, itctx)
1172 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1178 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1179 let exist_ty_item_kind = hir::ItemExistential(hir::ExistTy {
1180 generics: hir::Generics {
1181 params: lifetime_defs,
1182 where_clause: hir::WhereClause {
1183 id: lctx.next_id().node_id,
1184 predicates: Vec::new().into(),
1189 impl_trait_fn: Some(fn_def_id),
1191 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1192 // Generate an `existential type Foo: Trait;` declaration
1193 trace!("creating existential type with id {:#?}", exist_ty_id);
1194 // Set the name to `impl Bound1 + Bound2`
1195 let exist_ty_name = Symbol::intern(&pprust::ty_to_string(t));
1197 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1198 let exist_ty_item = hir::Item {
1199 id: exist_ty_id.node_id,
1200 hir_id: exist_ty_id.hir_id,
1201 name: exist_ty_name,
1202 attrs: Default::default(),
1203 node: exist_ty_item_kind,
1204 vis: hir::Visibility::Inherited,
1205 span: exist_ty_span,
1208 // Insert the item into the global list. This usually happens
1209 // automatically for all AST items. But this existential type item
1210 // does not actually exist in the AST.
1211 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1213 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1214 hir::TyImplTraitExistential(
1216 id: exist_ty_id.node_id
1218 DefId::local(exist_ty_def_index),
1223 ImplTraitContext::Universal(def_id) => {
1224 let def_node_id = self.next_id().node_id;
1226 // Add a definition for the in-band TyParam
1227 let def_index = self.resolver.definitions().create_def_with_parent(
1230 DefPathData::UniversalImplTrait,
1231 DefIndexAddressSpace::High,
1236 let hir_bounds = self.lower_bounds(bounds, itctx);
1237 // Set the name to `impl Bound1 + Bound2`
1238 let name = Symbol::intern(&pprust::ty_to_string(t));
1239 self.in_band_ty_params.push(hir::TyParam {
1245 pure_wrt_drop: false,
1246 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1250 hir::TyPath(hir::QPath::Resolved(
1254 def: Def::TyParam(DefId::local(def_index)),
1255 segments: hir_vec![hir::PathSegment::from_name(name)],
1259 ImplTraitContext::Disallowed => {
1264 "`impl Trait` not allowed outside of function \
1265 and inherent method return types"
1271 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1274 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1283 fn lifetimes_from_impl_trait_bounds(
1285 exist_ty_id: NodeId,
1286 parent_index: DefIndex,
1287 bounds: &hir::TyParamBounds,
1288 ) -> (HirVec<hir::Lifetime>, HirVec<hir::GenericParam>) {
1289 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1290 // appear in the bounds, excluding lifetimes that are created within the bounds.
1291 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1292 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1293 context: &'r mut LoweringContext<'a>,
1295 exist_ty_id: NodeId,
1296 collect_elided_lifetimes: bool,
1297 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1298 already_defined_lifetimes: HashSet<hir::LifetimeName>,
1299 output_lifetimes: Vec<hir::Lifetime>,
1300 output_lifetime_params: Vec<hir::GenericParam>,
1303 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1304 fn nested_visit_map<'this>(
1306 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1307 hir::intravisit::NestedVisitorMap::None
1310 fn visit_path_parameters(&mut self, span: Span, parameters: &'v hir::PathParameters) {
1311 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1312 if parameters.parenthesized {
1313 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1314 self.collect_elided_lifetimes = false;
1315 hir::intravisit::walk_path_parameters(self, span, parameters);
1316 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1318 hir::intravisit::walk_path_parameters(self, span, parameters);
1322 fn visit_ty(&mut self, t: &'v hir::Ty) {
1323 // Don't collect elided lifetimes used inside of `fn()` syntax
1324 if let &hir::Ty_::TyBareFn(_) = &t.node {
1325 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1326 self.collect_elided_lifetimes = false;
1328 // Record the "stack height" of `for<'a>` lifetime bindings
1329 // to be able to later fully undo their introduction.
1330 let old_len = self.currently_bound_lifetimes.len();
1331 hir::intravisit::walk_ty(self, t);
1332 self.currently_bound_lifetimes.truncate(old_len);
1334 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1336 hir::intravisit::walk_ty(self, t);
1340 fn visit_poly_trait_ref(
1342 trait_ref: &'v hir::PolyTraitRef,
1343 modifier: hir::TraitBoundModifier,
1345 // Record the "stack height" of `for<'a>` lifetime bindings
1346 // to be able to later fully undo their introduction.
1347 let old_len = self.currently_bound_lifetimes.len();
1348 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1349 self.currently_bound_lifetimes.truncate(old_len);
1352 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1353 // Record the introduction of 'a in `for<'a> ...`
1354 if let hir::GenericParam::Lifetime(ref lt_def) = *param {
1355 // Introduce lifetimes one at a time so that we can handle
1356 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1357 self.currently_bound_lifetimes.push(lt_def.lifetime.name);
1360 hir::intravisit::walk_generic_param(self, param);
1363 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1364 let name = match lifetime.name {
1365 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1366 if self.collect_elided_lifetimes {
1367 // Use `'_` for both implicit and underscore lifetimes in
1368 // `abstract type Foo<'_>: SomeTrait<'_>;`
1369 hir::LifetimeName::Underscore
1374 name @ hir::LifetimeName::Fresh(_) => name,
1375 name @ hir::LifetimeName::Name(_) => name,
1376 hir::LifetimeName::Static => return,
1379 if !self.currently_bound_lifetimes.contains(&name)
1380 && !self.already_defined_lifetimes.contains(&name)
1382 self.already_defined_lifetimes.insert(name);
1384 self.output_lifetimes.push(hir::Lifetime {
1385 id: self.context.next_id().node_id,
1386 span: lifetime.span,
1390 // We need to manually create the ids here, because the
1391 // definitions will go into the explicit `existential type`
1392 // declaration and thus need to have their owner set to that item
1393 let def_node_id = self.context.sess.next_node_id();
1394 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1395 self.context.resolver.definitions().create_def_with_parent(
1398 DefPathData::LifetimeDef(name.name().as_interned_str()),
1399 DefIndexAddressSpace::High,
1403 let def_lifetime = hir::Lifetime {
1405 span: lifetime.span,
1408 self.output_lifetime_params
1409 .push(hir::GenericParam::Lifetime(hir::LifetimeDef {
1410 lifetime: def_lifetime,
1411 bounds: Vec::new().into(),
1412 pure_wrt_drop: false,
1419 let mut lifetime_collector = ImplTraitLifetimeCollector {
1421 parent: parent_index,
1423 collect_elided_lifetimes: true,
1424 currently_bound_lifetimes: Vec::new(),
1425 already_defined_lifetimes: HashSet::new(),
1426 output_lifetimes: Vec::new(),
1427 output_lifetime_params: Vec::new(),
1430 for bound in bounds {
1431 hir::intravisit::walk_ty_param_bound(&mut lifetime_collector, &bound);
1435 lifetime_collector.output_lifetimes.into(),
1436 lifetime_collector.output_lifetime_params.into(),
1440 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1445 .map(|x| self.lower_foreign_item(x))
1450 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1457 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1459 node: hir::Variant_ {
1460 name: v.node.ident.name,
1461 attrs: self.lower_attrs(&v.node.attrs),
1462 data: self.lower_variant_data(&v.node.data),
1463 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1472 qself: &Option<QSelf>,
1474 param_mode: ParamMode,
1475 itctx: ImplTraitContext,
1477 let qself_position = qself.as_ref().map(|q| q.position);
1478 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx));
1480 let resolution = self.resolver
1482 .unwrap_or(PathResolution::new(Def::Err));
1484 let proj_start = p.segments.len() - resolution.unresolved_segments();
1485 let path = P(hir::Path {
1486 def: resolution.base_def(),
1487 segments: p.segments[..proj_start]
1490 .map(|(i, segment)| {
1491 let param_mode = match (qself_position, param_mode) {
1492 (Some(j), ParamMode::Optional) if i < j => {
1493 // This segment is part of the trait path in a
1494 // qualified path - one of `a`, `b` or `Trait`
1495 // in `<X as a::b::Trait>::T::U::method`.
1501 // Figure out if this is a type/trait segment,
1502 // which may need lifetime elision performed.
1503 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1504 krate: def_id.krate,
1505 index: this.def_key(def_id).parent.expect("missing parent"),
1507 let type_def_id = match resolution.base_def() {
1508 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1509 Some(parent_def_id(self, def_id))
1511 Def::Variant(def_id) if i + 1 == proj_start => {
1512 Some(parent_def_id(self, def_id))
1515 | Def::Union(def_id)
1517 | Def::TyAlias(def_id)
1518 | Def::Trait(def_id) if i + 1 == proj_start =>
1524 let parenthesized_generic_args = match resolution.base_def() {
1525 // `a::b::Trait(Args)`
1526 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1527 // `a::b::Trait(Args)::TraitItem`
1528 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1529 if i + 2 == proj_start =>
1531 ParenthesizedGenericArgs::Ok
1533 // Avoid duplicated errors
1534 Def::Err => ParenthesizedGenericArgs::Ok,
1540 | Def::Variant(..) if i + 1 == proj_start =>
1542 ParenthesizedGenericArgs::Err
1544 // A warning for now, for compatibility reasons
1545 _ => ParenthesizedGenericArgs::Warn,
1548 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1549 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1552 assert!(!def_id.is_local());
1554 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1555 let n = item_generics.own_counts().lifetimes;
1556 self.type_def_lifetime_params.insert(def_id, n);
1559 self.lower_path_segment(
1564 parenthesized_generic_args,
1572 // Simple case, either no projections, or only fully-qualified.
1573 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1574 if resolution.unresolved_segments() == 0 {
1575 return hir::QPath::Resolved(qself, path);
1578 // Create the innermost type that we're projecting from.
1579 let mut ty = if path.segments.is_empty() {
1580 // If the base path is empty that means there exists a
1581 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1582 qself.expect("missing QSelf for <T>::...")
1584 // Otherwise, the base path is an implicit `Self` type path,
1585 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1586 // `<I as Iterator>::Item::default`.
1587 let new_id = self.next_id();
1588 self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))
1591 // Anything after the base path are associated "extensions",
1592 // out of which all but the last one are associated types,
1593 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1594 // * base path is `std::vec::Vec<T>`
1595 // * "extensions" are `IntoIter`, `Item` and `clone`
1596 // * type nodes are:
1597 // 1. `std::vec::Vec<T>` (created above)
1598 // 2. `<std::vec::Vec<T>>::IntoIter`
1599 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1600 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1601 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1602 let segment = P(self.lower_path_segment(
1607 ParenthesizedGenericArgs::Warn,
1610 let qpath = hir::QPath::TypeRelative(ty, segment);
1612 // It's finished, return the extension of the right node type.
1613 if i == p.segments.len() - 1 {
1617 // Wrap the associated extension in another type node.
1618 let new_id = self.next_id();
1619 ty = self.ty_path(new_id, p.span, qpath);
1622 // Should've returned in the for loop above.
1625 "lower_qpath: no final extension segment in {}..{}",
1631 fn lower_path_extra(
1636 param_mode: ParamMode,
1640 segments: p.segments
1643 self.lower_path_segment(
1648 ParenthesizedGenericArgs::Err,
1649 ImplTraitContext::Disallowed,
1652 .chain(name.map(|name| hir::PathSegment::from_name(name)))
1658 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1659 let def = self.expect_full_def(id);
1660 self.lower_path_extra(def, p, None, param_mode)
1663 fn lower_path_segment(
1666 segment: &PathSegment,
1667 param_mode: ParamMode,
1668 expected_lifetimes: usize,
1669 parenthesized_generic_args: ParenthesizedGenericArgs,
1670 itctx: ImplTraitContext,
1671 ) -> hir::PathSegment {
1672 let (mut parameters, infer_types) = if let Some(ref parameters) = segment.parameters {
1673 let msg = "parenthesized parameters may only be used with a trait";
1674 match **parameters {
1675 PathParameters::AngleBracketed(ref data) => {
1676 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1678 PathParameters::Parenthesized(ref data) => match parenthesized_generic_args {
1679 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1680 ParenthesizedGenericArgs::Warn => {
1681 self.sess.buffer_lint(
1682 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1687 (hir::PathParameters::none(), true)
1689 ParenthesizedGenericArgs::Err => {
1690 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1691 .span_label(data.span, "only traits may use parentheses")
1693 (hir::PathParameters::none(), true)
1698 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1701 if !parameters.parenthesized && parameters.lifetimes.is_empty() {
1702 parameters.lifetimes = self.elided_path_lifetimes(path_span, expected_lifetimes);
1705 hir::PathSegment::new(
1706 self.lower_ident(segment.ident),
1712 fn lower_angle_bracketed_parameter_data(
1714 data: &AngleBracketedParameterData,
1715 param_mode: ParamMode,
1716 itctx: ImplTraitContext,
1717 ) -> (hir::PathParameters, bool) {
1718 let &AngleBracketedParameterData {
1725 hir::PathParameters {
1726 lifetimes: self.lower_lifetimes(lifetimes),
1727 types: types.iter().map(|ty| self.lower_ty(ty, itctx)).collect(),
1730 .map(|b| self.lower_ty_binding(b, itctx))
1732 parenthesized: false,
1734 types.is_empty() && param_mode == ParamMode::Optional,
1738 fn lower_parenthesized_parameter_data(
1740 data: &ParenthesizedParameterData,
1741 ) -> (hir::PathParameters, bool) {
1742 // Switch to `PassThrough` mode for anonymous lifetimes: this
1743 // means that we permit things like `&Ref<T>`, where `Ref` has
1744 // a hidden lifetime parameter. This is needed for backwards
1745 // compatibility, even in contexts like an impl header where
1746 // we generally don't permit such things (see #51008).
1747 self.with_anonymous_lifetime_mode(
1748 AnonymousLifetimeMode::PassThrough,
1750 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1751 let &ParenthesizedParameterData {
1758 .map(|ty| this.lower_ty(ty, DISALLOWED))
1760 let mk_tup = |this: &mut Self, tys, span| {
1761 let LoweredNodeId { node_id, hir_id } = this.next_id();
1763 node: hir::TyTup(tys),
1771 hir::PathParameters {
1772 lifetimes: hir::HirVec::new(),
1773 types: hir_vec![mk_tup(this, inputs, span)],
1776 id: this.next_id().node_id,
1777 name: Symbol::intern(FN_OUTPUT_NAME),
1780 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1781 .unwrap_or_else(|| mk_tup(this, hir::HirVec::new(), span)),
1782 span: output.as_ref().map_or(span, |ty| ty.span),
1785 parenthesized: true,
1793 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1794 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1800 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1801 pat: self.lower_pat(&l.pat),
1802 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1804 attrs: l.attrs.clone(),
1805 source: hir::LocalSource::Normal,
1809 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1811 Mutability::Mutable => hir::MutMutable,
1812 Mutability::Immutable => hir::MutImmutable,
1816 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1817 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1821 pat: self.lower_pat(&arg.pat),
1825 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Spanned<Name>> {
1828 .map(|arg| match arg.pat.node {
1829 PatKind::Ident(_, ident, None) => respan(ident.span, ident.name),
1830 _ => respan(arg.pat.span, keywords::Invalid.name()),
1838 fn_def_id: Option<DefId>,
1839 impl_trait_return_allow: bool,
1840 ) -> P<hir::FnDecl> {
1841 // NOTE: The two last parameters here have to do with impl Trait. If fn_def_id is Some,
1842 // then impl Trait arguments are lowered into generic parameters on the given
1843 // fn_def_id, otherwise impl Trait is disallowed. (for now)
1845 // Furthermore, if impl_trait_return_allow is true, then impl Trait may be used in
1846 // return positions as well. This guards against trait declarations and their impls
1847 // where impl Trait is disallowed. (again for now)
1852 if let Some(def_id) = fn_def_id {
1853 self.lower_ty(&arg.ty, ImplTraitContext::Universal(def_id))
1855 self.lower_ty(&arg.ty, ImplTraitContext::Disallowed)
1859 output: match decl.output {
1860 FunctionRetTy::Ty(ref ty) => match fn_def_id {
1861 Some(def_id) if impl_trait_return_allow => {
1862 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1864 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1866 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1868 variadic: decl.variadic,
1869 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1870 TyKind::ImplicitSelf => true,
1871 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1877 fn lower_ty_param_bound(
1880 itctx: ImplTraitContext,
1881 ) -> hir::TyParamBound {
1883 TraitTyParamBound(ref ty, modifier) => hir::TraitTyParamBound(
1884 self.lower_poly_trait_ref(ty, itctx),
1885 self.lower_trait_bound_modifier(modifier),
1887 RegionTyParamBound(ref lifetime) => {
1888 hir::RegionTyParamBound(self.lower_lifetime(lifetime))
1896 add_bounds: &[TyParamBound],
1897 itctx: ImplTraitContext,
1899 let mut name = self.lower_ident(tp.ident);
1901 // Don't expose `Self` (recovered "keyword used as ident" parse error).
1902 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
1903 // Instead, use gensym("Self") to create a distinct name that looks the same.
1904 if name == keywords::SelfType.name() {
1905 name = Symbol::gensym("Self");
1908 let mut bounds = self.lower_bounds(&tp.bounds, itctx);
1909 if !add_bounds.is_empty() {
1912 .chain(self.lower_bounds(add_bounds, itctx).into_iter())
1917 id: self.lower_node_id(tp.id).node_id,
1922 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
1923 span: tp.ident.span,
1924 pure_wrt_drop: attr::contains_name(&tp.attrs, "may_dangle"),
1927 .filter(|attr| attr.check_name("rustc_synthetic"))
1928 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
1930 attrs: self.lower_attrs(&tp.attrs),
1934 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1935 let span = l.ident.span;
1936 match self.lower_ident(l.ident) {
1937 x if x == "'static" => self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
1938 x if x == "'_" => match self.anonymous_lifetime_mode {
1939 AnonymousLifetimeMode::CreateParameter => {
1940 let fresh_name = self.collect_fresh_in_band_lifetime(span);
1941 self.new_named_lifetime(l.id, span, fresh_name)
1944 AnonymousLifetimeMode::PassThrough => {
1945 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
1949 self.maybe_collect_in_band_lifetime(span, name);
1950 self.new_named_lifetime(l.id, span, hir::LifetimeName::Name(name))
1955 fn new_named_lifetime(
1959 name: hir::LifetimeName,
1960 ) -> hir::Lifetime {
1962 id: self.lower_node_id(id).node_id,
1968 fn lower_lifetime_def(&mut self, l: &LifetimeDef) -> hir::LifetimeDef {
1969 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
1970 self.is_collecting_in_band_lifetimes = false;
1972 let def = hir::LifetimeDef {
1973 lifetime: self.lower_lifetime(&l.lifetime),
1974 bounds: self.lower_lifetimes(&l.bounds),
1975 pure_wrt_drop: attr::contains_name(&l.attrs, "may_dangle"),
1979 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
1984 fn lower_lifetimes(&mut self, lts: &Vec<Lifetime>) -> hir::HirVec<hir::Lifetime> {
1985 lts.iter().map(|l| self.lower_lifetime(l)).collect()
1988 fn lower_generic_params(
1990 params: &Vec<GenericParam>,
1991 add_bounds: &NodeMap<Vec<TyParamBound>>,
1992 itctx: ImplTraitContext,
1993 ) -> hir::HirVec<hir::GenericParam> {
1996 .map(|param| match *param {
1997 GenericParam::Lifetime(ref lifetime_def) => {
1998 hir::GenericParam::Lifetime(self.lower_lifetime_def(lifetime_def))
2000 GenericParam::Type(ref ty_param) => hir::GenericParam::Type(self.lower_ty_param(
2002 add_bounds.get(&ty_param.id).map_or(&[][..], |x| &x),
2009 fn lower_generics(&mut self, g: &Generics, itctx: ImplTraitContext) -> hir::Generics {
2010 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2011 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2012 // paths where report_error is called are also the only paths that advance to after
2013 // the match statement, so the error reporting could probably just be moved there.
2014 let mut add_bounds = NodeMap();
2015 for pred in &g.where_clause.predicates {
2016 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2017 'next_bound: for bound in &bound_pred.bounds {
2018 if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
2019 let report_error = |this: &mut Self| {
2020 this.diagnostic().span_err(
2021 bound_pred.bounded_ty.span,
2022 "`?Trait` bounds are only permitted at the \
2023 point where a type parameter is declared",
2026 // Check if the where clause type is a plain type parameter.
2027 match bound_pred.bounded_ty.node {
2028 TyKind::Path(None, ref path)
2029 if path.segments.len() == 1
2030 && bound_pred.bound_generic_params.is_empty() =>
2032 if let Some(Def::TyParam(def_id)) = self.resolver
2033 .get_resolution(bound_pred.bounded_ty.id)
2034 .map(|d| d.base_def())
2036 if let Some(node_id) =
2037 self.resolver.definitions().as_local_node_id(def_id)
2039 for param in &g.params {
2040 if let GenericParam::Type(ref ty_param) = *param {
2041 if node_id == ty_param.id {
2044 .or_insert(Vec::new())
2045 .push(bound.clone());
2046 continue 'next_bound;
2054 _ => report_error(self),
2062 params: self.lower_generic_params(&g.params, &add_bounds, itctx),
2063 where_clause: self.lower_where_clause(&g.where_clause),
2068 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2070 id: self.lower_node_id(wc.id).node_id,
2071 predicates: wc.predicates
2073 .map(|predicate| self.lower_where_predicate(predicate))
2078 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2080 WherePredicate::BoundPredicate(WhereBoundPredicate {
2081 ref bound_generic_params,
2086 self.with_in_scope_lifetime_defs(
2087 bound_generic_params.iter().filter_map(|p| match p {
2088 GenericParam::Lifetime(ld) => Some(ld),
2092 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2093 bound_generic_params: this.lower_generic_params(
2094 bound_generic_params,
2096 ImplTraitContext::Disallowed,
2098 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2101 .filter_map(|bound| match *bound {
2102 // Ignore `?Trait` bounds.
2103 // Tthey were copied into type parameters already.
2104 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
2105 _ => Some(this.lower_ty_param_bound(
2107 ImplTraitContext::Disallowed,
2116 WherePredicate::RegionPredicate(WhereRegionPredicate {
2120 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2122 lifetime: self.lower_lifetime(lifetime),
2125 .map(|bound| self.lower_lifetime(bound))
2128 WherePredicate::EqPredicate(WhereEqPredicate {
2133 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2134 id: self.lower_node_id(id).node_id,
2135 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2136 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2142 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2144 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2148 .map(|f| self.lower_struct_field(f))
2150 self.lower_node_id(id).node_id,
2152 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2156 .map(|f| self.lower_struct_field(f))
2158 self.lower_node_id(id).node_id,
2160 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2164 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2165 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2166 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2167 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2171 ref_id: self.lower_node_id(p.ref_id).node_id,
2175 fn lower_poly_trait_ref(
2178 itctx: ImplTraitContext,
2179 ) -> hir::PolyTraitRef {
2180 let bound_generic_params =
2181 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx);
2182 let trait_ref = self.with_parent_impl_lifetime_defs(
2183 &bound_generic_params
2185 .filter_map(|p| match *p {
2186 hir::GenericParam::Lifetime(ref ld) => Some(ld.clone()),
2189 .collect::<Vec<_>>(),
2190 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2194 bound_generic_params,
2200 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2203 id: self.lower_node_id(f.id).node_id,
2204 ident: match f.ident {
2205 Some(ident) => ident,
2206 // FIXME(jseyfried) positional field hygiene
2207 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2209 vis: self.lower_visibility(&f.vis, None),
2210 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2211 attrs: self.lower_attrs(&f.attrs),
2215 fn lower_field(&mut self, f: &Field) -> hir::Field {
2217 id: self.next_id().node_id,
2219 expr: P(self.lower_expr(&f.expr)),
2221 is_shorthand: f.is_shorthand,
2225 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2227 ty: self.lower_ty(&mt.ty, itctx),
2228 mutbl: self.lower_mutability(mt.mutbl),
2234 bounds: &[TyParamBound],
2235 itctx: ImplTraitContext,
2236 ) -> hir::TyParamBounds {
2239 .map(|bound| self.lower_ty_param_bound(bound, itctx))
2243 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2244 let mut expr = None;
2246 let mut stmts = vec![];
2248 for (index, stmt) in b.stmts.iter().enumerate() {
2249 if index == b.stmts.len() - 1 {
2250 if let StmtKind::Expr(ref e) = stmt.node {
2251 expr = Some(P(self.lower_expr(e)));
2253 stmts.extend(self.lower_stmt(stmt));
2256 stmts.extend(self.lower_stmt(stmt));
2260 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2265 stmts: stmts.into(),
2267 rules: self.lower_block_check_mode(&b.rules),
2270 recovered: b.recovered,
2278 attrs: &hir::HirVec<Attribute>,
2279 vis: &mut hir::Visibility,
2283 ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2284 ItemKind::Use(ref use_tree) => {
2285 // Start with an empty prefix
2288 span: use_tree.span,
2291 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2293 ItemKind::Static(ref t, m, ref e) => {
2294 let value = self.lower_body(None, |this| this.lower_expr(e));
2296 self.lower_ty(t, ImplTraitContext::Disallowed),
2297 self.lower_mutability(m),
2301 ItemKind::Const(ref t, ref e) => {
2302 let value = self.lower_body(None, |this| this.lower_expr(e));
2303 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2305 ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
2306 let fn_def_id = self.resolver.definitions().local_def_id(id);
2307 self.with_new_scopes(|this| {
2308 let body_id = this.lower_body(Some(decl), |this| {
2309 let body = this.lower_block(body, false);
2310 this.expr_block(body, ThinVec::new())
2312 let (generics, fn_decl) = this.add_in_band_defs(
2315 AnonymousLifetimeMode::PassThrough,
2316 |this| this.lower_fn_decl(decl, Some(fn_def_id), true),
2321 this.lower_unsafety(unsafety),
2322 this.lower_constness(constness),
2329 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2330 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2331 ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2332 ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2333 self.lower_ty(t, ImplTraitContext::Disallowed),
2334 self.lower_generics(generics, ImplTraitContext::Disallowed),
2336 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2338 variants: enum_definition
2341 .map(|x| self.lower_variant(x))
2344 self.lower_generics(generics, ImplTraitContext::Disallowed),
2346 ItemKind::Struct(ref struct_def, ref generics) => {
2347 let struct_def = self.lower_variant_data(struct_def);
2350 self.lower_generics(generics, ImplTraitContext::Disallowed),
2353 ItemKind::Union(ref vdata, ref generics) => {
2354 let vdata = self.lower_variant_data(vdata);
2357 self.lower_generics(generics, ImplTraitContext::Disallowed),
2369 let def_id = self.resolver.definitions().local_def_id(id);
2371 // Lower the "impl header" first. This ordering is important
2372 // for in-band lifetimes! Consider `'a` here:
2374 // impl Foo<'a> for u32 {
2375 // fn method(&'a self) { .. }
2378 // Because we start by lowering the `Foo<'a> for u32`
2379 // part, we will add `'a` to the list of generics on
2380 // the impl. When we then encounter it later in the
2381 // method, it will not be considered an in-band
2382 // lifetime to be added, but rather a reference to a
2384 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2387 AnonymousLifetimeMode::CreateParameter,
2389 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2390 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2393 if let Some(ref trait_ref) = trait_ref {
2394 if let Def::Trait(def_id) = trait_ref.path.def {
2395 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2399 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2401 (trait_ref, lowered_ty)
2405 let new_impl_items = self.with_in_scope_lifetime_defs(
2406 ast_generics.params.iter().filter_map(|p| match p {
2407 GenericParam::Lifetime(ld) => Some(ld),
2413 .map(|item| this.lower_impl_item_ref(item))
2419 self.lower_unsafety(unsafety),
2420 self.lower_impl_polarity(polarity),
2421 self.lower_defaultness(defaultness, true /* [1] */),
2428 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2429 let bounds = self.lower_bounds(bounds, ImplTraitContext::Disallowed);
2432 .map(|item| self.lower_trait_item_ref(item))
2435 self.lower_is_auto(is_auto),
2436 self.lower_unsafety(unsafety),
2437 self.lower_generics(generics, ImplTraitContext::Disallowed),
2442 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2443 self.lower_generics(generics, ImplTraitContext::Disallowed),
2444 self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2446 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2449 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2450 // not cause an assertion failure inside the `lower_defaultness` function
2458 vis: &mut hir::Visibility,
2460 attrs: &hir::HirVec<Attribute>,
2462 let path = &tree.prefix;
2465 UseTreeKind::Simple(rename, id1, id2) => {
2466 *name = tree.ident().name;
2468 // First apply the prefix to the path
2469 let mut path = Path {
2473 .chain(path.segments.iter())
2479 // Correctly resolve `self` imports
2480 if path.segments.len() > 1
2481 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2483 let _ = path.segments.pop();
2484 if rename.is_none() {
2485 *name = path.segments.last().unwrap().ident.name;
2489 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2490 let mut defs = self.expect_full_def_from_use(id);
2491 // we want to return *something* from this function, so hang onto the first item
2493 let mut ret_def = defs.next().unwrap_or(Def::Err);
2495 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2496 let vis = vis.clone();
2497 let name = name.clone();
2498 let span = path.span;
2499 self.resolver.definitions().create_def_with_parent(
2503 DefIndexAddressSpace::High,
2506 self.allocate_hir_id_counter(new_node_id, &path);
2508 self.with_hir_id_owner(new_node_id, |this| {
2509 let new_id = this.lower_node_id(new_node_id);
2510 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2511 let item = hir::ItemUse(P(path), hir::UseKind::Single);
2512 let vis = match vis {
2513 hir::Visibility::Public => hir::Visibility::Public,
2514 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2515 hir::Visibility::Inherited => hir::Visibility::Inherited,
2516 hir::Visibility::Restricted { ref path, id: _ } => {
2517 hir::Visibility::Restricted {
2519 // We are allocating a new NodeId here
2520 id: this.next_id().node_id,
2529 hir_id: new_id.hir_id,
2531 attrs: attrs.clone(),
2540 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2541 hir::ItemUse(path, hir::UseKind::Single)
2543 UseTreeKind::Glob => {
2544 let path = P(self.lower_path(
2550 .chain(path.segments.iter())
2555 ParamMode::Explicit,
2557 hir::ItemUse(path, hir::UseKind::Glob)
2559 UseTreeKind::Nested(ref trees) => {
2564 .chain(path.segments.iter())
2567 span: prefix.span.to(path.span),
2570 // Add all the nested PathListItems in the HIR
2571 for &(ref use_tree, id) in trees {
2572 self.allocate_hir_id_counter(id, &use_tree);
2576 } = self.lower_node_id(id);
2578 let mut vis = vis.clone();
2579 let mut name = name.clone();
2581 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2583 self.with_hir_id_owner(new_id, |this| {
2584 let vis = match vis {
2585 hir::Visibility::Public => hir::Visibility::Public,
2586 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2587 hir::Visibility::Inherited => hir::Visibility::Inherited,
2588 hir::Visibility::Restricted { ref path, id: _ } => {
2589 hir::Visibility::Restricted {
2591 // We are allocating a new NodeId here
2592 id: this.next_id().node_id,
2603 attrs: attrs.clone(),
2606 span: use_tree.span,
2612 // Privatize the degenerate import base, used only to check
2613 // the stability of `use a::{};`, to avoid it showing up as
2614 // a re-export by accident when `pub`, e.g. in documentation.
2615 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2616 *vis = hir::Inherited;
2617 hir::ItemUse(path, hir::UseKind::ListStem)
2622 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2623 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2624 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2626 let (generics, node) = match i.node {
2627 TraitItemKind::Const(ref ty, ref default) => (
2628 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2629 hir::TraitItemKind::Const(
2630 self.lower_ty(ty, ImplTraitContext::Disallowed),
2633 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2636 TraitItemKind::Method(ref sig, None) => {
2637 let names = self.lower_fn_args_to_names(&sig.decl);
2638 self.add_in_band_defs(
2641 AnonymousLifetimeMode::PassThrough,
2643 hir::TraitItemKind::Method(
2644 this.lower_method_sig(sig, trait_item_def_id, false),
2645 hir::TraitMethod::Required(names),
2650 TraitItemKind::Method(ref sig, Some(ref body)) => {
2651 let body_id = self.lower_body(Some(&sig.decl), |this| {
2652 let body = this.lower_block(body, false);
2653 this.expr_block(body, ThinVec::new())
2656 self.add_in_band_defs(
2659 AnonymousLifetimeMode::PassThrough,
2661 hir::TraitItemKind::Method(
2662 this.lower_method_sig(sig, trait_item_def_id, false),
2663 hir::TraitMethod::Provided(body_id),
2668 TraitItemKind::Type(ref bounds, ref default) => (
2669 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2670 hir::TraitItemKind::Type(
2671 self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2674 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2677 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2683 name: self.lower_ident(i.ident),
2684 attrs: self.lower_attrs(&i.attrs),
2691 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2692 let (kind, has_default) = match i.node {
2693 TraitItemKind::Const(_, ref default) => {
2694 (hir::AssociatedItemKind::Const, default.is_some())
2696 TraitItemKind::Type(_, ref default) => {
2697 (hir::AssociatedItemKind::Type, default.is_some())
2699 TraitItemKind::Method(ref sig, ref default) => (
2700 hir::AssociatedItemKind::Method {
2701 has_self: sig.decl.has_self(),
2705 TraitItemKind::Macro(..) => unimplemented!(),
2708 id: hir::TraitItemId { node_id: i.id },
2709 name: self.lower_ident(i.ident),
2711 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
2716 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
2717 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2718 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
2720 let (generics, node) = match i.node {
2721 ImplItemKind::Const(ref ty, ref expr) => {
2722 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
2724 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2725 hir::ImplItemKind::Const(
2726 self.lower_ty(ty, ImplTraitContext::Disallowed),
2731 ImplItemKind::Method(ref sig, ref body) => {
2732 let body_id = self.lower_body(Some(&sig.decl), |this| {
2733 let body = this.lower_block(body, false);
2734 this.expr_block(body, ThinVec::new())
2736 let impl_trait_return_allow = !self.is_in_trait_impl;
2738 self.add_in_band_defs(
2741 AnonymousLifetimeMode::PassThrough,
2743 hir::ImplItemKind::Method(
2744 this.lower_method_sig(
2747 impl_trait_return_allow,
2754 ImplItemKind::Type(ref ty) => (
2755 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2756 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
2758 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2764 name: self.lower_ident(i.ident),
2765 attrs: self.lower_attrs(&i.attrs),
2767 vis: self.lower_visibility(&i.vis, None),
2768 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2773 // [1] since `default impl` is not yet implemented, this is always true in impls
2776 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
2778 id: hir::ImplItemId { node_id: i.id },
2779 name: self.lower_ident(i.ident),
2781 vis: self.lower_visibility(&i.vis, Some(i.id)),
2782 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2783 kind: match i.node {
2784 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
2785 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
2786 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
2787 has_self: sig.decl.has_self(),
2789 ImplItemKind::Macro(..) => unimplemented!(),
2793 // [1] since `default impl` is not yet implemented, this is always true in impls
2796 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
2799 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
2803 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
2805 ItemKind::Use(ref use_tree) => {
2806 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
2807 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
2810 ItemKind::MacroDef(..) => return SmallVector::new(),
2813 SmallVector::one(hir::ItemId { id: i.id })
2816 fn lower_item_id_use_tree(&mut self,
2819 vec: &mut SmallVector<hir::ItemId>)
2822 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
2823 vec.push(hir::ItemId { id });
2824 self.lower_item_id_use_tree(nested, id, vec);
2826 UseTreeKind::Glob => {}
2827 UseTreeKind::Simple(_, id1, id2) => {
2828 for (_, &id) in self.expect_full_def_from_use(base_id)
2830 .zip([id1, id2].iter())
2832 vec.push(hir::ItemId { id });
2838 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
2839 let mut name = i.ident.name;
2840 let mut vis = self.lower_visibility(&i.vis, None);
2841 let attrs = self.lower_attrs(&i.attrs);
2842 if let ItemKind::MacroDef(ref def) = i.node {
2843 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
2844 let body = self.lower_token_stream(def.stream());
2845 self.exported_macros.push(hir::MacroDef {
2858 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
2860 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2873 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
2874 let node_id = self.lower_node_id(i.id).node_id;
2875 let def_id = self.resolver.definitions().local_def_id(node_id);
2879 attrs: self.lower_attrs(&i.attrs),
2880 node: match i.node {
2881 ForeignItemKind::Fn(ref fdec, ref generics) => {
2882 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
2885 AnonymousLifetimeMode::PassThrough,
2888 // Disallow impl Trait in foreign items
2889 this.lower_fn_decl(fdec, None, false),
2890 this.lower_fn_args_to_names(fdec),
2895 hir::ForeignItemFn(fn_dec, fn_args, generics)
2897 ForeignItemKind::Static(ref t, m) => {
2898 hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
2900 ForeignItemKind::Ty => hir::ForeignItemType,
2901 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
2903 vis: self.lower_visibility(&i.vis, None),
2908 fn lower_method_sig(
2912 impl_trait_return_allow: bool,
2913 ) -> hir::MethodSig {
2916 unsafety: self.lower_unsafety(sig.unsafety),
2917 constness: self.lower_constness(sig.constness),
2918 decl: self.lower_fn_decl(&sig.decl, Some(fn_def_id), impl_trait_return_allow),
2922 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
2924 IsAuto::Yes => hir::IsAuto::Yes,
2925 IsAuto::No => hir::IsAuto::No,
2929 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
2931 Unsafety::Unsafe => hir::Unsafety::Unsafe,
2932 Unsafety::Normal => hir::Unsafety::Normal,
2936 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
2938 Constness::Const => hir::Constness::Const,
2939 Constness::NotConst => hir::Constness::NotConst,
2943 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
2945 UnOp::Deref => hir::UnDeref,
2946 UnOp::Not => hir::UnNot,
2947 UnOp::Neg => hir::UnNeg,
2951 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
2953 node: match b.node {
2954 BinOpKind::Add => hir::BiAdd,
2955 BinOpKind::Sub => hir::BiSub,
2956 BinOpKind::Mul => hir::BiMul,
2957 BinOpKind::Div => hir::BiDiv,
2958 BinOpKind::Rem => hir::BiRem,
2959 BinOpKind::And => hir::BiAnd,
2960 BinOpKind::Or => hir::BiOr,
2961 BinOpKind::BitXor => hir::BiBitXor,
2962 BinOpKind::BitAnd => hir::BiBitAnd,
2963 BinOpKind::BitOr => hir::BiBitOr,
2964 BinOpKind::Shl => hir::BiShl,
2965 BinOpKind::Shr => hir::BiShr,
2966 BinOpKind::Eq => hir::BiEq,
2967 BinOpKind::Lt => hir::BiLt,
2968 BinOpKind::Le => hir::BiLe,
2969 BinOpKind::Ne => hir::BiNe,
2970 BinOpKind::Ge => hir::BiGe,
2971 BinOpKind::Gt => hir::BiGt,
2977 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2978 let node = match p.node {
2979 PatKind::Wild => hir::PatKind::Wild,
2980 PatKind::Ident(ref binding_mode, ident, ref sub) => {
2981 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
2982 // `None` can occur in body-less function signatures
2983 def @ None | def @ Some(Def::Local(_)) => {
2984 let canonical_id = match def {
2985 Some(Def::Local(id)) => id,
2988 hir::PatKind::Binding(
2989 self.lower_binding_mode(binding_mode),
2991 respan(ident.span, ident.name),
2992 sub.as_ref().map(|x| self.lower_pat(x)),
2995 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3000 segments: hir_vec![hir::PathSegment::from_name(ident.name)],
3005 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3006 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3007 let qpath = self.lower_qpath(
3011 ParamMode::Optional,
3012 ImplTraitContext::Disallowed,
3014 hir::PatKind::TupleStruct(
3016 pats.iter().map(|x| self.lower_pat(x)).collect(),
3020 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3024 ParamMode::Optional,
3025 ImplTraitContext::Disallowed,
3027 PatKind::Struct(ref path, ref fields, etc) => {
3028 let qpath = self.lower_qpath(
3032 ParamMode::Optional,
3033 ImplTraitContext::Disallowed,
3040 node: hir::FieldPat {
3041 id: self.next_id().node_id,
3042 ident: f.node.ident,
3043 pat: self.lower_pat(&f.node.pat),
3044 is_shorthand: f.node.is_shorthand,
3048 hir::PatKind::Struct(qpath, fs, etc)
3050 PatKind::Tuple(ref elts, ddpos) => {
3051 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3053 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3054 PatKind::Ref(ref inner, mutbl) => {
3055 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3057 PatKind::Range(ref e1, ref e2, ref end) => hir::PatKind::Range(
3058 P(self.lower_expr(e1)),
3059 P(self.lower_expr(e2)),
3060 self.lower_range_end(end),
3062 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3063 before.iter().map(|x| self.lower_pat(x)).collect(),
3064 slice.as_ref().map(|x| self.lower_pat(x)),
3065 after.iter().map(|x| self.lower_pat(x)).collect(),
3067 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3068 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3071 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3080 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3082 RangeEnd::Included(_) => hir::RangeEnd::Included,
3083 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3087 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3088 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3093 body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3097 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3098 let kind = match e.node {
3099 ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
3100 ExprKind::ObsoleteInPlace(..) => {
3101 self.sess.abort_if_errors();
3102 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3104 ExprKind::Array(ref exprs) => {
3105 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
3107 ExprKind::Repeat(ref expr, ref count) => {
3108 let expr = P(self.lower_expr(expr));
3109 let count = self.lower_anon_const(count);
3110 hir::ExprRepeat(expr, count)
3112 ExprKind::Tup(ref elts) => {
3113 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
3115 ExprKind::Call(ref f, ref args) => {
3116 let f = P(self.lower_expr(f));
3117 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
3119 ExprKind::MethodCall(ref seg, ref args) => {
3120 let hir_seg = self.lower_path_segment(
3123 ParamMode::Optional,
3125 ParenthesizedGenericArgs::Err,
3126 ImplTraitContext::Disallowed,
3128 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3129 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
3131 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3132 let binop = self.lower_binop(binop);
3133 let lhs = P(self.lower_expr(lhs));
3134 let rhs = P(self.lower_expr(rhs));
3135 hir::ExprBinary(binop, lhs, rhs)
3137 ExprKind::Unary(op, ref ohs) => {
3138 let op = self.lower_unop(op);
3139 let ohs = P(self.lower_expr(ohs));
3140 hir::ExprUnary(op, ohs)
3142 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
3143 ExprKind::Cast(ref expr, ref ty) => {
3144 let expr = P(self.lower_expr(expr));
3145 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3147 ExprKind::Type(ref expr, ref ty) => {
3148 let expr = P(self.lower_expr(expr));
3149 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3151 ExprKind::AddrOf(m, ref ohs) => {
3152 let m = self.lower_mutability(m);
3153 let ohs = P(self.lower_expr(ohs));
3154 hir::ExprAddrOf(m, ohs)
3156 // More complicated than you might expect because the else branch
3157 // might be `if let`.
3158 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3159 let else_opt = else_opt.as_ref().map(|els| {
3161 ExprKind::IfLet(..) => {
3162 // wrap the if-let expr in a block
3163 let span = els.span;
3164 let els = P(self.lower_expr(els));
3165 let LoweredNodeId { node_id, hir_id } = self.next_id();
3166 let blk = P(hir::Block {
3171 rules: hir::DefaultBlock,
3173 targeted_by_break: false,
3174 recovered: blk.recovered,
3176 P(self.expr_block(blk, ThinVec::new()))
3178 _ => P(self.lower_expr(els)),
3182 let then_blk = self.lower_block(blk, false);
3183 let then_expr = self.expr_block(then_blk, ThinVec::new());
3185 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3187 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3189 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3190 this.lower_block(body, false),
3191 this.lower_label(opt_label),
3194 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3196 this.lower_block(body, false),
3197 this.lower_label(opt_label),
3198 hir::LoopSource::Loop,
3201 ExprKind::Catch(ref body) => {
3202 self.with_catch_scope(body.id, |this| {
3204 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3205 let mut block = this.lower_block(body, true).into_inner();
3206 let tail = block.expr.take().map_or_else(
3208 let LoweredNodeId { node_id, hir_id } = this.next_id();
3209 let span = this.sess.codemap().end_point(unstable_span);
3213 node: hir::ExprTup(hir_vec![]),
3214 attrs: ThinVec::new(),
3218 |x: P<hir::Expr>| x.into_inner(),
3220 block.expr = Some(this.wrap_in_try_constructor(
3221 "from_ok", tail, unstable_span));
3222 hir::ExprBlock(P(block), None)
3225 ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3226 P(self.lower_expr(expr)),
3227 arms.iter().map(|x| self.lower_arm(x)).collect(),
3228 hir::MatchSource::Normal,
3230 ExprKind::Closure(capture_clause, movability, ref decl, ref body, fn_decl_span) => {
3231 self.with_new_scopes(|this| {
3232 let mut is_generator = false;
3233 let body_id = this.lower_body(Some(decl), |this| {
3234 let e = this.lower_expr(body);
3235 is_generator = this.is_generator;
3238 let generator_option = if is_generator {
3239 if !decl.inputs.is_empty() {
3244 "generators cannot have explicit arguments"
3246 this.sess.abort_if_errors();
3248 Some(match movability {
3249 Movability::Movable => hir::GeneratorMovability::Movable,
3250 Movability::Static => hir::GeneratorMovability::Static,
3253 if movability == Movability::Static {
3258 "closures cannot be static"
3264 this.lower_capture_clause(capture_clause),
3265 this.lower_fn_decl(decl, None, false),
3272 ExprKind::Block(ref blk, opt_label) => {
3273 hir::ExprBlock(self.lower_block(blk,
3274 opt_label.is_some()),
3275 self.lower_label(opt_label))
3277 ExprKind::Assign(ref el, ref er) => {
3278 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3280 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3281 self.lower_binop(op),
3282 P(self.lower_expr(el)),
3283 P(self.lower_expr(er)),
3285 ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3286 ExprKind::Index(ref el, ref er) => {
3287 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3289 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3290 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3291 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3292 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3293 let id = self.next_id();
3294 let e1 = self.lower_expr(e1);
3295 let e2 = self.lower_expr(e2);
3296 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], false));
3297 let ty = self.ty_path(id, span, hir::QPath::Resolved(None, ty_path));
3298 let new_seg = P(hir::PathSegment::from_name(Symbol::intern("new")));
3299 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3300 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3301 hir::ExprCall(new, hir_vec![e1, e2])
3303 ExprKind::Range(ref e1, ref e2, lims) => {
3304 use syntax::ast::RangeLimits::*;
3306 let path = match (e1, e2, lims) {
3307 (&None, &None, HalfOpen) => "RangeFull",
3308 (&Some(..), &None, HalfOpen) => "RangeFrom",
3309 (&None, &Some(..), HalfOpen) => "RangeTo",
3310 (&Some(..), &Some(..), HalfOpen) => "Range",
3311 (&None, &Some(..), Closed) => "RangeToInclusive",
3312 (&Some(..), &Some(..), Closed) => unreachable!(),
3313 (_, &None, Closed) => self.diagnostic()
3314 .span_fatal(e.span, "inclusive range with no end")
3318 let fields = e1.iter()
3319 .map(|e| ("start", e))
3320 .chain(e2.iter().map(|e| ("end", e)))
3322 let expr = P(self.lower_expr(&e));
3324 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3325 let ident = Ident::new(Symbol::intern(s), unstable_span);
3326 self.field(ident, expr, unstable_span)
3328 .collect::<P<[hir::Field]>>();
3330 let is_unit = fields.is_empty();
3332 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3333 let struct_path = iter::once("ops")
3334 .chain(iter::once(path))
3335 .collect::<Vec<_>>();
3336 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
3337 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3339 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3345 hir::ExprPath(struct_path)
3347 hir::ExprStruct(struct_path, fields, None)
3349 span: unstable_span,
3350 attrs: e.attrs.clone(),
3353 ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3357 ParamMode::Optional,
3358 ImplTraitContext::Disallowed,
3360 ExprKind::Break(opt_label, ref opt_expr) => {
3361 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3364 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3367 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3371 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3374 ExprKind::Continue(opt_label) => {
3375 hir::ExprAgain(if self.is_in_loop_condition && opt_label.is_none() {
3378 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3381 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3384 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3385 ExprKind::InlineAsm(ref asm) => {
3386 let hir_asm = hir::InlineAsm {
3387 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3388 outputs: asm.outputs
3390 .map(|out| hir::InlineAsmOutput {
3391 constraint: out.constraint.clone(),
3393 is_indirect: out.is_indirect,
3396 asm: asm.asm.clone(),
3397 asm_str_style: asm.asm_str_style,
3398 clobbers: asm.clobbers.clone().into(),
3399 volatile: asm.volatile,
3400 alignstack: asm.alignstack,
3401 dialect: asm.dialect,
3404 let outputs = asm.outputs
3406 .map(|out| self.lower_expr(&out.expr))
3408 let inputs = asm.inputs
3410 .map(|&(_, ref input)| self.lower_expr(input))
3412 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3414 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3419 ParamMode::Optional,
3420 ImplTraitContext::Disallowed,
3422 fields.iter().map(|x| self.lower_field(x)).collect(),
3423 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3425 ExprKind::Paren(ref ex) => {
3426 let mut ex = self.lower_expr(ex);
3427 // include parens in span, but only if it is a super-span.
3428 if e.span.contains(ex.span) {
3431 // merge attributes into the inner expression.
3432 let mut attrs = e.attrs.clone();
3433 attrs.extend::<Vec<_>>(ex.attrs.into());
3438 ExprKind::Yield(ref opt_expr) => {
3439 self.is_generator = true;
3442 .map(|x| self.lower_expr(x))
3443 .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3444 hir::ExprYield(P(expr))
3447 // Desugar ExprIfLet
3448 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3449 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3452 // match <sub_expr> {
3454 // _ => [<else_opt> | ()]
3457 let mut arms = vec![];
3459 // `<pat> => <body>`
3461 let body = self.lower_block(body, false);
3462 let body_expr = P(self.expr_block(body, ThinVec::new()));
3463 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3464 arms.push(self.arm(pats, body_expr));
3467 // _ => [<else_opt>|()]
3469 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3470 let wildcard_pattern = self.pat_wild(e.span);
3471 let body = if let Some(else_expr) = wildcard_arm {
3472 P(self.lower_expr(else_expr))
3474 self.expr_tuple(e.span, hir_vec![])
3476 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3479 let contains_else_clause = else_opt.is_some();
3481 let sub_expr = P(self.lower_expr(sub_expr));
3486 hir::MatchSource::IfLetDesugar {
3487 contains_else_clause,
3492 // Desugar ExprWhileLet
3493 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3494 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3497 // [opt_ident]: loop {
3498 // match <sub_expr> {
3504 // Note that the block AND the condition are evaluated in the loop scope.
3505 // This is done to allow `break` from inside the condition of the loop.
3506 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3508 this.lower_block(body, false),
3509 this.expr_break(e.span, ThinVec::new()),
3510 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3514 // `<pat> => <body>`
3516 let body_expr = P(self.expr_block(body, ThinVec::new()));
3517 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3518 self.arm(pats, body_expr)
3523 let pat_under = self.pat_wild(e.span);
3524 self.arm(hir_vec![pat_under], break_expr)
3527 // `match <sub_expr> { ... }`
3528 let arms = hir_vec![pat_arm, break_arm];
3529 let match_expr = self.expr(
3531 hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3535 // `[opt_ident]: loop { ... }`
3536 let loop_block = P(self.block_expr(P(match_expr)));
3537 let loop_expr = hir::ExprLoop(
3539 self.lower_label(opt_label),
3540 hir::LoopSource::WhileLet,
3542 // add attributes to the outer returned expr node
3546 // Desugar ExprForLoop
3547 // From: `[opt_ident]: for <pat> in <head> <body>`
3548 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3552 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3554 // [opt_ident]: loop {
3556 // match ::std::iter::Iterator::next(&mut iter) {
3557 // ::std::option::Option::Some(val) => __next = val,
3558 // ::std::option::Option::None => break
3560 // let <pat> = __next;
3561 // StmtExpr(<body>);
3569 let head = self.lower_expr(head);
3570 let head_sp = head.span;
3572 let iter = self.str_to_ident("iter");
3574 let next_ident = self.str_to_ident("__next");
3575 let next_pat = self.pat_ident_binding_mode(
3578 hir::BindingAnnotation::Mutable,
3581 // `::std::option::Option::Some(val) => next = val`
3583 let val_ident = self.str_to_ident("val");
3584 let val_pat = self.pat_ident(pat.span, val_ident);
3585 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
3586 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
3587 let assign = P(self.expr(
3589 hir::ExprAssign(next_expr, val_expr),
3592 let some_pat = self.pat_some(pat.span, val_pat);
3593 self.arm(hir_vec![some_pat], assign)
3596 // `::std::option::Option::None => break`
3599 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
3600 let pat = self.pat_none(e.span);
3601 self.arm(hir_vec![pat], break_expr)
3606 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
3608 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
3610 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
3611 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
3612 let next_path = &["iter", "Iterator", "next"];
3613 let next_path = P(self.expr_std_path(head_sp, next_path, ThinVec::new()));
3614 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
3615 let arms = hir_vec![pat_arm, break_arm];
3619 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
3623 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
3625 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
3629 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
3631 // `let <pat> = __next`
3632 let pat = self.lower_pat(pat);
3633 let pat_let = self.stmt_let_pat(
3637 hir::LocalSource::ForLoopDesugar,
3640 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
3641 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
3642 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
3644 let loop_block = P(self.block_all(
3646 hir_vec![next_let, match_stmt, pat_let, body_stmt],
3650 // `[opt_ident]: loop { ... }`
3651 let loop_expr = hir::ExprLoop(
3653 self.lower_label(opt_label),
3654 hir::LoopSource::ForLoop,
3656 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3657 let loop_expr = P(hir::Expr {
3662 attrs: ThinVec::new(),
3665 // `mut iter => { ... }`
3666 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
3668 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
3669 let into_iter_expr = {
3670 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
3671 let into_iter = P(self.expr_std_path(head_sp, into_iter_path, ThinVec::new()));
3672 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
3675 let match_expr = P(self.expr_match(
3679 hir::MatchSource::ForLoopDesugar,
3682 // `{ let _result = ...; _result }`
3683 // underscore prevents an unused_variables lint if the head diverges
3684 let result_ident = self.str_to_ident("_result");
3685 let (let_stmt, let_stmt_binding) =
3686 self.stmt_let(e.span, false, result_ident, match_expr);
3688 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
3689 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
3690 // add the attributes to the outer returned expr node
3691 return self.expr_block(block, e.attrs.clone());
3694 // Desugar ExprKind::Try
3696 ExprKind::Try(ref sub_expr) => {
3699 // match Try::into_result(<expr>) {
3700 // Ok(val) => #[allow(unreachable_code)] val,
3701 // Err(err) => #[allow(unreachable_code)]
3702 // // If there is an enclosing `catch {...}`
3703 // break 'catch_target Try::from_error(From::from(err)),
3705 // return Try::from_error(From::from(err)),
3709 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
3711 // Try::into_result(<expr>)
3714 let sub_expr = self.lower_expr(sub_expr);
3716 let path = &["ops", "Try", "into_result"];
3717 let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
3718 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
3721 // #[allow(unreachable_code)]
3723 // allow(unreachable_code)
3725 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
3726 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
3727 let uc_nested = attr::mk_nested_word_item(uc_ident);
3728 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
3730 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
3732 let attrs = vec![attr];
3734 // Ok(val) => #[allow(unreachable_code)] val,
3736 let val_ident = self.str_to_ident("val");
3737 let val_pat = self.pat_ident(e.span, val_ident);
3738 let val_expr = P(self.expr_ident_with_attrs(
3742 ThinVec::from(attrs.clone()),
3744 let ok_pat = self.pat_ok(e.span, val_pat);
3746 self.arm(hir_vec![ok_pat], val_expr)
3749 // Err(err) => #[allow(unreachable_code)]
3750 // return Try::from_error(From::from(err)),
3752 let err_ident = self.str_to_ident("err");
3753 let err_local = self.pat_ident(e.span, err_ident);
3755 let path = &["convert", "From", "from"];
3756 let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
3757 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
3759 self.expr_call(e.span, from, hir_vec![err_expr])
3762 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
3763 let thin_attrs = ThinVec::from(attrs);
3764 let catch_scope = self.catch_scopes.last().map(|x| *x);
3765 let ret_expr = if let Some(catch_node) = catch_scope {
3771 target_id: Ok(catch_node),
3773 Some(from_err_expr),
3778 P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
3781 let err_pat = self.pat_err(e.span, err_local);
3782 self.arm(hir_vec![err_pat], ret_expr)
3787 hir_vec![err_arm, ok_arm],
3788 hir::MatchSource::TryDesugar,
3792 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
3795 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3802 attrs: e.attrs.clone(),
3806 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
3807 SmallVector::one(match s.node {
3808 StmtKind::Local(ref l) => Spanned {
3809 node: hir::StmtDecl(
3811 node: hir::DeclLocal(self.lower_local(l)),
3814 self.lower_node_id(s.id).node_id,
3818 StmtKind::Item(ref it) => {
3819 // Can only use the ID once.
3820 let mut id = Some(s.id);
3821 return self.lower_item_id(it)
3823 .map(|item_id| Spanned {
3824 node: hir::StmtDecl(
3826 node: hir::DeclItem(item_id),
3830 .map(|id| self.lower_node_id(id).node_id)
3831 .unwrap_or_else(|| self.next_id().node_id),
3837 StmtKind::Expr(ref e) => Spanned {
3838 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3841 StmtKind::Semi(ref e) => Spanned {
3842 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3845 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
3849 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
3851 CaptureBy::Value => hir::CaptureByValue,
3852 CaptureBy::Ref => hir::CaptureByRef,
3856 /// If an `explicit_owner` is given, this method allocates the `HirId` in
3857 /// the address space of that item instead of the item currently being
3858 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
3859 /// lower a `Visibility` value although we haven't lowered the owning
3860 /// `ImplItem` in question yet.
3861 fn lower_visibility(
3864 explicit_owner: Option<NodeId>,
3865 ) -> hir::Visibility {
3867 VisibilityKind::Public => hir::Public,
3868 VisibilityKind::Crate(sugar) => hir::Visibility::Crate(sugar),
3869 VisibilityKind::Restricted { ref path, id, .. } => hir::Visibility::Restricted {
3870 path: P(self.lower_path(id, path, ParamMode::Explicit)),
3871 id: if let Some(owner) = explicit_owner {
3872 self.lower_node_id_with_owner(id, owner).node_id
3874 self.lower_node_id(id).node_id
3877 VisibilityKind::Inherited => hir::Inherited,
3881 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
3883 Defaultness::Default => hir::Defaultness::Default {
3884 has_value: has_value,
3886 Defaultness::Final => {
3888 hir::Defaultness::Final
3893 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3895 BlockCheckMode::Default => hir::DefaultBlock,
3896 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3900 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3902 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
3903 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
3904 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
3905 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
3909 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3911 CompilerGenerated => hir::CompilerGenerated,
3912 UserProvided => hir::UserProvided,
3916 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
3918 ImplPolarity::Positive => hir::ImplPolarity::Positive,
3919 ImplPolarity::Negative => hir::ImplPolarity::Negative,
3923 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3925 TraitBoundModifier::None => hir::TraitBoundModifier::None,
3926 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3930 // Helper methods for building HIR.
3932 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
3941 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
3943 id: self.next_id().node_id,
3947 is_shorthand: false,
3951 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
3952 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
3953 P(self.expr(span, expr_break, attrs))
3960 args: hir::HirVec<hir::Expr>,
3962 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
3965 fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
3966 self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
3969 fn expr_ident_with_attrs(
3974 attrs: ThinVec<Attribute>,
3976 let expr_path = hir::ExprPath(hir::QPath::Resolved(
3980 def: Def::Local(binding),
3981 segments: hir_vec![hir::PathSegment::from_name(id)],
3985 self.expr(span, expr_path, attrs)
3988 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
3989 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
3995 components: &[&str],
3996 attrs: ThinVec<Attribute>,
3998 let path = self.std_path(span, components, true);
4001 hir::ExprPath(hir::QPath::Resolved(None, P(path))),
4010 arms: hir::HirVec<hir::Arm>,
4011 source: hir::MatchSource,
4013 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
4016 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4017 self.expr(b.span, hir::ExprBlock(b, None), attrs)
4020 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4021 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
4024 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
4025 let LoweredNodeId { node_id, hir_id } = self.next_id();
4038 ex: Option<P<hir::Expr>>,
4040 source: hir::LocalSource,
4042 let LoweredNodeId { node_id, hir_id } = self.next_id();
4044 let local = P(hir::Local {
4051 attrs: ThinVec::new(),
4054 let decl = respan(sp, hir::DeclLocal(local));
4055 respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
4064 ) -> (hir::Stmt, NodeId) {
4065 let pat = if mutbl {
4066 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4068 self.pat_ident(sp, ident)
4070 let pat_id = pat.id;
4072 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4077 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4078 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4084 stmts: hir::HirVec<hir::Stmt>,
4085 expr: Option<P<hir::Expr>>,
4087 let LoweredNodeId { node_id, hir_id } = self.next_id();
4094 rules: hir::DefaultBlock,
4096 targeted_by_break: false,
4101 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4102 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4105 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4106 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4109 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4110 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4113 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4114 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4120 components: &[&str],
4121 subpats: hir::HirVec<P<hir::Pat>>,
4123 let path = self.std_path(span, components, true);
4124 let qpath = hir::QPath::Resolved(None, P(path));
4125 let pt = if subpats.is_empty() {
4126 hir::PatKind::Path(qpath)
4128 hir::PatKind::TupleStruct(qpath, subpats, None)
4133 fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
4134 self.pat_ident_binding_mode(span, name, hir::BindingAnnotation::Unannotated)
4137 fn pat_ident_binding_mode(
4141 bm: hir::BindingAnnotation,
4143 let LoweredNodeId { node_id, hir_id } = self.next_id();
4148 node: hir::PatKind::Binding(bm, node_id, Spanned { span, node: name }, None),
4153 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4154 self.pat(span, hir::PatKind::Wild)
4157 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4158 let LoweredNodeId { node_id, hir_id } = self.next_id();
4167 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4168 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4169 /// The path is also resolved according to `is_value`.
4170 fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
4172 .resolve_str_path(span, self.crate_root, components, is_value)
4175 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
4177 let node = match qpath {
4178 hir::QPath::Resolved(None, path) => {
4179 // Turn trait object paths into `TyTraitObject` instead.
4180 if let Def::Trait(_) = path.def {
4181 let principal = hir::PolyTraitRef {
4182 bound_generic_params: hir::HirVec::new(),
4183 trait_ref: hir::TraitRef {
4184 path: path.and_then(|path| path),
4190 // The original ID is taken by the `PolyTraitRef`,
4191 // so the `Ty` itself needs a different one.
4192 id = self.next_id();
4193 hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4195 hir::TyPath(hir::QPath::Resolved(None, path))
4198 _ => hir::TyPath(qpath),
4208 /// Invoked to create the lifetime argument for a type `&T`
4209 /// with no explicit lifetime.
4210 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4211 match self.anonymous_lifetime_mode {
4212 // Intercept when we are in an impl header and introduce an in-band lifetime.
4213 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4215 AnonymousLifetimeMode::CreateParameter => {
4216 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4218 id: self.next_id().node_id,
4224 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4228 /// Invoked to create the lifetime argument(s) for a path like
4229 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4230 /// sorts of cases are deprecated. This may therefore report a warning or an
4231 /// error, depending on the mode.
4232 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4233 match self.anonymous_lifetime_mode {
4234 // NB. We intentionally ignore the create-parameter mode here
4235 // and instead "pass through" to resolve-lifetimes, which will then
4236 // report an error. This is because we don't want to support
4237 // impl elision for deprecated forms like
4239 // impl Foo for std::cell::Ref<u32> // note lack of '_
4240 AnonymousLifetimeMode::CreateParameter => {}
4242 // This is the normal case.
4243 AnonymousLifetimeMode::PassThrough => {}
4247 .map(|_| self.new_implicit_lifetime(span))
4251 /// Invoked to create the lifetime argument(s) for an elided trait object
4252 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4253 /// when the bound is written, even if it is written with `'_` like in
4254 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4255 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4256 match self.anonymous_lifetime_mode {
4257 // NB. We intentionally ignore the create-parameter mode here.
4258 // and instead "pass through" to resolve-lifetimes, which will apply
4259 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4260 // do not act like other elided lifetimes. In other words, given this:
4262 // impl Foo for Box<dyn Debug>
4264 // we do not introduce a fresh `'_` to serve as the bound, but instead
4265 // ultimately translate to the equivalent of:
4267 // impl Foo for Box<dyn Debug + 'static>
4269 // `resolve_lifetime` has the code to make that happen.
4270 AnonymousLifetimeMode::CreateParameter => {}
4272 // This is the normal case.
4273 AnonymousLifetimeMode::PassThrough => {}
4276 self.new_implicit_lifetime(span)
4279 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4281 id: self.next_id().node_id,
4283 name: hir::LifetimeName::Implicit,
4287 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4288 self.sess.buffer_lint_with_diagnostic(
4289 builtin::BARE_TRAIT_OBJECTS,
4292 "trait objects without an explicit `dyn` are deprecated",
4293 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4297 fn wrap_in_try_constructor(
4299 method: &'static str,
4301 unstable_span: Span,
4303 let path = &["ops", "Try", method];
4304 let from_err = P(self.expr_std_path(unstable_span, path,
4306 P(self.expr_call(e.span, from_err, hir_vec![e]))
4310 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4311 // Sorting by span ensures that we get things in order within a
4312 // file, and also puts the files in a sensible order.
4313 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4314 body_ids.sort_by_key(|b| bodies[b].value.span);