1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Lowers the AST to the HIR.
13 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
14 //! much like a fold. Where lowering involves a bit more work things get more
15 //! interesting and there are some invariants you should know about. These mostly
16 //! concern spans and ids.
18 //! Spans are assigned to AST nodes during parsing and then are modified during
19 //! expansion to indicate the origin of a node and the process it went through
20 //! being expanded. Ids are assigned to AST nodes just before lowering.
22 //! For the simpler lowering steps, ids and spans should be preserved. Unlike
23 //! expansion we do not preserve the process of lowering in the spans, so spans
24 //! should not be modified here. When creating a new node (as opposed to
25 //! 'folding' an existing one), then you create a new id using `next_id()`.
27 //! You must ensure that ids are unique. That means that you should only use the
28 //! id from an AST node in a single HIR node (you can assume that AST node ids
29 //! are unique). Every new node must have a unique id. Avoid cloning HIR nodes.
30 //! If you do, you must then set the new node's id to a fresh one.
32 //! Spans are used for error messages and for tools to map semantics back to
33 //! source code. It is therefore not as important with spans as ids to be strict
34 //! about use (you can't break the compiler by screwing up a span). Obviously, a
35 //! HIR node can only have a single span. But multiple nodes can have the same
36 //! span and spans don't need to be kept in order, etc. Where code is preserved
37 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
38 //! new it is probably best to give a span for the whole AST node being lowered.
39 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
40 //! get confused if the spans from leaf AST nodes occur in multiple places
41 //! in the HIR, especially for multiple identifiers.
43 use dep_graph::DepGraph;
46 use hir::map::{DefKey, DefPathData, Definitions};
47 use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX};
48 use hir::def::{Def, PathResolution, PerNS};
50 use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES};
51 use middle::cstore::CrateStore;
52 use rustc_data_structures::indexed_vec::IndexVec;
54 use util::common::FN_OUTPUT_NAME;
55 use util::nodemap::{DefIdMap, FxHashMap, NodeMap};
57 use std::collections::{BTreeMap, HashSet};
65 use syntax::ext::hygiene::{Mark, SyntaxContext};
66 use syntax::print::pprust;
68 use syntax::codemap::{self, respan, CompilerDesugaringKind, Spanned};
69 use syntax::std_inject;
70 use syntax::symbol::{keywords, Symbol};
71 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
72 use syntax::parse::token::Token;
73 use syntax::util::small_vector::SmallVector;
74 use syntax::visit::{self, Visitor};
77 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
79 pub struct LoweringContext<'a> {
80 crate_root: Option<&'static str>,
82 // Use to assign ids to hir nodes that do not directly correspond to an ast node
85 cstore: &'a CrateStore,
87 resolver: &'a mut Resolver,
88 name_map: FxHashMap<Ident, Name>,
90 /// The items being lowered are collected here.
91 items: BTreeMap<NodeId, hir::Item>,
93 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
94 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
95 bodies: BTreeMap<hir::BodyId, hir::Body>,
96 exported_macros: Vec<hir::MacroDef>,
98 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
99 trait_auto_impl: BTreeMap<DefId, NodeId>,
103 catch_scopes: Vec<NodeId>,
104 loop_scopes: Vec<NodeId>,
105 is_in_loop_condition: bool,
106 is_in_trait_impl: bool,
108 /// What to do when we encounter either an "anonymous lifetime
109 /// reference". The term "anonymous" is meant to encompass both
110 /// `'_` lifetimes as well as fully elided cases where nothing is
111 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
112 anonymous_lifetime_mode: AnonymousLifetimeMode,
114 // This is a list of in-band type definitions being generated by
115 // Argument-position `impl Trait`.
116 // When traversing a signature such as `fn foo(x: impl Trait)`,
117 // we record `impl Trait` as a new type parameter, then later
118 // add it on to `foo`s generics.
119 in_band_ty_params: Vec<hir::GenericParam>,
121 // Used to create lifetime definitions from in-band lifetime usages.
122 // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
123 // When a named lifetime is encountered in a function or impl header and
124 // has not been defined
125 // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
126 // to this list. The results of this list are then added to the list of
127 // lifetime definitions in the corresponding impl or function generics.
128 lifetimes_to_define: Vec<(Span, hir::LifetimeName)>,
130 // Whether or not in-band lifetimes are being collected. This is used to
131 // indicate whether or not we're in a place where new lifetimes will result
132 // in in-band lifetime definitions, such a function or an impl header.
133 // This will always be false unless the `in_band_lifetimes` feature is
135 is_collecting_in_band_lifetimes: bool,
137 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
138 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
139 // against this list to see if it is already in-scope, or if a definition
140 // needs to be created for it.
141 in_scope_lifetimes: Vec<Name>,
143 type_def_lifetime_params: DefIdMap<usize>,
145 current_hir_id_owner: Vec<(DefIndex, u32)>,
146 item_local_id_counters: NodeMap<u32>,
147 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
151 /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
152 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
154 /// Obtain the resolution for a node id
155 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
157 /// Obtain the possible resolutions for the given `use` statement.
158 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
160 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
161 /// This should only return `None` during testing.
162 fn definitions(&mut self) -> &mut Definitions;
164 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
165 /// it based on `is_value`.
169 crate_root: Option<&str>,
175 #[derive(Clone, Copy, Debug)]
176 enum ImplTraitContext {
177 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
178 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
179 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
181 /// We store a DefId here so we can look up necessary information later
184 /// Treat `impl Trait` as shorthand for a new universal existential parameter.
185 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
186 /// equivalent to a fresh existential parameter like `abstract type T; fn foo() -> T`.
188 /// We store a DefId here so we can look up necessary information later
191 /// `impl Trait` is not accepted in this position.
198 dep_graph: &DepGraph,
200 resolver: &mut Resolver,
202 // We're constructing the HIR here; we don't care what we will
203 // read, since we haven't even constructed the *input* to
205 dep_graph.assert_ignored();
208 crate_root: std_inject::injected_crate_name(),
212 name_map: FxHashMap(),
213 items: BTreeMap::new(),
214 trait_items: BTreeMap::new(),
215 impl_items: BTreeMap::new(),
216 bodies: BTreeMap::new(),
217 trait_impls: BTreeMap::new(),
218 trait_auto_impl: BTreeMap::new(),
219 exported_macros: Vec::new(),
220 catch_scopes: Vec::new(),
221 loop_scopes: Vec::new(),
222 is_in_loop_condition: false,
223 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
224 type_def_lifetime_params: DefIdMap(),
225 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
226 item_local_id_counters: NodeMap(),
227 node_id_to_hir_id: IndexVec::new(),
229 is_in_trait_impl: false,
230 in_band_ty_params: Vec::new(),
231 lifetimes_to_define: Vec::new(),
232 is_collecting_in_band_lifetimes: false,
233 in_scope_lifetimes: Vec::new(),
237 #[derive(Copy, Clone, PartialEq, Eq)]
239 /// Any path in a type context.
241 /// The `module::Type` in `module::Type::method` in an expression.
246 struct LoweredNodeId {
251 enum ParenthesizedGenericArgs {
257 /// What to do when we encounter an **anonymous** lifetime
258 /// reference. Anonymous lifetime references come in two flavors. You
259 /// have implicit, or fully elided, references to lifetimes, like the
260 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
261 /// or `Ref<'_, T>`. These often behave the same, but not always:
263 /// - certain usages of implicit references are deprecated, like
264 /// `Ref<T>`, and we sometimes just give hard errors in those cases
266 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
267 /// the same as `Box<dyn Foo + '_>`.
269 /// We describe the effects of the various modes in terms of three cases:
271 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
272 /// of a `&` (e.g., the missing lifetime in something like `&T`)
273 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
274 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
275 /// elided bounds follow special rules. Note that this only covers
276 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
277 /// '_>` is a case of "modern" elision.
278 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
279 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
280 /// non-deprecated equivalent.
282 /// Currently, the handling of lifetime elision is somewhat spread out
283 /// between HIR lowering and -- as described below -- the
284 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
285 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
286 /// everything into HIR lowering.
287 #[derive(Copy, Clone)]
288 enum AnonymousLifetimeMode {
289 /// For **Modern** cases, create a new anonymous region parameter
290 /// and reference that.
292 /// For **Dyn Bound** cases, pass responsibility to
293 /// `resolve_lifetime` code.
295 /// For **Deprecated** cases, report an error.
298 /// Pass responsibility to `resolve_lifetime` code for all cases.
302 impl<'a> LoweringContext<'a> {
303 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
304 /// Full-crate AST visitor that inserts into a fresh
305 /// `LoweringContext` any information that may be
306 /// needed from arbitrary locations in the crate.
307 /// E.g. The number of lifetime generic parameters
308 /// declared for every type and trait definition.
309 struct MiscCollector<'lcx, 'interner: 'lcx> {
310 lctx: &'lcx mut LoweringContext<'interner>,
313 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
314 fn visit_item(&mut self, item: &'lcx Item) {
315 self.lctx.allocate_hir_id_counter(item.id, item);
318 ItemKind::Struct(_, ref generics)
319 | ItemKind::Union(_, ref generics)
320 | ItemKind::Enum(_, ref generics)
321 | ItemKind::Ty(_, ref generics)
322 | ItemKind::Trait(_, _, ref generics, ..) => {
323 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
327 .filter(|param| match param.kind {
328 ast::GenericParamKindAST::Lifetime { .. } => true,
332 self.lctx.type_def_lifetime_params.insert(def_id, count);
336 visit::walk_item(self, item);
339 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
340 self.lctx.allocate_hir_id_counter(item.id, item);
341 visit::walk_trait_item(self, item);
344 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
345 self.lctx.allocate_hir_id_counter(item.id, item);
346 visit::walk_impl_item(self, item);
350 struct ItemLowerer<'lcx, 'interner: 'lcx> {
351 lctx: &'lcx mut LoweringContext<'interner>,
354 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
355 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
357 F: FnOnce(&mut Self),
359 let old = self.lctx.is_in_trait_impl;
360 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
366 self.lctx.is_in_trait_impl = old;
370 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
371 fn visit_item(&mut self, item: &'lcx Item) {
372 let mut item_lowered = true;
373 self.lctx.with_hir_id_owner(item.id, |lctx| {
374 if let Some(hir_item) = lctx.lower_item(item) {
375 lctx.items.insert(item.id, hir_item);
377 item_lowered = false;
382 let item_lifetimes = match self.lctx.items.get(&item.id).unwrap().node {
383 hir::Item_::ItemImpl(_, _, _, ref generics, ..)
384 | hir::Item_::ItemTrait(_, _, ref generics, ..) => {
385 generics.params.clone()
390 self.lctx.with_parent_impl_lifetime_defs(&item_lifetimes, |this| {
391 let this = &mut ItemLowerer { lctx: this };
392 if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
393 this.with_trait_impl_ref(opt_trait_ref, |this| {
394 visit::walk_item(this, item)
397 visit::walk_item(this, item);
403 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
404 self.lctx.with_hir_id_owner(item.id, |lctx| {
405 let id = hir::TraitItemId { node_id: item.id };
406 let hir_item = lctx.lower_trait_item(item);
407 lctx.trait_items.insert(id, hir_item);
410 visit::walk_trait_item(self, item);
413 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
414 self.lctx.with_hir_id_owner(item.id, |lctx| {
415 let id = hir::ImplItemId { node_id: item.id };
416 let hir_item = lctx.lower_impl_item(item);
417 lctx.impl_items.insert(id, hir_item);
419 visit::walk_impl_item(self, item);
423 self.lower_node_id(CRATE_NODE_ID);
424 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
426 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
427 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
429 let module = self.lower_mod(&c.module);
430 let attrs = self.lower_attrs(&c.attrs);
431 let body_ids = body_ids(&self.bodies);
435 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
441 exported_macros: hir::HirVec::from(self.exported_macros),
443 trait_items: self.trait_items,
444 impl_items: self.impl_items,
447 trait_impls: self.trait_impls,
448 trait_auto_impl: self.trait_auto_impl,
452 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) {
453 if self.item_local_id_counters.insert(owner, 0).is_some() {
455 "Tried to allocate item_local_id_counter for {:?} twice",
459 // Always allocate the first HirId for the owner itself
460 self.lower_node_id_with_owner(owner, owner);
463 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
465 F: FnOnce(&mut Self) -> hir::HirId,
467 if ast_node_id == DUMMY_NODE_ID {
468 return LoweredNodeId {
469 node_id: DUMMY_NODE_ID,
470 hir_id: hir::DUMMY_HIR_ID,
474 let min_size = ast_node_id.as_usize() + 1;
476 if min_size > self.node_id_to_hir_id.len() {
477 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
480 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
482 if existing_hir_id == hir::DUMMY_HIR_ID {
483 // Generate a new HirId
484 let hir_id = alloc_hir_id(self);
485 self.node_id_to_hir_id[ast_node_id] = hir_id;
487 node_id: ast_node_id,
492 node_id: ast_node_id,
493 hir_id: existing_hir_id,
498 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
500 F: FnOnce(&mut Self) -> T,
502 let counter = self.item_local_id_counters
503 .insert(owner, HIR_ID_COUNTER_LOCKED)
505 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
506 self.current_hir_id_owner.push((def_index, counter));
508 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
510 debug_assert!(def_index == new_def_index);
511 debug_assert!(new_counter >= counter);
513 let prev = self.item_local_id_counters
514 .insert(owner, new_counter)
516 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
520 /// This method allocates a new HirId for the given NodeId and stores it in
521 /// the LoweringContext's NodeId => HirId map.
522 /// Take care not to call this method if the resulting HirId is then not
523 /// actually used in the HIR, as that would trigger an assertion in the
524 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
525 /// properly. Calling the method twice with the same NodeId is fine though.
526 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
527 self.lower_node_id_generic(ast_node_id, |this| {
528 let &mut (def_index, ref mut local_id_counter) =
529 this.current_hir_id_owner.last_mut().unwrap();
530 let local_id = *local_id_counter;
531 *local_id_counter += 1;
534 local_id: hir::ItemLocalId(local_id),
539 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
540 self.lower_node_id_generic(ast_node_id, |this| {
541 let local_id_counter = this
542 .item_local_id_counters
544 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
545 let local_id = *local_id_counter;
547 // We want to be sure not to modify the counter in the map while it
548 // is also on the stack. Otherwise we'll get lost updates when writing
549 // back from the stack to the map.
550 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
552 *local_id_counter += 1;
556 .opt_def_index(owner)
557 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
558 that do not belong to the current owner");
562 local_id: hir::ItemLocalId(local_id),
567 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
568 let body = hir::Body {
569 arguments: decl.map_or(hir_vec![], |decl| {
570 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
572 is_generator: self.is_generator,
576 self.bodies.insert(id, body);
580 fn next_id(&mut self) -> LoweredNodeId {
581 self.lower_node_id(self.sess.next_node_id())
584 fn expect_full_def(&mut self, id: NodeId) -> Def {
585 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
586 if pr.unresolved_segments() != 0 {
587 bug!("path not fully resolved: {:?}", pr);
593 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item=Def> {
594 self.resolver.get_import(id).present_items().map(|pr| {
595 if pr.unresolved_segments() != 0 {
596 bug!("path not fully resolved: {:?}", pr);
602 fn diagnostic(&self) -> &errors::Handler {
603 self.sess.diagnostic()
606 fn str_to_ident(&self, s: &'static str) -> Name {
610 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
611 let mark = Mark::fresh(Mark::root());
612 mark.set_expn_info(codemap::ExpnInfo {
614 callee: codemap::NameAndSpan {
615 format: codemap::CompilerDesugaring(reason),
617 allow_internal_unstable: true,
618 allow_internal_unsafe: false,
619 edition: codemap::hygiene::default_edition(),
622 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
625 fn with_anonymous_lifetime_mode<R>(
627 anonymous_lifetime_mode: AnonymousLifetimeMode,
628 op: impl FnOnce(&mut Self) -> R,
630 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
631 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
632 let result = op(self);
633 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
637 /// Creates a new hir::GenericParam for every new lifetime and
638 /// type parameter encountered while evaluating `f`. Definitions
639 /// are created with the parent provided. If no `parent_id` is
640 /// provided, no definitions will be returned.
642 /// Presuming that in-band lifetimes are enabled, then
643 /// `self.anonymous_lifetime_mode` will be updated to match the
644 /// argument while `f` is running (and restored afterwards).
645 fn collect_in_band_defs<T, F>(
648 anonymous_lifetime_mode: AnonymousLifetimeMode,
650 ) -> (Vec<hir::GenericParam>, T)
652 F: FnOnce(&mut LoweringContext) -> T,
654 assert!(!self.is_collecting_in_band_lifetimes);
655 assert!(self.lifetimes_to_define.is_empty());
656 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
658 self.is_collecting_in_band_lifetimes = self.sess.features_untracked().in_band_lifetimes;
659 if self.is_collecting_in_band_lifetimes {
660 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
663 assert!(self.in_band_ty_params.is_empty());
666 self.is_collecting_in_band_lifetimes = false;
667 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
669 let in_band_ty_params = self.in_band_ty_params.split_off(0);
670 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
672 let params = lifetimes_to_define
674 .map(|(span, hir_name)| {
675 let def_node_id = self.next_id().node_id;
677 // Get the name we'll use to make the def-path. Note
678 // that collisions are ok here and this shouldn't
679 // really show up for end-user.
680 let str_name = match hir_name {
681 hir::LifetimeName::Name(n) => n.as_str(),
682 hir::LifetimeName::Fresh(_) => keywords::UnderscoreLifetime.name().as_str(),
683 hir::LifetimeName::Implicit
684 | hir::LifetimeName::Underscore
685 | hir::LifetimeName::Static => {
686 span_bug!(span, "unexpected in-band lifetime name: {:?}", hir_name)
690 // Add a definition for the in-band lifetime def
691 self.resolver.definitions().create_def_with_parent(
694 DefPathData::LifetimeParam(str_name.as_interned_str()),
695 DefIndexAddressSpace::High,
703 pure_wrt_drop: false,
704 kind: hir::GenericParamKind::Lifetime {
706 bounds: vec![].into(),
708 lifetime_deprecated: hir::Lifetime {
716 .chain(in_band_ty_params.into_iter())
722 /// When there is a reference to some lifetime `'a`, and in-band
723 /// lifetimes are enabled, then we want to push that lifetime into
724 /// the vector of names to define later. In that case, it will get
725 /// added to the appropriate generics.
726 fn maybe_collect_in_band_lifetime(&mut self, span: Span, name: Name) {
727 if !self.is_collecting_in_band_lifetimes {
731 if self.in_scope_lifetimes.contains(&name) {
735 let hir_name = hir::LifetimeName::Name(name);
737 if self.lifetimes_to_define
739 .any(|(_, lt_name)| *lt_name == hir_name)
744 self.lifetimes_to_define.push((span, hir_name));
747 /// When we have either an elided or `'_` lifetime in an impl
748 /// header, we convert it to
749 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> hir::LifetimeName {
750 assert!(self.is_collecting_in_band_lifetimes);
751 let index = self.lifetimes_to_define.len();
752 let hir_name = hir::LifetimeName::Fresh(index);
753 self.lifetimes_to_define.push((span, hir_name));
757 // Evaluates `f` with the lifetimes in `params` in-scope.
758 // This is used to track which lifetimes have already been defined, and
759 // which are new in-band lifetimes that need to have a definition created
761 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &Vec<GenericParamAST>, f: F) -> T
763 F: FnOnce(&mut LoweringContext) -> T,
765 let old_len = self.in_scope_lifetimes.len();
766 let lt_def_names = params.iter().filter_map(|param| match param.kind {
767 GenericParamKindAST::Lifetime { .. } => Some(param.ident.name),
770 self.in_scope_lifetimes.extend(lt_def_names);
774 self.in_scope_lifetimes.truncate(old_len);
778 // Same as the method above, but accepts `hir::GenericParam`s
779 // instead of `ast::GenericParam`s.
780 // This should only be used with generics that have already had their
781 // in-band lifetimes added. In practice, this means that this function is
782 // only used when lowering a child item of a trait or impl.
783 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
784 params: &HirVec<hir::GenericParam>,
787 F: FnOnce(&mut LoweringContext) -> T,
789 let old_len = self.in_scope_lifetimes.len();
790 let lt_def_names = params.iter().filter_map(|param| match param.kind {
791 hir::GenericParamKind::Lifetime { .. } => Some(param.name()),
794 self.in_scope_lifetimes.extend(lt_def_names);
798 self.in_scope_lifetimes.truncate(old_len);
802 /// Appends in-band lifetime defs and argument-position `impl
803 /// Trait` defs to the existing set of generics.
805 /// Presuming that in-band lifetimes are enabled, then
806 /// `self.anonymous_lifetime_mode` will be updated to match the
807 /// argument while `f` is running (and restored afterwards).
808 fn add_in_band_defs<F, T>(
812 anonymous_lifetime_mode: AnonymousLifetimeMode,
814 ) -> (hir::Generics, T)
816 F: FnOnce(&mut LoweringContext) -> T,
818 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
821 let itctx = ImplTraitContext::Universal(parent_id);
822 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
823 (this.lower_generics(generics, itctx), f(this))
828 lowered_generics.params = lowered_generics
835 (lowered_generics, res)
838 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
840 F: FnOnce(&mut LoweringContext) -> T,
842 let len = self.catch_scopes.len();
843 self.catch_scopes.push(catch_id);
845 let result = f(self);
848 self.catch_scopes.len(),
849 "catch scopes should be added and removed in stack order"
852 self.catch_scopes.pop().unwrap();
857 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
859 F: FnOnce(&mut LoweringContext) -> hir::Expr,
861 let prev = mem::replace(&mut self.is_generator, false);
862 let result = f(self);
863 let r = self.record_body(result, decl);
864 self.is_generator = prev;
868 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
870 F: FnOnce(&mut LoweringContext) -> T,
872 // We're no longer in the base loop's condition; we're in another loop.
873 let was_in_loop_condition = self.is_in_loop_condition;
874 self.is_in_loop_condition = false;
876 let len = self.loop_scopes.len();
877 self.loop_scopes.push(loop_id);
879 let result = f(self);
882 self.loop_scopes.len(),
883 "Loop scopes should be added and removed in stack order"
886 self.loop_scopes.pop().unwrap();
888 self.is_in_loop_condition = was_in_loop_condition;
893 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
895 F: FnOnce(&mut LoweringContext) -> T,
897 let was_in_loop_condition = self.is_in_loop_condition;
898 self.is_in_loop_condition = true;
900 let result = f(self);
902 self.is_in_loop_condition = was_in_loop_condition;
907 fn with_new_scopes<T, F>(&mut self, f: F) -> T
909 F: FnOnce(&mut LoweringContext) -> T,
911 let was_in_loop_condition = self.is_in_loop_condition;
912 self.is_in_loop_condition = false;
914 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
915 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
916 let result = f(self);
917 self.catch_scopes = catch_scopes;
918 self.loop_scopes = loop_scopes;
920 self.is_in_loop_condition = was_in_loop_condition;
925 fn def_key(&mut self, id: DefId) -> DefKey {
927 self.resolver.definitions().def_key(id.index)
929 self.cstore.def_key(id)
933 fn lower_ident(&mut self, ident: Ident) -> Name {
934 let ident = ident.modern();
935 if ident.span.ctxt() == SyntaxContext::empty() {
940 .or_insert_with(|| Symbol::from_ident(ident))
943 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
944 label.map(|label| hir::Label {
945 name: label.ident.name,
946 span: label.ident.span,
950 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
952 Some((id, label)) => {
953 let target_id = if let Def::Label(loop_id) = self.expect_full_def(id) {
954 Ok(self.lower_node_id(loop_id).node_id)
956 Err(hir::LoopIdError::UnresolvedLabel)
959 label: self.lower_label(Some(label)),
964 let target_id = self.loop_scopes
966 .map(|innermost_loop_id| *innermost_loop_id)
967 .map(|id| Ok(self.lower_node_id(id).node_id))
968 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
979 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
982 .map(|a| self.lower_attr(a))
987 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
991 path: attr.path.clone(),
992 tokens: self.lower_token_stream(attr.tokens.clone()),
993 is_sugared_doc: attr.is_sugared_doc,
998 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1001 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1005 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1007 TokenTree::Token(span, token) => self.lower_token(token, span),
1008 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1011 delim: delimited.delim,
1012 tts: self.lower_token_stream(delimited.tts.into()).into(),
1018 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1020 Token::Interpolated(_) => {}
1021 other => return TokenTree::Token(span, other).into(),
1024 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1025 self.lower_token_stream(tts)
1028 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1030 attrs: self.lower_attrs(&arm.attrs),
1031 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1032 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1033 body: P(self.lower_expr(&arm.body)),
1037 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1039 id: self.lower_node_id(b.id).node_id,
1040 name: self.lower_ident(b.ident),
1041 ty: self.lower_ty(&b.ty, itctx),
1046 fn lower_generic_arg(&mut self,
1047 arg: &ast::GenericArgAST,
1048 itctx: ImplTraitContext)
1049 -> hir::GenericArg {
1051 ast::GenericArgAST::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1052 ast::GenericArgAST::Type(ty) => GenericArg::Type(self.lower_ty(&ty, itctx)),
1056 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1057 let kind = match t.node {
1058 TyKind::Infer => hir::TyInfer,
1059 TyKind::Err => hir::TyErr,
1060 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty, itctx)),
1061 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt, itctx)),
1062 TyKind::Rptr(ref region, ref mt) => {
1063 let span = t.span.shrink_to_lo();
1064 let lifetime = match *region {
1065 Some(ref lt) => self.lower_lifetime(lt),
1066 None => self.elided_ref_lifetime(span),
1068 hir::TyRptr(lifetime, self.lower_mt(mt, itctx))
1070 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1073 this.with_anonymous_lifetime_mode(
1074 AnonymousLifetimeMode::PassThrough,
1076 hir::TyBareFn(P(hir::BareFnTy {
1077 generic_params: this.lower_generic_params(
1080 ImplTraitContext::Disallowed,
1082 unsafety: this.lower_unsafety(f.unsafety),
1084 decl: this.lower_fn_decl(&f.decl, None, false),
1085 arg_names: this.lower_fn_args_to_names(&f.decl),
1091 TyKind::Never => hir::TyNever,
1092 TyKind::Tup(ref tys) => {
1093 hir::TyTup(tys.iter().map(|ty| self.lower_ty(ty, itctx)).collect())
1095 TyKind::Paren(ref ty) => {
1096 return self.lower_ty(ty, itctx);
1098 TyKind::Path(ref qself, ref path) => {
1099 let id = self.lower_node_id(t.id);
1100 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1101 let ty = self.ty_path(id, t.span, qpath);
1102 if let hir::TyTraitObject(..) = ty.node {
1103 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1107 TyKind::ImplicitSelf => hir::TyPath(hir::QPath::Resolved(
1110 def: self.expect_full_def(t.id),
1111 segments: hir_vec![hir::PathSegment::from_name(keywords::SelfType.name())],
1115 TyKind::Array(ref ty, ref length) => {
1116 hir::TyArray(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1118 TyKind::Typeof(ref expr) => {
1119 hir::TyTypeof(self.lower_anon_const(expr))
1121 TyKind::TraitObject(ref bounds, kind) => {
1122 let mut lifetime_bound = None;
1125 .filter_map(|bound| match *bound {
1126 TraitTyParamBound(ref ty, TraitBoundModifier::None) => {
1127 Some(self.lower_poly_trait_ref(ty, itctx))
1129 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
1130 RegionTyParamBound(ref lifetime) => {
1131 if lifetime_bound.is_none() {
1132 lifetime_bound = Some(self.lower_lifetime(lifetime));
1138 let lifetime_bound =
1139 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1140 if kind != TraitObjectSyntax::Dyn {
1141 self.maybe_lint_bare_trait(t.span, t.id, false);
1143 hir::TyTraitObject(bounds, lifetime_bound)
1145 TyKind::ImplTrait(ref bounds) => {
1148 ImplTraitContext::Existential(fn_def_id) => {
1150 // We need to manually repeat the code of `next_id` because the lowering
1151 // needs to happen while the owner_id is pointing to the item itself,
1152 // because items are their own owners
1153 let exist_ty_node_id = self.sess.next_node_id();
1155 // Make sure we know that some funky desugaring has been going on here.
1156 // This is a first: there is code in other places like for loop
1157 // desugaring that explicitly states that we don't want to track that.
1158 // Not tracking it makes lints in rustc and clippy very fragile as
1159 // frequently opened issues show.
1160 let exist_ty_span = self.allow_internal_unstable(
1161 CompilerDesugaringKind::ExistentialReturnType,
1165 // Pull a new definition from the ether
1166 let exist_ty_def_index = self
1169 .create_def_with_parent(
1172 DefPathData::ExistentialImplTrait,
1173 DefIndexAddressSpace::High,
1178 // the `t` is just for printing debug messages
1179 self.allocate_hir_id_counter(exist_ty_node_id, t);
1181 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1182 lctx.lower_bounds(bounds, itctx)
1185 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1191 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1192 let exist_ty_item_kind = hir::ItemExistential(hir::ExistTy {
1193 generics: hir::Generics {
1194 params: lifetime_defs,
1195 where_clause: hir::WhereClause {
1196 id: lctx.next_id().node_id,
1197 predicates: Vec::new().into(),
1202 impl_trait_fn: Some(fn_def_id),
1204 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1205 // Generate an `existential type Foo: Trait;` declaration
1206 trace!("creating existential type with id {:#?}", exist_ty_id);
1207 // Set the name to `impl Bound1 + Bound2`
1208 let exist_ty_name = Symbol::intern(&pprust::ty_to_string(t));
1210 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1211 let exist_ty_item = hir::Item {
1212 id: exist_ty_id.node_id,
1213 hir_id: exist_ty_id.hir_id,
1214 name: exist_ty_name,
1215 attrs: Default::default(),
1216 node: exist_ty_item_kind,
1217 vis: hir::Visibility::Inherited,
1218 span: exist_ty_span,
1221 // Insert the item into the global list. This usually happens
1222 // automatically for all AST items. But this existential type item
1223 // does not actually exist in the AST.
1224 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1226 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1227 hir::TyImplTraitExistential(
1229 id: exist_ty_id.node_id
1231 DefId::local(exist_ty_def_index),
1236 ImplTraitContext::Universal(def_id) => {
1237 let def_node_id = self.next_id().node_id;
1239 // Add a definition for the in-band TyParam
1240 let def_index = self.resolver.definitions().create_def_with_parent(
1243 DefPathData::UniversalImplTrait,
1244 DefIndexAddressSpace::High,
1249 let hir_bounds = self.lower_bounds(bounds, itctx);
1250 // Set the name to `impl Bound1 + Bound2`
1251 let name = Symbol::intern(&pprust::ty_to_string(t));
1252 self.in_band_ty_params.push(hir::GenericParam {
1255 pure_wrt_drop: false,
1256 kind: hir::GenericParamKind::Type {
1260 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1265 hir::TyPath(hir::QPath::Resolved(
1269 def: Def::TyParam(DefId::local(def_index)),
1270 segments: hir_vec![hir::PathSegment::from_name(name)],
1274 ImplTraitContext::Disallowed => {
1279 "`impl Trait` not allowed outside of function \
1280 and inherent method return types"
1286 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1289 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1298 fn lifetimes_from_impl_trait_bounds(
1300 exist_ty_id: NodeId,
1301 parent_index: DefIndex,
1302 bounds: &hir::TyParamBounds,
1303 ) -> (HirVec<hir::Lifetime>, HirVec<hir::GenericParam>) {
1304 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1305 // appear in the bounds, excluding lifetimes that are created within the bounds.
1306 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1307 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1308 context: &'r mut LoweringContext<'a>,
1310 exist_ty_id: NodeId,
1311 collect_elided_lifetimes: bool,
1312 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1313 already_defined_lifetimes: HashSet<hir::LifetimeName>,
1314 output_lifetimes: Vec<hir::Lifetime>,
1315 output_lifetime_params: Vec<hir::GenericParam>,
1318 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1319 fn nested_visit_map<'this>(
1321 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1322 hir::intravisit::NestedVisitorMap::None
1325 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1326 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1327 if parameters.parenthesized {
1328 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1329 self.collect_elided_lifetimes = false;
1330 hir::intravisit::walk_generic_args(self, span, parameters);
1331 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1333 hir::intravisit::walk_generic_args(self, span, parameters);
1337 fn visit_ty(&mut self, t: &'v hir::Ty) {
1338 // Don't collect elided lifetimes used inside of `fn()` syntax
1339 if let &hir::Ty_::TyBareFn(_) = &t.node {
1340 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1341 self.collect_elided_lifetimes = false;
1343 // Record the "stack height" of `for<'a>` lifetime bindings
1344 // to be able to later fully undo their introduction.
1345 let old_len = self.currently_bound_lifetimes.len();
1346 hir::intravisit::walk_ty(self, t);
1347 self.currently_bound_lifetimes.truncate(old_len);
1349 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1351 hir::intravisit::walk_ty(self, t);
1355 fn visit_poly_trait_ref(
1357 trait_ref: &'v hir::PolyTraitRef,
1358 modifier: hir::TraitBoundModifier,
1360 // Record the "stack height" of `for<'a>` lifetime bindings
1361 // to be able to later fully undo their introduction.
1362 let old_len = self.currently_bound_lifetimes.len();
1363 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1364 self.currently_bound_lifetimes.truncate(old_len);
1367 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1368 // Record the introduction of 'a in `for<'a> ...`
1369 if let hir::GenericParamKind::Lifetime { name, .. } = param.kind {
1370 // Introduce lifetimes one at a time so that we can handle
1371 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1372 self.currently_bound_lifetimes.push(name);
1375 hir::intravisit::walk_generic_param(self, param);
1378 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1379 let name = match lifetime.name {
1380 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1381 if self.collect_elided_lifetimes {
1382 // Use `'_` for both implicit and underscore lifetimes in
1383 // `abstract type Foo<'_>: SomeTrait<'_>;`
1384 hir::LifetimeName::Underscore
1389 name @ hir::LifetimeName::Fresh(_) => name,
1390 name @ hir::LifetimeName::Name(_) => name,
1391 hir::LifetimeName::Static => return,
1394 if !self.currently_bound_lifetimes.contains(&name)
1395 && !self.already_defined_lifetimes.contains(&name)
1397 self.already_defined_lifetimes.insert(name);
1399 self.output_lifetimes.push(hir::Lifetime {
1400 id: self.context.next_id().node_id,
1401 span: lifetime.span,
1405 // We need to manually create the ids here, because the
1406 // definitions will go into the explicit `existential type`
1407 // declaration and thus need to have their owner set to that item
1408 let def_node_id = self.context.sess.next_node_id();
1409 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1410 self.context.resolver.definitions().create_def_with_parent(
1413 DefPathData::LifetimeParam(name.name().as_interned_str()),
1414 DefIndexAddressSpace::High,
1419 self.output_lifetime_params.push(hir::GenericParam {
1421 span: lifetime.span,
1422 pure_wrt_drop: false,
1423 kind: hir::GenericParamKind::Lifetime {
1425 bounds: vec![].into(),
1427 lifetime_deprecated: hir::Lifetime {
1429 span: lifetime.span,
1438 let mut lifetime_collector = ImplTraitLifetimeCollector {
1440 parent: parent_index,
1442 collect_elided_lifetimes: true,
1443 currently_bound_lifetimes: Vec::new(),
1444 already_defined_lifetimes: HashSet::new(),
1445 output_lifetimes: Vec::new(),
1446 output_lifetime_params: Vec::new(),
1449 for bound in bounds {
1450 hir::intravisit::walk_ty_param_bound(&mut lifetime_collector, &bound);
1454 lifetime_collector.output_lifetimes.into(),
1455 lifetime_collector.output_lifetime_params.into(),
1459 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1464 .map(|x| self.lower_foreign_item(x))
1469 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1476 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1478 node: hir::Variant_ {
1479 name: v.node.ident.name,
1480 attrs: self.lower_attrs(&v.node.attrs),
1481 data: self.lower_variant_data(&v.node.data),
1482 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1491 qself: &Option<QSelf>,
1493 param_mode: ParamMode,
1494 itctx: ImplTraitContext,
1496 let qself_position = qself.as_ref().map(|q| q.position);
1497 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx));
1499 let resolution = self.resolver
1501 .unwrap_or(PathResolution::new(Def::Err));
1503 let proj_start = p.segments.len() - resolution.unresolved_segments();
1504 let path = P(hir::Path {
1505 def: resolution.base_def(),
1506 segments: p.segments[..proj_start]
1509 .map(|(i, segment)| {
1510 let param_mode = match (qself_position, param_mode) {
1511 (Some(j), ParamMode::Optional) if i < j => {
1512 // This segment is part of the trait path in a
1513 // qualified path - one of `a`, `b` or `Trait`
1514 // in `<X as a::b::Trait>::T::U::method`.
1520 // Figure out if this is a type/trait segment,
1521 // which may need lifetime elision performed.
1522 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1523 krate: def_id.krate,
1524 index: this.def_key(def_id).parent.expect("missing parent"),
1526 let type_def_id = match resolution.base_def() {
1527 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1528 Some(parent_def_id(self, def_id))
1530 Def::Variant(def_id) if i + 1 == proj_start => {
1531 Some(parent_def_id(self, def_id))
1534 | Def::Union(def_id)
1536 | Def::TyAlias(def_id)
1537 | Def::Trait(def_id) if i + 1 == proj_start =>
1543 let parenthesized_generic_args = match resolution.base_def() {
1544 // `a::b::Trait(Args)`
1545 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1546 // `a::b::Trait(Args)::TraitItem`
1547 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1548 if i + 2 == proj_start =>
1550 ParenthesizedGenericArgs::Ok
1552 // Avoid duplicated errors
1553 Def::Err => ParenthesizedGenericArgs::Ok,
1559 | Def::Variant(..) if i + 1 == proj_start =>
1561 ParenthesizedGenericArgs::Err
1563 // A warning for now, for compatibility reasons
1564 _ => ParenthesizedGenericArgs::Warn,
1567 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1568 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1571 assert!(!def_id.is_local());
1573 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1574 let n = item_generics.own_counts().lifetimes;
1575 self.type_def_lifetime_params.insert(def_id, n);
1578 self.lower_path_segment(
1583 parenthesized_generic_args,
1591 // Simple case, either no projections, or only fully-qualified.
1592 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1593 if resolution.unresolved_segments() == 0 {
1594 return hir::QPath::Resolved(qself, path);
1597 // Create the innermost type that we're projecting from.
1598 let mut ty = if path.segments.is_empty() {
1599 // If the base path is empty that means there exists a
1600 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1601 qself.expect("missing QSelf for <T>::...")
1603 // Otherwise, the base path is an implicit `Self` type path,
1604 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1605 // `<I as Iterator>::Item::default`.
1606 let new_id = self.next_id();
1607 self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))
1610 // Anything after the base path are associated "extensions",
1611 // out of which all but the last one are associated types,
1612 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1613 // * base path is `std::vec::Vec<T>`
1614 // * "extensions" are `IntoIter`, `Item` and `clone`
1615 // * type nodes are:
1616 // 1. `std::vec::Vec<T>` (created above)
1617 // 2. `<std::vec::Vec<T>>::IntoIter`
1618 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1619 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1620 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1621 let segment = P(self.lower_path_segment(
1626 ParenthesizedGenericArgs::Warn,
1629 let qpath = hir::QPath::TypeRelative(ty, segment);
1631 // It's finished, return the extension of the right node type.
1632 if i == p.segments.len() - 1 {
1636 // Wrap the associated extension in another type node.
1637 let new_id = self.next_id();
1638 ty = self.ty_path(new_id, p.span, qpath);
1641 // Should've returned in the for loop above.
1644 "lower_qpath: no final extension segment in {}..{}",
1650 fn lower_path_extra(
1655 param_mode: ParamMode,
1659 segments: p.segments
1662 self.lower_path_segment(
1667 ParenthesizedGenericArgs::Err,
1668 ImplTraitContext::Disallowed,
1671 .chain(name.map(|name| hir::PathSegment::from_name(name)))
1677 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1678 let def = self.expect_full_def(id);
1679 self.lower_path_extra(def, p, None, param_mode)
1682 fn lower_path_segment(
1685 segment: &PathSegment,
1686 param_mode: ParamMode,
1687 expected_lifetimes: usize,
1688 parenthesized_generic_args: ParenthesizedGenericArgs,
1689 itctx: ImplTraitContext,
1690 ) -> hir::PathSegment {
1691 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1692 let msg = "parenthesized parameters may only be used with a trait";
1693 match **generic_args {
1694 GenericArgs::AngleBracketed(ref data) => {
1695 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1697 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1698 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1699 ParenthesizedGenericArgs::Warn => {
1700 self.sess.buffer_lint(
1701 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1706 (hir::GenericArgs::none(), true)
1708 ParenthesizedGenericArgs::Err => {
1709 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1710 .span_label(data.span, "only traits may use parentheses")
1712 (hir::GenericArgs::none(), true)
1717 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1720 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1721 GenericArg::Lifetime(_) => true,
1724 if !generic_args.parenthesized && !has_lifetimes {
1726 self.elided_path_lifetimes(path_span, expected_lifetimes)
1728 .map(|lt| GenericArg::Lifetime(lt))
1729 .chain(generic_args.args.into_iter())
1733 hir::PathSegment::new(
1734 self.lower_ident(segment.ident),
1740 fn lower_angle_bracketed_parameter_data(
1742 data: &AngleBracketedArgs,
1743 param_mode: ParamMode,
1744 itctx: ImplTraitContext,
1745 ) -> (hir::GenericArgs, bool) {
1746 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1747 let has_types = args.iter().any(|arg| match arg {
1748 GenericArgAST::Type(_) => true,
1752 args: args.iter().map(|a| self.lower_generic_arg(a, itctx)).collect(),
1753 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(),
1754 parenthesized: false,
1756 !has_types && param_mode == ParamMode::Optional)
1759 fn lower_parenthesized_parameter_data(
1761 data: &ParenthesizedParameterData,
1762 ) -> (hir::PathParameters, bool) {
1763 // Switch to `PassThrough` mode for anonymous lifetimes: this
1764 // means that we permit things like `&Ref<T>`, where `Ref` has
1765 // a hidden lifetime parameter. This is needed for backwards
1766 // compatibility, even in contexts like an impl header where
1767 // we generally don't permit such things (see #51008).
1768 self.with_anonymous_lifetime_mode(
1769 AnonymousLifetimeMode::PassThrough,
1771 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1772 let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
1773 let inputs = inputs.iter().map(|ty| this.lower_ty(ty, DISALLOWED)).collect();
1774 let mk_tup = |this: &mut Self, tys, span| {
1775 let LoweredNodeId { node_id, hir_id } = this.next_id();
1776 P(hir::Ty { node: hir::TyTup(tys), id: node_id, hir_id, span })
1781 parameters: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1784 id: this.next_id().node_id,
1785 name: Symbol::intern(FN_OUTPUT_NAME),
1788 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1789 .unwrap_or_else(|| mk_tup(this, hir::HirVec::new(), span)),
1790 span: output.as_ref().map_or(span, |ty| ty.span),
1793 parenthesized: true,
1801 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1802 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1808 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1809 pat: self.lower_pat(&l.pat),
1810 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1812 attrs: l.attrs.clone(),
1813 source: hir::LocalSource::Normal,
1817 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1819 Mutability::Mutable => hir::MutMutable,
1820 Mutability::Immutable => hir::MutImmutable,
1824 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1825 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1829 pat: self.lower_pat(&arg.pat),
1833 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Spanned<Name>> {
1836 .map(|arg| match arg.pat.node {
1837 PatKind::Ident(_, ident, None) => respan(ident.span, ident.name),
1838 _ => respan(arg.pat.span, keywords::Invalid.name()),
1846 fn_def_id: Option<DefId>,
1847 impl_trait_return_allow: bool,
1848 ) -> P<hir::FnDecl> {
1849 // NOTE: The two last parameters here have to do with impl Trait. If fn_def_id is Some,
1850 // then impl Trait arguments are lowered into generic parameters on the given
1851 // fn_def_id, otherwise impl Trait is disallowed. (for now)
1853 // Furthermore, if impl_trait_return_allow is true, then impl Trait may be used in
1854 // return positions as well. This guards against trait declarations and their impls
1855 // where impl Trait is disallowed. (again for now)
1860 if let Some(def_id) = fn_def_id {
1861 self.lower_ty(&arg.ty, ImplTraitContext::Universal(def_id))
1863 self.lower_ty(&arg.ty, ImplTraitContext::Disallowed)
1867 output: match decl.output {
1868 FunctionRetTy::Ty(ref ty) => match fn_def_id {
1869 Some(def_id) if impl_trait_return_allow => {
1870 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1872 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1874 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1876 variadic: decl.variadic,
1877 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1878 TyKind::ImplicitSelf => true,
1879 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1885 fn lower_ty_param_bound(
1888 itctx: ImplTraitContext,
1889 ) -> hir::TyParamBound {
1891 TraitTyParamBound(ref ty, modifier) => hir::TraitTyParamBound(
1892 self.lower_poly_trait_ref(ty, itctx),
1893 self.lower_trait_bound_modifier(modifier),
1895 RegionTyParamBound(ref lifetime) => {
1896 hir::RegionTyParamBound(self.lower_lifetime(lifetime))
1901 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1902 let span = l.ident.span;
1903 match self.lower_ident(l.ident) {
1904 x if x == "'static" => self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
1905 x if x == "'_" => match self.anonymous_lifetime_mode {
1906 AnonymousLifetimeMode::CreateParameter => {
1907 let fresh_name = self.collect_fresh_in_band_lifetime(span);
1908 self.new_named_lifetime(l.id, span, fresh_name)
1911 AnonymousLifetimeMode::PassThrough => {
1912 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
1916 self.maybe_collect_in_band_lifetime(span, name);
1917 self.new_named_lifetime(l.id, span, hir::LifetimeName::Name(name))
1922 fn new_named_lifetime(
1926 name: hir::LifetimeName,
1927 ) -> hir::Lifetime {
1929 id: self.lower_node_id(id).node_id,
1935 fn lower_generic_params(
1937 params: &Vec<GenericParamAST>,
1938 add_bounds: &NodeMap<Vec<TyParamBound>>,
1939 itctx: ImplTraitContext,
1940 ) -> hir::HirVec<hir::GenericParam> {
1941 params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect()
1944 fn lower_generic_param(&mut self,
1945 param: &GenericParamAST,
1946 add_bounds: &NodeMap<Vec<TyParamBound>>,
1947 itctx: ImplTraitContext)
1948 -> hir::GenericParam {
1950 GenericParamKindAST::Lifetime { ref bounds, ref lifetime, .. } => {
1951 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
1952 self.is_collecting_in_band_lifetimes = false;
1954 let lifetime = self.lower_lifetime(lifetime);
1955 let param = hir::GenericParam {
1957 span: lifetime.span,
1958 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
1959 kind: hir::GenericParamKind::Lifetime {
1960 name: lifetime.name,
1961 bounds: bounds.iter().map(|lt| self.lower_lifetime(lt)).collect(),
1963 lifetime_deprecated: lifetime,
1967 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
1971 GenericParamKindAST::Type { ref bounds, ref default } => {
1972 let mut name = self.lower_ident(param.ident);
1974 // Don't expose `Self` (recovered "keyword used as ident" parse error).
1975 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
1976 // Instead, use gensym("Self") to create a distinct name that looks the same.
1977 if name == keywords::SelfType.name() {
1978 name = Symbol::gensym("Self");
1981 let mut bounds = self.lower_bounds(bounds, itctx);
1982 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
1983 if !add_bounds.is_empty() {
1984 bounds = bounds.into_iter()
1985 .chain(self.lower_bounds(add_bounds, itctx).into_iter())
1990 id: self.lower_node_id(param.id).node_id,
1991 span: param.ident.span,
1992 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
1993 kind: hir::GenericParamKind::Type {
1996 default: default.as_ref().map(|x| {
1997 self.lower_ty(x, ImplTraitContext::Disallowed)
1999 synthetic: param.attrs.iter()
2000 .filter(|attr| attr.check_name("rustc_synthetic"))
2001 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2003 attrs: self.lower_attrs(¶m.attrs),
2012 generics: &Generics,
2013 itctx: ImplTraitContext)
2016 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2017 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2018 // paths where report_error is called are also the only paths that advance to after
2019 // the match statement, so the error reporting could probably just be moved there.
2020 let mut add_bounds = NodeMap();
2021 for pred in &generics.where_clause.predicates {
2022 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2023 'next_bound: for bound in &bound_pred.bounds {
2024 if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
2025 let report_error = |this: &mut Self| {
2026 this.diagnostic().span_err(
2027 bound_pred.bounded_ty.span,
2028 "`?Trait` bounds are only permitted at the \
2029 point where a type parameter is declared",
2032 // Check if the where clause type is a plain type parameter.
2033 match bound_pred.bounded_ty.node {
2034 TyKind::Path(None, ref path)
2035 if path.segments.len() == 1
2036 && bound_pred.bound_generic_params.is_empty() =>
2038 if let Some(Def::TyParam(def_id)) = self.resolver
2039 .get_resolution(bound_pred.bounded_ty.id)
2040 .map(|d| d.base_def())
2042 if let Some(node_id) =
2043 self.resolver.definitions().as_local_node_id(def_id)
2045 for param in &generics.params {
2047 GenericParamKindAST::Type { .. } => {
2048 if node_id == param.id {
2049 add_bounds.entry(param.id)
2050 .or_insert(Vec::new())
2051 .push(bound.clone());
2052 continue 'next_bound;
2062 _ => report_error(self),
2070 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2071 where_clause: self.lower_where_clause(&generics.where_clause),
2072 span: generics.span,
2076 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2078 id: self.lower_node_id(wc.id).node_id,
2079 predicates: wc.predicates
2081 .map(|predicate| self.lower_where_predicate(predicate))
2086 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2088 WherePredicate::BoundPredicate(WhereBoundPredicate {
2089 ref bound_generic_params,
2094 self.with_in_scope_lifetime_defs(
2095 &bound_generic_params,
2097 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2098 bound_generic_params: this.lower_generic_params(
2099 bound_generic_params,
2101 ImplTraitContext::Disallowed,
2103 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2106 .filter_map(|bound| match *bound {
2107 // Ignore `?Trait` bounds.
2108 // Tthey were copied into type parameters already.
2109 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
2110 _ => Some(this.lower_ty_param_bound(
2112 ImplTraitContext::Disallowed,
2121 WherePredicate::RegionPredicate(WhereRegionPredicate {
2125 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2127 lifetime: self.lower_lifetime(lifetime),
2130 .map(|bound| self.lower_lifetime(bound))
2133 WherePredicate::EqPredicate(WhereEqPredicate {
2138 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2139 id: self.lower_node_id(id).node_id,
2140 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2141 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2147 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2149 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2153 .map(|f| self.lower_struct_field(f))
2155 self.lower_node_id(id).node_id,
2157 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2161 .map(|f| self.lower_struct_field(f))
2163 self.lower_node_id(id).node_id,
2165 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2169 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2170 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2171 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2172 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2176 ref_id: self.lower_node_id(p.ref_id).node_id,
2180 fn lower_poly_trait_ref(
2183 itctx: ImplTraitContext,
2184 ) -> hir::PolyTraitRef {
2185 let bound_generic_params =
2186 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx);
2187 let trait_ref = self.with_parent_impl_lifetime_defs(
2188 &bound_generic_params,
2189 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2193 bound_generic_params,
2199 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2202 id: self.lower_node_id(f.id).node_id,
2203 ident: match f.ident {
2204 Some(ident) => ident,
2205 // FIXME(jseyfried) positional field hygiene
2206 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2208 vis: self.lower_visibility(&f.vis, None),
2209 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2210 attrs: self.lower_attrs(&f.attrs),
2214 fn lower_field(&mut self, f: &Field) -> hir::Field {
2216 id: self.next_id().node_id,
2218 expr: P(self.lower_expr(&f.expr)),
2220 is_shorthand: f.is_shorthand,
2224 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2226 ty: self.lower_ty(&mt.ty, itctx),
2227 mutbl: self.lower_mutability(mt.mutbl),
2233 bounds: &[TyParamBound],
2234 itctx: ImplTraitContext,
2235 ) -> hir::TyParamBounds {
2238 .map(|bound| self.lower_ty_param_bound(bound, itctx))
2242 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2243 let mut expr = None;
2245 let mut stmts = vec![];
2247 for (index, stmt) in b.stmts.iter().enumerate() {
2248 if index == b.stmts.len() - 1 {
2249 if let StmtKind::Expr(ref e) = stmt.node {
2250 expr = Some(P(self.lower_expr(e)));
2252 stmts.extend(self.lower_stmt(stmt));
2255 stmts.extend(self.lower_stmt(stmt));
2259 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2264 stmts: stmts.into(),
2266 rules: self.lower_block_check_mode(&b.rules),
2269 recovered: b.recovered,
2277 attrs: &hir::HirVec<Attribute>,
2278 vis: &mut hir::Visibility,
2282 ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2283 ItemKind::Use(ref use_tree) => {
2284 // Start with an empty prefix
2287 span: use_tree.span,
2290 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2292 ItemKind::Static(ref t, m, ref e) => {
2293 let value = self.lower_body(None, |this| this.lower_expr(e));
2295 self.lower_ty(t, ImplTraitContext::Disallowed),
2296 self.lower_mutability(m),
2300 ItemKind::Const(ref t, ref e) => {
2301 let value = self.lower_body(None, |this| this.lower_expr(e));
2302 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2304 ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
2305 let fn_def_id = self.resolver.definitions().local_def_id(id);
2306 self.with_new_scopes(|this| {
2307 let body_id = this.lower_body(Some(decl), |this| {
2308 let body = this.lower_block(body, false);
2309 this.expr_block(body, ThinVec::new())
2311 let (generics, fn_decl) = this.add_in_band_defs(
2314 AnonymousLifetimeMode::PassThrough,
2315 |this| this.lower_fn_decl(decl, Some(fn_def_id), true),
2320 this.lower_unsafety(unsafety),
2321 this.lower_constness(constness),
2328 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2329 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2330 ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2331 ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2332 self.lower_ty(t, ImplTraitContext::Disallowed),
2333 self.lower_generics(generics, ImplTraitContext::Disallowed),
2335 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2337 variants: enum_definition
2340 .map(|x| self.lower_variant(x))
2343 self.lower_generics(generics, ImplTraitContext::Disallowed),
2345 ItemKind::Struct(ref struct_def, ref generics) => {
2346 let struct_def = self.lower_variant_data(struct_def);
2349 self.lower_generics(generics, ImplTraitContext::Disallowed),
2352 ItemKind::Union(ref vdata, ref generics) => {
2353 let vdata = self.lower_variant_data(vdata);
2356 self.lower_generics(generics, ImplTraitContext::Disallowed),
2368 let def_id = self.resolver.definitions().local_def_id(id);
2370 // Lower the "impl header" first. This ordering is important
2371 // for in-band lifetimes! Consider `'a` here:
2373 // impl Foo<'a> for u32 {
2374 // fn method(&'a self) { .. }
2377 // Because we start by lowering the `Foo<'a> for u32`
2378 // part, we will add `'a` to the list of generics on
2379 // the impl. When we then encounter it later in the
2380 // method, it will not be considered an in-band
2381 // lifetime to be added, but rather a reference to a
2383 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2386 AnonymousLifetimeMode::CreateParameter,
2388 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2389 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2392 if let Some(ref trait_ref) = trait_ref {
2393 if let Def::Trait(def_id) = trait_ref.path.def {
2394 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2398 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2400 (trait_ref, lowered_ty)
2404 let new_impl_items = self.with_in_scope_lifetime_defs(
2405 &ast_generics.params,
2409 .map(|item| this.lower_impl_item_ref(item))
2415 self.lower_unsafety(unsafety),
2416 self.lower_impl_polarity(polarity),
2417 self.lower_defaultness(defaultness, true /* [1] */),
2424 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2425 let bounds = self.lower_bounds(bounds, ImplTraitContext::Disallowed);
2428 .map(|item| self.lower_trait_item_ref(item))
2431 self.lower_is_auto(is_auto),
2432 self.lower_unsafety(unsafety),
2433 self.lower_generics(generics, ImplTraitContext::Disallowed),
2438 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2439 self.lower_generics(generics, ImplTraitContext::Disallowed),
2440 self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2442 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2445 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2446 // not cause an assertion failure inside the `lower_defaultness` function
2454 vis: &mut hir::Visibility,
2456 attrs: &hir::HirVec<Attribute>,
2458 let path = &tree.prefix;
2461 UseTreeKind::Simple(rename, id1, id2) => {
2462 *name = tree.ident().name;
2464 // First apply the prefix to the path
2465 let mut path = Path {
2469 .chain(path.segments.iter())
2475 // Correctly resolve `self` imports
2476 if path.segments.len() > 1
2477 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2479 let _ = path.segments.pop();
2480 if rename.is_none() {
2481 *name = path.segments.last().unwrap().ident.name;
2485 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2486 let mut defs = self.expect_full_def_from_use(id);
2487 // we want to return *something* from this function, so hang onto the first item
2489 let mut ret_def = defs.next().unwrap_or(Def::Err);
2491 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2492 let vis = vis.clone();
2493 let name = name.clone();
2494 let span = path.span;
2495 self.resolver.definitions().create_def_with_parent(
2499 DefIndexAddressSpace::High,
2502 self.allocate_hir_id_counter(new_node_id, &path);
2504 self.with_hir_id_owner(new_node_id, |this| {
2505 let new_id = this.lower_node_id(new_node_id);
2506 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2507 let item = hir::ItemUse(P(path), hir::UseKind::Single);
2508 let vis = match vis {
2509 hir::Visibility::Public => hir::Visibility::Public,
2510 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2511 hir::Visibility::Inherited => hir::Visibility::Inherited,
2512 hir::Visibility::Restricted { ref path, id: _ } => {
2513 hir::Visibility::Restricted {
2515 // We are allocating a new NodeId here
2516 id: this.next_id().node_id,
2525 hir_id: new_id.hir_id,
2527 attrs: attrs.clone(),
2536 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2537 hir::ItemUse(path, hir::UseKind::Single)
2539 UseTreeKind::Glob => {
2540 let path = P(self.lower_path(
2546 .chain(path.segments.iter())
2551 ParamMode::Explicit,
2553 hir::ItemUse(path, hir::UseKind::Glob)
2555 UseTreeKind::Nested(ref trees) => {
2560 .chain(path.segments.iter())
2563 span: prefix.span.to(path.span),
2566 // Add all the nested PathListItems in the HIR
2567 for &(ref use_tree, id) in trees {
2568 self.allocate_hir_id_counter(id, &use_tree);
2572 } = self.lower_node_id(id);
2574 let mut vis = vis.clone();
2575 let mut name = name.clone();
2577 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2579 self.with_hir_id_owner(new_id, |this| {
2580 let vis = match vis {
2581 hir::Visibility::Public => hir::Visibility::Public,
2582 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2583 hir::Visibility::Inherited => hir::Visibility::Inherited,
2584 hir::Visibility::Restricted { ref path, id: _ } => {
2585 hir::Visibility::Restricted {
2587 // We are allocating a new NodeId here
2588 id: this.next_id().node_id,
2599 attrs: attrs.clone(),
2602 span: use_tree.span,
2608 // Privatize the degenerate import base, used only to check
2609 // the stability of `use a::{};`, to avoid it showing up as
2610 // a re-export by accident when `pub`, e.g. in documentation.
2611 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2612 *vis = hir::Inherited;
2613 hir::ItemUse(path, hir::UseKind::ListStem)
2618 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2619 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2620 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2622 let (generics, node) = match i.node {
2623 TraitItemKind::Const(ref ty, ref default) => (
2624 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2625 hir::TraitItemKind::Const(
2626 self.lower_ty(ty, ImplTraitContext::Disallowed),
2629 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2632 TraitItemKind::Method(ref sig, None) => {
2633 let names = self.lower_fn_args_to_names(&sig.decl);
2634 self.add_in_band_defs(
2637 AnonymousLifetimeMode::PassThrough,
2639 hir::TraitItemKind::Method(
2640 this.lower_method_sig(sig, trait_item_def_id, false),
2641 hir::TraitMethod::Required(names),
2646 TraitItemKind::Method(ref sig, Some(ref body)) => {
2647 let body_id = self.lower_body(Some(&sig.decl), |this| {
2648 let body = this.lower_block(body, false);
2649 this.expr_block(body, ThinVec::new())
2652 self.add_in_band_defs(
2655 AnonymousLifetimeMode::PassThrough,
2657 hir::TraitItemKind::Method(
2658 this.lower_method_sig(sig, trait_item_def_id, false),
2659 hir::TraitMethod::Provided(body_id),
2664 TraitItemKind::Type(ref bounds, ref default) => (
2665 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2666 hir::TraitItemKind::Type(
2667 self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2670 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2673 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2679 name: self.lower_ident(i.ident),
2680 attrs: self.lower_attrs(&i.attrs),
2687 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2688 let (kind, has_default) = match i.node {
2689 TraitItemKind::Const(_, ref default) => {
2690 (hir::AssociatedItemKind::Const, default.is_some())
2692 TraitItemKind::Type(_, ref default) => {
2693 (hir::AssociatedItemKind::Type, default.is_some())
2695 TraitItemKind::Method(ref sig, ref default) => (
2696 hir::AssociatedItemKind::Method {
2697 has_self: sig.decl.has_self(),
2701 TraitItemKind::Macro(..) => unimplemented!(),
2704 id: hir::TraitItemId { node_id: i.id },
2705 name: self.lower_ident(i.ident),
2707 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
2712 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
2713 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2714 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
2716 let (generics, node) = match i.node {
2717 ImplItemKind::Const(ref ty, ref expr) => {
2718 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
2720 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2721 hir::ImplItemKind::Const(
2722 self.lower_ty(ty, ImplTraitContext::Disallowed),
2727 ImplItemKind::Method(ref sig, ref body) => {
2728 let body_id = self.lower_body(Some(&sig.decl), |this| {
2729 let body = this.lower_block(body, false);
2730 this.expr_block(body, ThinVec::new())
2732 let impl_trait_return_allow = !self.is_in_trait_impl;
2734 self.add_in_band_defs(
2737 AnonymousLifetimeMode::PassThrough,
2739 hir::ImplItemKind::Method(
2740 this.lower_method_sig(
2743 impl_trait_return_allow,
2750 ImplItemKind::Type(ref ty) => (
2751 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2752 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
2754 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2760 name: self.lower_ident(i.ident),
2761 attrs: self.lower_attrs(&i.attrs),
2763 vis: self.lower_visibility(&i.vis, None),
2764 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2769 // [1] since `default impl` is not yet implemented, this is always true in impls
2772 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
2774 id: hir::ImplItemId { node_id: i.id },
2775 name: self.lower_ident(i.ident),
2777 vis: self.lower_visibility(&i.vis, Some(i.id)),
2778 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2779 kind: match i.node {
2780 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
2781 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
2782 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
2783 has_self: sig.decl.has_self(),
2785 ImplItemKind::Macro(..) => unimplemented!(),
2789 // [1] since `default impl` is not yet implemented, this is always true in impls
2792 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
2795 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
2799 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
2801 ItemKind::Use(ref use_tree) => {
2802 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
2803 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
2806 ItemKind::MacroDef(..) => return SmallVector::new(),
2809 SmallVector::one(hir::ItemId { id: i.id })
2812 fn lower_item_id_use_tree(&mut self,
2815 vec: &mut SmallVector<hir::ItemId>)
2818 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
2819 vec.push(hir::ItemId { id });
2820 self.lower_item_id_use_tree(nested, id, vec);
2822 UseTreeKind::Glob => {}
2823 UseTreeKind::Simple(_, id1, id2) => {
2824 for (_, &id) in self.expect_full_def_from_use(base_id)
2826 .zip([id1, id2].iter())
2828 vec.push(hir::ItemId { id });
2834 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
2835 let mut name = i.ident.name;
2836 let mut vis = self.lower_visibility(&i.vis, None);
2837 let attrs = self.lower_attrs(&i.attrs);
2838 if let ItemKind::MacroDef(ref def) = i.node {
2839 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
2840 let body = self.lower_token_stream(def.stream());
2841 self.exported_macros.push(hir::MacroDef {
2854 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
2856 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2869 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
2870 let node_id = self.lower_node_id(i.id).node_id;
2871 let def_id = self.resolver.definitions().local_def_id(node_id);
2875 attrs: self.lower_attrs(&i.attrs),
2876 node: match i.node {
2877 ForeignItemKind::Fn(ref fdec, ref generics) => {
2878 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
2881 AnonymousLifetimeMode::PassThrough,
2884 // Disallow impl Trait in foreign items
2885 this.lower_fn_decl(fdec, None, false),
2886 this.lower_fn_args_to_names(fdec),
2891 hir::ForeignItemFn(fn_dec, fn_args, generics)
2893 ForeignItemKind::Static(ref t, m) => {
2894 hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
2896 ForeignItemKind::Ty => hir::ForeignItemType,
2897 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
2899 vis: self.lower_visibility(&i.vis, None),
2904 fn lower_method_sig(
2908 impl_trait_return_allow: bool,
2909 ) -> hir::MethodSig {
2912 unsafety: self.lower_unsafety(sig.unsafety),
2913 constness: self.lower_constness(sig.constness),
2914 decl: self.lower_fn_decl(&sig.decl, Some(fn_def_id), impl_trait_return_allow),
2918 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
2920 IsAuto::Yes => hir::IsAuto::Yes,
2921 IsAuto::No => hir::IsAuto::No,
2925 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
2927 Unsafety::Unsafe => hir::Unsafety::Unsafe,
2928 Unsafety::Normal => hir::Unsafety::Normal,
2932 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
2934 Constness::Const => hir::Constness::Const,
2935 Constness::NotConst => hir::Constness::NotConst,
2939 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
2941 UnOp::Deref => hir::UnDeref,
2942 UnOp::Not => hir::UnNot,
2943 UnOp::Neg => hir::UnNeg,
2947 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
2949 node: match b.node {
2950 BinOpKind::Add => hir::BiAdd,
2951 BinOpKind::Sub => hir::BiSub,
2952 BinOpKind::Mul => hir::BiMul,
2953 BinOpKind::Div => hir::BiDiv,
2954 BinOpKind::Rem => hir::BiRem,
2955 BinOpKind::And => hir::BiAnd,
2956 BinOpKind::Or => hir::BiOr,
2957 BinOpKind::BitXor => hir::BiBitXor,
2958 BinOpKind::BitAnd => hir::BiBitAnd,
2959 BinOpKind::BitOr => hir::BiBitOr,
2960 BinOpKind::Shl => hir::BiShl,
2961 BinOpKind::Shr => hir::BiShr,
2962 BinOpKind::Eq => hir::BiEq,
2963 BinOpKind::Lt => hir::BiLt,
2964 BinOpKind::Le => hir::BiLe,
2965 BinOpKind::Ne => hir::BiNe,
2966 BinOpKind::Ge => hir::BiGe,
2967 BinOpKind::Gt => hir::BiGt,
2973 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2974 let node = match p.node {
2975 PatKind::Wild => hir::PatKind::Wild,
2976 PatKind::Ident(ref binding_mode, ident, ref sub) => {
2977 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
2978 // `None` can occur in body-less function signatures
2979 def @ None | def @ Some(Def::Local(_)) => {
2980 let canonical_id = match def {
2981 Some(Def::Local(id)) => id,
2984 hir::PatKind::Binding(
2985 self.lower_binding_mode(binding_mode),
2987 respan(ident.span, ident.name),
2988 sub.as_ref().map(|x| self.lower_pat(x)),
2991 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
2996 segments: hir_vec![hir::PathSegment::from_name(ident.name)],
3001 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3002 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3003 let qpath = self.lower_qpath(
3007 ParamMode::Optional,
3008 ImplTraitContext::Disallowed,
3010 hir::PatKind::TupleStruct(
3012 pats.iter().map(|x| self.lower_pat(x)).collect(),
3016 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3020 ParamMode::Optional,
3021 ImplTraitContext::Disallowed,
3023 PatKind::Struct(ref path, ref fields, etc) => {
3024 let qpath = self.lower_qpath(
3028 ParamMode::Optional,
3029 ImplTraitContext::Disallowed,
3036 node: hir::FieldPat {
3037 id: self.next_id().node_id,
3038 ident: f.node.ident,
3039 pat: self.lower_pat(&f.node.pat),
3040 is_shorthand: f.node.is_shorthand,
3044 hir::PatKind::Struct(qpath, fs, etc)
3046 PatKind::Tuple(ref elts, ddpos) => {
3047 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3049 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3050 PatKind::Ref(ref inner, mutbl) => {
3051 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3053 PatKind::Range(ref e1, ref e2, ref end) => hir::PatKind::Range(
3054 P(self.lower_expr(e1)),
3055 P(self.lower_expr(e2)),
3056 self.lower_range_end(end),
3058 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3059 before.iter().map(|x| self.lower_pat(x)).collect(),
3060 slice.as_ref().map(|x| self.lower_pat(x)),
3061 after.iter().map(|x| self.lower_pat(x)).collect(),
3063 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3064 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3067 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3076 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3078 RangeEnd::Included(_) => hir::RangeEnd::Included,
3079 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3083 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3084 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3089 body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3093 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3094 let kind = match e.node {
3095 ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
3096 ExprKind::ObsoleteInPlace(..) => {
3097 self.sess.abort_if_errors();
3098 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3100 ExprKind::Array(ref exprs) => {
3101 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
3103 ExprKind::Repeat(ref expr, ref count) => {
3104 let expr = P(self.lower_expr(expr));
3105 let count = self.lower_anon_const(count);
3106 hir::ExprRepeat(expr, count)
3108 ExprKind::Tup(ref elts) => {
3109 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
3111 ExprKind::Call(ref f, ref args) => {
3112 let f = P(self.lower_expr(f));
3113 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
3115 ExprKind::MethodCall(ref seg, ref args) => {
3116 let hir_seg = self.lower_path_segment(
3119 ParamMode::Optional,
3121 ParenthesizedGenericArgs::Err,
3122 ImplTraitContext::Disallowed,
3124 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3125 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
3127 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3128 let binop = self.lower_binop(binop);
3129 let lhs = P(self.lower_expr(lhs));
3130 let rhs = P(self.lower_expr(rhs));
3131 hir::ExprBinary(binop, lhs, rhs)
3133 ExprKind::Unary(op, ref ohs) => {
3134 let op = self.lower_unop(op);
3135 let ohs = P(self.lower_expr(ohs));
3136 hir::ExprUnary(op, ohs)
3138 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
3139 ExprKind::Cast(ref expr, ref ty) => {
3140 let expr = P(self.lower_expr(expr));
3141 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3143 ExprKind::Type(ref expr, ref ty) => {
3144 let expr = P(self.lower_expr(expr));
3145 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3147 ExprKind::AddrOf(m, ref ohs) => {
3148 let m = self.lower_mutability(m);
3149 let ohs = P(self.lower_expr(ohs));
3150 hir::ExprAddrOf(m, ohs)
3152 // More complicated than you might expect because the else branch
3153 // might be `if let`.
3154 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3155 let else_opt = else_opt.as_ref().map(|els| {
3157 ExprKind::IfLet(..) => {
3158 // wrap the if-let expr in a block
3159 let span = els.span;
3160 let els = P(self.lower_expr(els));
3161 let LoweredNodeId { node_id, hir_id } = self.next_id();
3162 let blk = P(hir::Block {
3167 rules: hir::DefaultBlock,
3169 targeted_by_break: false,
3170 recovered: blk.recovered,
3172 P(self.expr_block(blk, ThinVec::new()))
3174 _ => P(self.lower_expr(els)),
3178 let then_blk = self.lower_block(blk, false);
3179 let then_expr = self.expr_block(then_blk, ThinVec::new());
3181 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3183 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3185 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3186 this.lower_block(body, false),
3187 this.lower_label(opt_label),
3190 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3192 this.lower_block(body, false),
3193 this.lower_label(opt_label),
3194 hir::LoopSource::Loop,
3197 ExprKind::Catch(ref body) => {
3198 self.with_catch_scope(body.id, |this| {
3200 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3201 let mut block = this.lower_block(body, true).into_inner();
3202 let tail = block.expr.take().map_or_else(
3204 let LoweredNodeId { node_id, hir_id } = this.next_id();
3205 let span = this.sess.codemap().end_point(unstable_span);
3209 node: hir::ExprTup(hir_vec![]),
3210 attrs: ThinVec::new(),
3214 |x: P<hir::Expr>| x.into_inner(),
3216 block.expr = Some(this.wrap_in_try_constructor(
3217 "from_ok", tail, unstable_span));
3218 hir::ExprBlock(P(block), None)
3221 ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3222 P(self.lower_expr(expr)),
3223 arms.iter().map(|x| self.lower_arm(x)).collect(),
3224 hir::MatchSource::Normal,
3226 ExprKind::Closure(capture_clause, movability, ref decl, ref body, fn_decl_span) => {
3227 self.with_new_scopes(|this| {
3228 let mut is_generator = false;
3229 let body_id = this.lower_body(Some(decl), |this| {
3230 let e = this.lower_expr(body);
3231 is_generator = this.is_generator;
3234 let generator_option = if is_generator {
3235 if !decl.inputs.is_empty() {
3240 "generators cannot have explicit arguments"
3242 this.sess.abort_if_errors();
3244 Some(match movability {
3245 Movability::Movable => hir::GeneratorMovability::Movable,
3246 Movability::Static => hir::GeneratorMovability::Static,
3249 if movability == Movability::Static {
3254 "closures cannot be static"
3260 this.lower_capture_clause(capture_clause),
3261 this.lower_fn_decl(decl, None, false),
3268 ExprKind::Block(ref blk, opt_label) => {
3269 hir::ExprBlock(self.lower_block(blk,
3270 opt_label.is_some()),
3271 self.lower_label(opt_label))
3273 ExprKind::Assign(ref el, ref er) => {
3274 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3276 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3277 self.lower_binop(op),
3278 P(self.lower_expr(el)),
3279 P(self.lower_expr(er)),
3281 ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3282 ExprKind::Index(ref el, ref er) => {
3283 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3285 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3286 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3287 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3288 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3289 let id = self.next_id();
3290 let e1 = self.lower_expr(e1);
3291 let e2 = self.lower_expr(e2);
3292 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], false));
3293 let ty = self.ty_path(id, span, hir::QPath::Resolved(None, ty_path));
3294 let new_seg = P(hir::PathSegment::from_name(Symbol::intern("new")));
3295 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3296 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3297 hir::ExprCall(new, hir_vec![e1, e2])
3299 ExprKind::Range(ref e1, ref e2, lims) => {
3300 use syntax::ast::RangeLimits::*;
3302 let path = match (e1, e2, lims) {
3303 (&None, &None, HalfOpen) => "RangeFull",
3304 (&Some(..), &None, HalfOpen) => "RangeFrom",
3305 (&None, &Some(..), HalfOpen) => "RangeTo",
3306 (&Some(..), &Some(..), HalfOpen) => "Range",
3307 (&None, &Some(..), Closed) => "RangeToInclusive",
3308 (&Some(..), &Some(..), Closed) => unreachable!(),
3309 (_, &None, Closed) => self.diagnostic()
3310 .span_fatal(e.span, "inclusive range with no end")
3314 let fields = e1.iter()
3315 .map(|e| ("start", e))
3316 .chain(e2.iter().map(|e| ("end", e)))
3318 let expr = P(self.lower_expr(&e));
3320 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3321 let ident = Ident::new(Symbol::intern(s), unstable_span);
3322 self.field(ident, expr, unstable_span)
3324 .collect::<P<[hir::Field]>>();
3326 let is_unit = fields.is_empty();
3328 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3329 let struct_path = iter::once("ops")
3330 .chain(iter::once(path))
3331 .collect::<Vec<_>>();
3332 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
3333 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3335 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3341 hir::ExprPath(struct_path)
3343 hir::ExprStruct(struct_path, fields, None)
3345 span: unstable_span,
3346 attrs: e.attrs.clone(),
3349 ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3353 ParamMode::Optional,
3354 ImplTraitContext::Disallowed,
3356 ExprKind::Break(opt_label, ref opt_expr) => {
3357 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3360 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3363 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3367 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3370 ExprKind::Continue(opt_label) => {
3371 hir::ExprAgain(if self.is_in_loop_condition && opt_label.is_none() {
3374 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3377 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3380 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3381 ExprKind::InlineAsm(ref asm) => {
3382 let hir_asm = hir::InlineAsm {
3383 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3384 outputs: asm.outputs
3386 .map(|out| hir::InlineAsmOutput {
3387 constraint: out.constraint.clone(),
3389 is_indirect: out.is_indirect,
3392 asm: asm.asm.clone(),
3393 asm_str_style: asm.asm_str_style,
3394 clobbers: asm.clobbers.clone().into(),
3395 volatile: asm.volatile,
3396 alignstack: asm.alignstack,
3397 dialect: asm.dialect,
3400 let outputs = asm.outputs
3402 .map(|out| self.lower_expr(&out.expr))
3404 let inputs = asm.inputs
3406 .map(|&(_, ref input)| self.lower_expr(input))
3408 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3410 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3415 ParamMode::Optional,
3416 ImplTraitContext::Disallowed,
3418 fields.iter().map(|x| self.lower_field(x)).collect(),
3419 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3421 ExprKind::Paren(ref ex) => {
3422 let mut ex = self.lower_expr(ex);
3423 // include parens in span, but only if it is a super-span.
3424 if e.span.contains(ex.span) {
3427 // merge attributes into the inner expression.
3428 let mut attrs = e.attrs.clone();
3429 attrs.extend::<Vec<_>>(ex.attrs.into());
3434 ExprKind::Yield(ref opt_expr) => {
3435 self.is_generator = true;
3438 .map(|x| self.lower_expr(x))
3439 .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3440 hir::ExprYield(P(expr))
3443 // Desugar ExprIfLet
3444 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3445 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3448 // match <sub_expr> {
3450 // _ => [<else_opt> | ()]
3453 let mut arms = vec![];
3455 // `<pat> => <body>`
3457 let body = self.lower_block(body, false);
3458 let body_expr = P(self.expr_block(body, ThinVec::new()));
3459 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3460 arms.push(self.arm(pats, body_expr));
3463 // _ => [<else_opt>|()]
3465 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3466 let wildcard_pattern = self.pat_wild(e.span);
3467 let body = if let Some(else_expr) = wildcard_arm {
3468 P(self.lower_expr(else_expr))
3470 self.expr_tuple(e.span, hir_vec![])
3472 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3475 let contains_else_clause = else_opt.is_some();
3477 let sub_expr = P(self.lower_expr(sub_expr));
3482 hir::MatchSource::IfLetDesugar {
3483 contains_else_clause,
3488 // Desugar ExprWhileLet
3489 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3490 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3493 // [opt_ident]: loop {
3494 // match <sub_expr> {
3500 // Note that the block AND the condition are evaluated in the loop scope.
3501 // This is done to allow `break` from inside the condition of the loop.
3502 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3504 this.lower_block(body, false),
3505 this.expr_break(e.span, ThinVec::new()),
3506 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3510 // `<pat> => <body>`
3512 let body_expr = P(self.expr_block(body, ThinVec::new()));
3513 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3514 self.arm(pats, body_expr)
3519 let pat_under = self.pat_wild(e.span);
3520 self.arm(hir_vec![pat_under], break_expr)
3523 // `match <sub_expr> { ... }`
3524 let arms = hir_vec![pat_arm, break_arm];
3525 let match_expr = self.expr(
3527 hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3531 // `[opt_ident]: loop { ... }`
3532 let loop_block = P(self.block_expr(P(match_expr)));
3533 let loop_expr = hir::ExprLoop(
3535 self.lower_label(opt_label),
3536 hir::LoopSource::WhileLet,
3538 // add attributes to the outer returned expr node
3542 // Desugar ExprForLoop
3543 // From: `[opt_ident]: for <pat> in <head> <body>`
3544 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3548 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3550 // [opt_ident]: loop {
3552 // match ::std::iter::Iterator::next(&mut iter) {
3553 // ::std::option::Option::Some(val) => __next = val,
3554 // ::std::option::Option::None => break
3556 // let <pat> = __next;
3557 // StmtExpr(<body>);
3565 let head = self.lower_expr(head);
3566 let head_sp = head.span;
3568 let iter = self.str_to_ident("iter");
3570 let next_ident = self.str_to_ident("__next");
3571 let next_pat = self.pat_ident_binding_mode(
3574 hir::BindingAnnotation::Mutable,
3577 // `::std::option::Option::Some(val) => next = val`
3579 let val_ident = self.str_to_ident("val");
3580 let val_pat = self.pat_ident(pat.span, val_ident);
3581 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
3582 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
3583 let assign = P(self.expr(
3585 hir::ExprAssign(next_expr, val_expr),
3588 let some_pat = self.pat_some(pat.span, val_pat);
3589 self.arm(hir_vec![some_pat], assign)
3592 // `::std::option::Option::None => break`
3595 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
3596 let pat = self.pat_none(e.span);
3597 self.arm(hir_vec![pat], break_expr)
3602 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
3604 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
3606 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
3607 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
3608 let next_path = &["iter", "Iterator", "next"];
3609 let next_path = P(self.expr_std_path(head_sp, next_path, ThinVec::new()));
3610 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
3611 let arms = hir_vec![pat_arm, break_arm];
3615 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
3619 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
3621 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
3625 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
3627 // `let <pat> = __next`
3628 let pat = self.lower_pat(pat);
3629 let pat_let = self.stmt_let_pat(
3633 hir::LocalSource::ForLoopDesugar,
3636 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
3637 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
3638 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
3640 let loop_block = P(self.block_all(
3642 hir_vec![next_let, match_stmt, pat_let, body_stmt],
3646 // `[opt_ident]: loop { ... }`
3647 let loop_expr = hir::ExprLoop(
3649 self.lower_label(opt_label),
3650 hir::LoopSource::ForLoop,
3652 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3653 let loop_expr = P(hir::Expr {
3658 attrs: ThinVec::new(),
3661 // `mut iter => { ... }`
3662 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
3664 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
3665 let into_iter_expr = {
3666 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
3667 let into_iter = P(self.expr_std_path(head_sp, into_iter_path, ThinVec::new()));
3668 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
3671 let match_expr = P(self.expr_match(
3675 hir::MatchSource::ForLoopDesugar,
3678 // `{ let _result = ...; _result }`
3679 // underscore prevents an unused_variables lint if the head diverges
3680 let result_ident = self.str_to_ident("_result");
3681 let (let_stmt, let_stmt_binding) =
3682 self.stmt_let(e.span, false, result_ident, match_expr);
3684 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
3685 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
3686 // add the attributes to the outer returned expr node
3687 return self.expr_block(block, e.attrs.clone());
3690 // Desugar ExprKind::Try
3692 ExprKind::Try(ref sub_expr) => {
3695 // match Try::into_result(<expr>) {
3696 // Ok(val) => #[allow(unreachable_code)] val,
3697 // Err(err) => #[allow(unreachable_code)]
3698 // // If there is an enclosing `catch {...}`
3699 // break 'catch_target Try::from_error(From::from(err)),
3701 // return Try::from_error(From::from(err)),
3705 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
3707 // Try::into_result(<expr>)
3710 let sub_expr = self.lower_expr(sub_expr);
3712 let path = &["ops", "Try", "into_result"];
3713 let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
3714 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
3717 // #[allow(unreachable_code)]
3719 // allow(unreachable_code)
3721 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
3722 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
3723 let uc_nested = attr::mk_nested_word_item(uc_ident);
3724 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
3726 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
3728 let attrs = vec![attr];
3730 // Ok(val) => #[allow(unreachable_code)] val,
3732 let val_ident = self.str_to_ident("val");
3733 let val_pat = self.pat_ident(e.span, val_ident);
3734 let val_expr = P(self.expr_ident_with_attrs(
3738 ThinVec::from(attrs.clone()),
3740 let ok_pat = self.pat_ok(e.span, val_pat);
3742 self.arm(hir_vec![ok_pat], val_expr)
3745 // Err(err) => #[allow(unreachable_code)]
3746 // return Try::from_error(From::from(err)),
3748 let err_ident = self.str_to_ident("err");
3749 let err_local = self.pat_ident(e.span, err_ident);
3751 let path = &["convert", "From", "from"];
3752 let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
3753 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
3755 self.expr_call(e.span, from, hir_vec![err_expr])
3758 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
3759 let thin_attrs = ThinVec::from(attrs);
3760 let catch_scope = self.catch_scopes.last().map(|x| *x);
3761 let ret_expr = if let Some(catch_node) = catch_scope {
3767 target_id: Ok(catch_node),
3769 Some(from_err_expr),
3774 P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
3777 let err_pat = self.pat_err(e.span, err_local);
3778 self.arm(hir_vec![err_pat], ret_expr)
3783 hir_vec![err_arm, ok_arm],
3784 hir::MatchSource::TryDesugar,
3788 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
3791 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3798 attrs: e.attrs.clone(),
3802 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
3803 SmallVector::one(match s.node {
3804 StmtKind::Local(ref l) => Spanned {
3805 node: hir::StmtDecl(
3807 node: hir::DeclLocal(self.lower_local(l)),
3810 self.lower_node_id(s.id).node_id,
3814 StmtKind::Item(ref it) => {
3815 // Can only use the ID once.
3816 let mut id = Some(s.id);
3817 return self.lower_item_id(it)
3819 .map(|item_id| Spanned {
3820 node: hir::StmtDecl(
3822 node: hir::DeclItem(item_id),
3826 .map(|id| self.lower_node_id(id).node_id)
3827 .unwrap_or_else(|| self.next_id().node_id),
3833 StmtKind::Expr(ref e) => Spanned {
3834 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3837 StmtKind::Semi(ref e) => Spanned {
3838 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3841 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
3845 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
3847 CaptureBy::Value => hir::CaptureByValue,
3848 CaptureBy::Ref => hir::CaptureByRef,
3852 /// If an `explicit_owner` is given, this method allocates the `HirId` in
3853 /// the address space of that item instead of the item currently being
3854 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
3855 /// lower a `Visibility` value although we haven't lowered the owning
3856 /// `ImplItem` in question yet.
3857 fn lower_visibility(
3860 explicit_owner: Option<NodeId>,
3861 ) -> hir::Visibility {
3863 VisibilityKind::Public => hir::Public,
3864 VisibilityKind::Crate(sugar) => hir::Visibility::Crate(sugar),
3865 VisibilityKind::Restricted { ref path, id, .. } => hir::Visibility::Restricted {
3866 path: P(self.lower_path(id, path, ParamMode::Explicit)),
3867 id: if let Some(owner) = explicit_owner {
3868 self.lower_node_id_with_owner(id, owner).node_id
3870 self.lower_node_id(id).node_id
3873 VisibilityKind::Inherited => hir::Inherited,
3877 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
3879 Defaultness::Default => hir::Defaultness::Default {
3880 has_value: has_value,
3882 Defaultness::Final => {
3884 hir::Defaultness::Final
3889 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3891 BlockCheckMode::Default => hir::DefaultBlock,
3892 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3896 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3898 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
3899 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
3900 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
3901 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
3905 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3907 CompilerGenerated => hir::CompilerGenerated,
3908 UserProvided => hir::UserProvided,
3912 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
3914 ImplPolarity::Positive => hir::ImplPolarity::Positive,
3915 ImplPolarity::Negative => hir::ImplPolarity::Negative,
3919 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3921 TraitBoundModifier::None => hir::TraitBoundModifier::None,
3922 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3926 // Helper methods for building HIR.
3928 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
3937 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
3939 id: self.next_id().node_id,
3943 is_shorthand: false,
3947 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
3948 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
3949 P(self.expr(span, expr_break, attrs))
3956 args: hir::HirVec<hir::Expr>,
3958 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
3961 fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
3962 self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
3965 fn expr_ident_with_attrs(
3970 attrs: ThinVec<Attribute>,
3972 let expr_path = hir::ExprPath(hir::QPath::Resolved(
3976 def: Def::Local(binding),
3977 segments: hir_vec![hir::PathSegment::from_name(id)],
3981 self.expr(span, expr_path, attrs)
3984 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
3985 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
3991 components: &[&str],
3992 attrs: ThinVec<Attribute>,
3994 let path = self.std_path(span, components, true);
3997 hir::ExprPath(hir::QPath::Resolved(None, P(path))),
4006 arms: hir::HirVec<hir::Arm>,
4007 source: hir::MatchSource,
4009 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
4012 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4013 self.expr(b.span, hir::ExprBlock(b, None), attrs)
4016 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4017 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
4020 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
4021 let LoweredNodeId { node_id, hir_id } = self.next_id();
4034 ex: Option<P<hir::Expr>>,
4036 source: hir::LocalSource,
4038 let LoweredNodeId { node_id, hir_id } = self.next_id();
4040 let local = P(hir::Local {
4047 attrs: ThinVec::new(),
4050 let decl = respan(sp, hir::DeclLocal(local));
4051 respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
4060 ) -> (hir::Stmt, NodeId) {
4061 let pat = if mutbl {
4062 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4064 self.pat_ident(sp, ident)
4066 let pat_id = pat.id;
4068 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4073 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4074 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4080 stmts: hir::HirVec<hir::Stmt>,
4081 expr: Option<P<hir::Expr>>,
4083 let LoweredNodeId { node_id, hir_id } = self.next_id();
4090 rules: hir::DefaultBlock,
4092 targeted_by_break: false,
4097 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4098 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4101 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4102 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4105 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4106 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4109 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4110 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4116 components: &[&str],
4117 subpats: hir::HirVec<P<hir::Pat>>,
4119 let path = self.std_path(span, components, true);
4120 let qpath = hir::QPath::Resolved(None, P(path));
4121 let pt = if subpats.is_empty() {
4122 hir::PatKind::Path(qpath)
4124 hir::PatKind::TupleStruct(qpath, subpats, None)
4129 fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
4130 self.pat_ident_binding_mode(span, name, hir::BindingAnnotation::Unannotated)
4133 fn pat_ident_binding_mode(
4137 bm: hir::BindingAnnotation,
4139 let LoweredNodeId { node_id, hir_id } = self.next_id();
4144 node: hir::PatKind::Binding(bm, node_id, Spanned { span, node: name }, None),
4149 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4150 self.pat(span, hir::PatKind::Wild)
4153 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4154 let LoweredNodeId { node_id, hir_id } = self.next_id();
4163 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4164 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4165 /// The path is also resolved according to `is_value`.
4166 fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
4168 .resolve_str_path(span, self.crate_root, components, is_value)
4171 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
4173 let node = match qpath {
4174 hir::QPath::Resolved(None, path) => {
4175 // Turn trait object paths into `TyTraitObject` instead.
4176 if let Def::Trait(_) = path.def {
4177 let principal = hir::PolyTraitRef {
4178 bound_generic_params: hir::HirVec::new(),
4179 trait_ref: hir::TraitRef {
4180 path: path.and_then(|path| path),
4186 // The original ID is taken by the `PolyTraitRef`,
4187 // so the `Ty` itself needs a different one.
4188 id = self.next_id();
4189 hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4191 hir::TyPath(hir::QPath::Resolved(None, path))
4194 _ => hir::TyPath(qpath),
4204 /// Invoked to create the lifetime argument for a type `&T`
4205 /// with no explicit lifetime.
4206 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4207 match self.anonymous_lifetime_mode {
4208 // Intercept when we are in an impl header and introduce an in-band lifetime.
4209 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4211 AnonymousLifetimeMode::CreateParameter => {
4212 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4214 id: self.next_id().node_id,
4220 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4224 /// Invoked to create the lifetime argument(s) for a path like
4225 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4226 /// sorts of cases are deprecated. This may therefore report a warning or an
4227 /// error, depending on the mode.
4228 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4229 match self.anonymous_lifetime_mode {
4230 // NB. We intentionally ignore the create-parameter mode here
4231 // and instead "pass through" to resolve-lifetimes, which will then
4232 // report an error. This is because we don't want to support
4233 // impl elision for deprecated forms like
4235 // impl Foo for std::cell::Ref<u32> // note lack of '_
4236 AnonymousLifetimeMode::CreateParameter => {}
4238 // This is the normal case.
4239 AnonymousLifetimeMode::PassThrough => {}
4243 .map(|_| self.new_implicit_lifetime(span))
4247 /// Invoked to create the lifetime argument(s) for an elided trait object
4248 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4249 /// when the bound is written, even if it is written with `'_` like in
4250 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4251 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4252 match self.anonymous_lifetime_mode {
4253 // NB. We intentionally ignore the create-parameter mode here.
4254 // and instead "pass through" to resolve-lifetimes, which will apply
4255 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4256 // do not act like other elided lifetimes. In other words, given this:
4258 // impl Foo for Box<dyn Debug>
4260 // we do not introduce a fresh `'_` to serve as the bound, but instead
4261 // ultimately translate to the equivalent of:
4263 // impl Foo for Box<dyn Debug + 'static>
4265 // `resolve_lifetime` has the code to make that happen.
4266 AnonymousLifetimeMode::CreateParameter => {}
4268 // This is the normal case.
4269 AnonymousLifetimeMode::PassThrough => {}
4272 self.new_implicit_lifetime(span)
4275 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4277 id: self.next_id().node_id,
4279 name: hir::LifetimeName::Implicit,
4283 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4284 self.sess.buffer_lint_with_diagnostic(
4285 builtin::BARE_TRAIT_OBJECTS,
4288 "trait objects without an explicit `dyn` are deprecated",
4289 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4293 fn wrap_in_try_constructor(
4295 method: &'static str,
4297 unstable_span: Span,
4299 let path = &["ops", "Try", method];
4300 let from_err = P(self.expr_std_path(unstable_span, path,
4302 P(self.expr_call(e.span, from_err, hir_vec![e]))
4306 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4307 // Sorting by span ensures that we get things in order within a
4308 // file, and also puts the files in a sensible order.
4309 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4310 body_ids.sort_by_key(|b| bodies[b].value.span);