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::GenericParamKind::Lifetime { .. } => true,
332 self.lctx.type_def_lifetime_params.insert(def_id, count);
336 visit::walk_item(self, item);
339 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
340 self.lctx.allocate_hir_id_counter(item.id, item);
341 visit::walk_trait_item(self, item);
344 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
345 self.lctx.allocate_hir_id_counter(item.id, item);
346 visit::walk_impl_item(self, item);
350 struct ItemLowerer<'lcx, 'interner: 'lcx> {
351 lctx: &'lcx mut LoweringContext<'interner>,
354 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
355 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
357 F: FnOnce(&mut Self),
359 let old = self.lctx.is_in_trait_impl;
360 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
366 self.lctx.is_in_trait_impl = old;
370 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
371 fn visit_item(&mut self, item: &'lcx Item) {
372 let mut item_lowered = true;
373 self.lctx.with_hir_id_owner(item.id, |lctx| {
374 if let Some(hir_item) = lctx.lower_item(item) {
375 lctx.items.insert(item.id, hir_item);
377 item_lowered = false;
382 let item_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,
702 name: hir_name.name(),
704 pure_wrt_drop: false,
705 bounds: vec![].into(),
706 kind: hir::GenericParamKind::Lifetime {
712 .chain(in_band_ty_params.into_iter())
718 /// When there is a reference to some lifetime `'a`, and in-band
719 /// lifetimes are enabled, then we want to push that lifetime into
720 /// the vector of names to define later. In that case, it will get
721 /// added to the appropriate generics.
722 fn maybe_collect_in_band_lifetime(&mut self, span: Span, name: Name) {
723 if !self.is_collecting_in_band_lifetimes {
727 if self.in_scope_lifetimes.contains(&name) {
731 let hir_name = hir::LifetimeName::Name(name);
733 if self.lifetimes_to_define.iter().any(|(_, lt_name)| *lt_name == hir_name) {
737 self.lifetimes_to_define.push((span, hir_name));
740 /// When we have either an elided or `'_` lifetime in an impl
741 /// header, we convert it to
742 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> hir::LifetimeName {
743 assert!(self.is_collecting_in_band_lifetimes);
744 let index = self.lifetimes_to_define.len();
745 let hir_name = hir::LifetimeName::Fresh(index);
746 self.lifetimes_to_define.push((span, hir_name));
750 // Evaluates `f` with the lifetimes in `params` in-scope.
751 // This is used to track which lifetimes have already been defined, and
752 // which are new in-band lifetimes that need to have a definition created
754 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &Vec<GenericParam>, f: F) -> T
756 F: FnOnce(&mut LoweringContext) -> T,
758 let old_len = self.in_scope_lifetimes.len();
759 let lt_def_names = params.iter().filter_map(|param| match param.kind {
760 GenericParamKind::Lifetime { .. } => Some(param.ident.name),
763 self.in_scope_lifetimes.extend(lt_def_names);
767 self.in_scope_lifetimes.truncate(old_len);
771 // Same as the method above, but accepts `hir::GenericParam`s
772 // instead of `ast::GenericParam`s.
773 // This should only be used with generics that have already had their
774 // in-band lifetimes added. In practice, this means that this function is
775 // only used when lowering a child item of a trait or impl.
776 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
777 params: &HirVec<hir::GenericParam>,
780 F: FnOnce(&mut LoweringContext) -> T,
782 let old_len = self.in_scope_lifetimes.len();
783 let lt_def_names = params.iter().filter_map(|param| match param.kind {
784 hir::GenericParamKind::Lifetime { .. } => Some(param.name),
787 self.in_scope_lifetimes.extend(lt_def_names);
791 self.in_scope_lifetimes.truncate(old_len);
795 /// Appends in-band lifetime defs and argument-position `impl
796 /// Trait` defs to the existing set of generics.
798 /// Presuming that in-band lifetimes are enabled, then
799 /// `self.anonymous_lifetime_mode` will be updated to match the
800 /// argument while `f` is running (and restored afterwards).
801 fn add_in_band_defs<F, T>(
805 anonymous_lifetime_mode: AnonymousLifetimeMode,
807 ) -> (hir::Generics, T)
809 F: FnOnce(&mut LoweringContext) -> T,
811 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
814 let itctx = ImplTraitContext::Universal(parent_id);
815 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
816 (this.lower_generics(generics, itctx), f(this))
821 lowered_generics.params = lowered_generics
828 (lowered_generics, res)
831 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
833 F: FnOnce(&mut LoweringContext) -> T,
835 let len = self.catch_scopes.len();
836 self.catch_scopes.push(catch_id);
838 let result = f(self);
841 self.catch_scopes.len(),
842 "catch scopes should be added and removed in stack order"
845 self.catch_scopes.pop().unwrap();
850 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
852 F: FnOnce(&mut LoweringContext) -> hir::Expr,
854 let prev = mem::replace(&mut self.is_generator, false);
855 let result = f(self);
856 let r = self.record_body(result, decl);
857 self.is_generator = prev;
861 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
863 F: FnOnce(&mut LoweringContext) -> T,
865 // We're no longer in the base loop's condition; we're in another loop.
866 let was_in_loop_condition = self.is_in_loop_condition;
867 self.is_in_loop_condition = false;
869 let len = self.loop_scopes.len();
870 self.loop_scopes.push(loop_id);
872 let result = f(self);
875 self.loop_scopes.len(),
876 "Loop scopes should be added and removed in stack order"
879 self.loop_scopes.pop().unwrap();
881 self.is_in_loop_condition = was_in_loop_condition;
886 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
888 F: FnOnce(&mut LoweringContext) -> T,
890 let was_in_loop_condition = self.is_in_loop_condition;
891 self.is_in_loop_condition = true;
893 let result = f(self);
895 self.is_in_loop_condition = was_in_loop_condition;
900 fn with_new_scopes<T, F>(&mut self, f: F) -> T
902 F: FnOnce(&mut LoweringContext) -> T,
904 let was_in_loop_condition = self.is_in_loop_condition;
905 self.is_in_loop_condition = false;
907 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
908 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
909 let result = f(self);
910 self.catch_scopes = catch_scopes;
911 self.loop_scopes = loop_scopes;
913 self.is_in_loop_condition = was_in_loop_condition;
918 fn def_key(&mut self, id: DefId) -> DefKey {
920 self.resolver.definitions().def_key(id.index)
922 self.cstore.def_key(id)
926 fn lower_ident(&mut self, ident: Ident) -> Name {
927 let ident = ident.modern();
928 if ident.span.ctxt() == SyntaxContext::empty() {
933 .or_insert_with(|| Symbol::from_ident(ident))
936 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
937 label.map(|label| hir::Label {
938 name: label.ident.name,
939 span: label.ident.span,
943 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
945 Some((id, label)) => {
946 let target_id = if let Def::Label(loop_id) = self.expect_full_def(id) {
947 Ok(self.lower_node_id(loop_id).node_id)
949 Err(hir::LoopIdError::UnresolvedLabel)
952 label: self.lower_label(Some(label)),
957 let target_id = self.loop_scopes
959 .map(|innermost_loop_id| *innermost_loop_id)
960 .map(|id| Ok(self.lower_node_id(id).node_id))
961 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
972 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
975 .map(|a| self.lower_attr(a))
980 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
984 path: attr.path.clone(),
985 tokens: self.lower_token_stream(attr.tokens.clone()),
986 is_sugared_doc: attr.is_sugared_doc,
991 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
994 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
998 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1000 TokenTree::Token(span, token) => self.lower_token(token, span),
1001 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1004 delim: delimited.delim,
1005 tts: self.lower_token_stream(delimited.tts.into()).into(),
1011 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1013 Token::Interpolated(_) => {}
1014 other => return TokenTree::Token(span, other).into(),
1017 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1018 self.lower_token_stream(tts)
1021 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1023 attrs: self.lower_attrs(&arm.attrs),
1024 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1025 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1026 body: P(self.lower_expr(&arm.body)),
1030 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1032 id: self.lower_node_id(b.id).node_id,
1033 name: self.lower_ident(b.ident),
1034 ty: self.lower_ty(&b.ty, itctx),
1039 fn lower_generic_arg(&mut self,
1040 arg: &ast::GenericArg,
1041 itctx: ImplTraitContext)
1042 -> hir::GenericArg {
1044 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1045 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty(&ty, itctx)),
1049 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1050 let kind = match t.node {
1051 TyKind::Infer => hir::TyInfer,
1052 TyKind::Err => hir::TyErr,
1053 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty, itctx)),
1054 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt, itctx)),
1055 TyKind::Rptr(ref region, ref mt) => {
1056 let span = t.span.shrink_to_lo();
1057 let lifetime = match *region {
1058 Some(ref lt) => self.lower_lifetime(lt),
1059 None => self.elided_ref_lifetime(span),
1061 hir::TyRptr(lifetime, self.lower_mt(mt, itctx))
1063 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1066 this.with_anonymous_lifetime_mode(
1067 AnonymousLifetimeMode::PassThrough,
1069 hir::TyBareFn(P(hir::BareFnTy {
1070 generic_params: this.lower_generic_params(
1073 ImplTraitContext::Disallowed,
1075 unsafety: this.lower_unsafety(f.unsafety),
1077 decl: this.lower_fn_decl(&f.decl, None, false),
1078 arg_names: this.lower_fn_args_to_names(&f.decl),
1084 TyKind::Never => hir::TyNever,
1085 TyKind::Tup(ref tys) => {
1086 hir::TyTup(tys.iter().map(|ty| self.lower_ty(ty, itctx)).collect())
1088 TyKind::Paren(ref ty) => {
1089 return self.lower_ty(ty, itctx);
1091 TyKind::Path(ref qself, ref path) => {
1092 let id = self.lower_node_id(t.id);
1093 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1094 let ty = self.ty_path(id, t.span, qpath);
1095 if let hir::TyTraitObject(..) = ty.node {
1096 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1100 TyKind::ImplicitSelf => hir::TyPath(hir::QPath::Resolved(
1103 def: self.expect_full_def(t.id),
1104 segments: hir_vec![hir::PathSegment::from_name(keywords::SelfType.name())],
1108 TyKind::Array(ref ty, ref length) => {
1109 hir::TyArray(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1111 TyKind::Typeof(ref expr) => {
1112 hir::TyTypeof(self.lower_anon_const(expr))
1114 TyKind::TraitObject(ref bounds, kind) => {
1115 let mut lifetime_bound = None;
1118 .filter_map(|bound| match *bound {
1119 TraitTyParamBound(ref ty, TraitBoundModifier::None) => {
1120 Some(self.lower_poly_trait_ref(ty, itctx))
1122 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
1123 Outlives(ref lifetime) => {
1124 if lifetime_bound.is_none() {
1125 lifetime_bound = Some(self.lower_lifetime(lifetime));
1131 let lifetime_bound =
1132 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1133 if kind != TraitObjectSyntax::Dyn {
1134 self.maybe_lint_bare_trait(t.span, t.id, false);
1136 hir::TyTraitObject(bounds, lifetime_bound)
1138 TyKind::ImplTrait(ref bounds) => {
1141 ImplTraitContext::Existential(fn_def_id) => {
1143 // We need to manually repeat the code of `next_id` because the lowering
1144 // needs to happen while the owner_id is pointing to the item itself,
1145 // because items are their own owners
1146 let exist_ty_node_id = self.sess.next_node_id();
1148 // Make sure we know that some funky desugaring has been going on here.
1149 // This is a first: there is code in other places like for loop
1150 // desugaring that explicitly states that we don't want to track that.
1151 // Not tracking it makes lints in rustc and clippy very fragile as
1152 // frequently opened issues show.
1153 let exist_ty_span = self.allow_internal_unstable(
1154 CompilerDesugaringKind::ExistentialReturnType,
1158 // Pull a new definition from the ether
1159 let exist_ty_def_index = self
1162 .create_def_with_parent(
1165 DefPathData::ExistentialImplTrait,
1166 DefIndexAddressSpace::High,
1171 // the `t` is just for printing debug messages
1172 self.allocate_hir_id_counter(exist_ty_node_id, t);
1174 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1175 lctx.lower_bounds(bounds, itctx)
1178 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1184 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1185 let exist_ty_item_kind = hir::ItemExistential(hir::ExistTy {
1186 generics: hir::Generics {
1187 params: lifetime_defs,
1188 where_clause: hir::WhereClause {
1189 id: lctx.next_id().node_id,
1190 predicates: Vec::new().into(),
1195 impl_trait_fn: Some(fn_def_id),
1197 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1198 // Generate an `existential type Foo: Trait;` declaration
1199 trace!("creating existential type with id {:#?}", exist_ty_id);
1200 // Set the name to `impl Bound1 + Bound2`
1201 let exist_ty_name = Symbol::intern(&pprust::ty_to_string(t));
1203 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1204 let exist_ty_item = hir::Item {
1205 id: exist_ty_id.node_id,
1206 hir_id: exist_ty_id.hir_id,
1207 name: exist_ty_name,
1208 attrs: Default::default(),
1209 node: exist_ty_item_kind,
1210 vis: hir::Visibility::Inherited,
1211 span: exist_ty_span,
1214 // Insert the item into the global list. This usually happens
1215 // automatically for all AST items. But this existential type item
1216 // does not actually exist in the AST.
1217 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1219 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1220 hir::TyImplTraitExistential(
1222 id: exist_ty_id.node_id
1224 DefId::local(exist_ty_def_index),
1229 ImplTraitContext::Universal(def_id) => {
1230 let def_node_id = self.next_id().node_id;
1232 // Add a definition for the in-band TyParam
1233 let def_index = self.resolver.definitions().create_def_with_parent(
1236 DefPathData::UniversalImplTrait,
1237 DefIndexAddressSpace::High,
1242 let hir_bounds = self.lower_param_bounds(bounds, itctx);
1243 // Set the name to `impl Bound1 + Bound2`
1244 let name = Symbol::intern(&pprust::ty_to_string(t));
1245 self.in_band_ty_params.push(hir::GenericParam {
1249 pure_wrt_drop: false,
1251 kind: hir::GenericParamKind::Type {
1253 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1258 hir::TyPath(hir::QPath::Resolved(
1262 def: Def::TyParam(DefId::local(def_index)),
1263 segments: hir_vec![hir::PathSegment::from_name(name)],
1267 ImplTraitContext::Disallowed => {
1272 "`impl Trait` not allowed outside of function \
1273 and inherent method return types"
1279 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1282 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1291 fn lifetimes_from_impl_trait_bounds(
1293 exist_ty_id: NodeId,
1294 parent_index: DefIndex,
1295 bounds: &hir::ParamBounds,
1296 ) -> (HirVec<hir::Lifetime>, HirVec<hir::GenericParam>) {
1297 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1298 // appear in the bounds, excluding lifetimes that are created within the bounds.
1299 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1300 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1301 context: &'r mut LoweringContext<'a>,
1303 exist_ty_id: NodeId,
1304 collect_elided_lifetimes: bool,
1305 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1306 already_defined_lifetimes: HashSet<hir::LifetimeName>,
1307 output_lifetimes: Vec<hir::Lifetime>,
1308 output_lifetime_params: Vec<hir::GenericParam>,
1311 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1312 fn nested_visit_map<'this>(
1314 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1315 hir::intravisit::NestedVisitorMap::None
1318 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1319 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1320 if parameters.parenthesized {
1321 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1322 self.collect_elided_lifetimes = false;
1323 hir::intravisit::walk_generic_args(self, span, parameters);
1324 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1326 hir::intravisit::walk_generic_args(self, span, parameters);
1330 fn visit_ty(&mut self, t: &'v hir::Ty) {
1331 // Don't collect elided lifetimes used inside of `fn()` syntax
1332 if let &hir::Ty_::TyBareFn(_) = &t.node {
1333 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1334 self.collect_elided_lifetimes = false;
1336 // Record the "stack height" of `for<'a>` lifetime bindings
1337 // to be able to later fully undo their introduction.
1338 let old_len = self.currently_bound_lifetimes.len();
1339 hir::intravisit::walk_ty(self, t);
1340 self.currently_bound_lifetimes.truncate(old_len);
1342 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1344 hir::intravisit::walk_ty(self, t);
1348 fn visit_poly_trait_ref(
1350 trait_ref: &'v hir::PolyTraitRef,
1351 modifier: hir::TraitBoundModifier,
1353 // Record the "stack height" of `for<'a>` lifetime bindings
1354 // to be able to later fully undo their introduction.
1355 let old_len = self.currently_bound_lifetimes.len();
1356 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1357 self.currently_bound_lifetimes.truncate(old_len);
1360 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1361 // Record the introduction of 'a in `for<'a> ...`
1362 if let hir::GenericParamKind::Lifetime { lt_name, .. } = param.kind {
1363 // Introduce lifetimes one at a time so that we can handle
1364 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1365 self.currently_bound_lifetimes.push(lt_name);
1368 hir::intravisit::walk_generic_param(self, param);
1371 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1372 let name = match lifetime.name {
1373 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1374 if self.collect_elided_lifetimes {
1375 // Use `'_` for both implicit and underscore lifetimes in
1376 // `abstract type Foo<'_>: SomeTrait<'_>;`
1377 hir::LifetimeName::Underscore
1382 name @ hir::LifetimeName::Fresh(_) => name,
1383 name @ hir::LifetimeName::Name(_) => name,
1384 hir::LifetimeName::Static => return,
1387 if !self.currently_bound_lifetimes.contains(&name)
1388 && !self.already_defined_lifetimes.contains(&name)
1390 self.already_defined_lifetimes.insert(name);
1392 self.output_lifetimes.push(hir::Lifetime {
1393 id: self.context.next_id().node_id,
1394 span: lifetime.span,
1398 // We need to manually create the ids here, because the
1399 // definitions will go into the explicit `existential type`
1400 // declaration and thus need to have their owner set to that item
1401 let def_node_id = self.context.sess.next_node_id();
1402 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1403 self.context.resolver.definitions().create_def_with_parent(
1406 DefPathData::LifetimeParam(name.name().as_interned_str()),
1407 DefIndexAddressSpace::High,
1412 self.output_lifetime_params.push(hir::GenericParam {
1415 span: lifetime.span,
1416 pure_wrt_drop: false,
1417 bounds: vec![].into(),
1418 kind: hir::GenericParamKind::Lifetime {
1427 let mut lifetime_collector = ImplTraitLifetimeCollector {
1429 parent: parent_index,
1431 collect_elided_lifetimes: true,
1432 currently_bound_lifetimes: Vec::new(),
1433 already_defined_lifetimes: HashSet::new(),
1434 output_lifetimes: Vec::new(),
1435 output_lifetime_params: Vec::new(),
1438 for bound in bounds {
1439 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1443 lifetime_collector.output_lifetimes.into(),
1444 lifetime_collector.output_lifetime_params.into(),
1448 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1453 .map(|x| self.lower_foreign_item(x))
1458 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1465 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1467 node: hir::Variant_ {
1468 name: v.node.ident.name,
1469 attrs: self.lower_attrs(&v.node.attrs),
1470 data: self.lower_variant_data(&v.node.data),
1471 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1480 qself: &Option<QSelf>,
1482 param_mode: ParamMode,
1483 itctx: ImplTraitContext,
1485 let qself_position = qself.as_ref().map(|q| q.position);
1486 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx));
1488 let resolution = self.resolver
1490 .unwrap_or(PathResolution::new(Def::Err));
1492 let proj_start = p.segments.len() - resolution.unresolved_segments();
1493 let path = P(hir::Path {
1494 def: resolution.base_def(),
1495 segments: p.segments[..proj_start]
1498 .map(|(i, segment)| {
1499 let param_mode = match (qself_position, param_mode) {
1500 (Some(j), ParamMode::Optional) if i < j => {
1501 // This segment is part of the trait path in a
1502 // qualified path - one of `a`, `b` or `Trait`
1503 // in `<X as a::b::Trait>::T::U::method`.
1509 // Figure out if this is a type/trait segment,
1510 // which may need lifetime elision performed.
1511 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1512 krate: def_id.krate,
1513 index: this.def_key(def_id).parent.expect("missing parent"),
1515 let type_def_id = match resolution.base_def() {
1516 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1517 Some(parent_def_id(self, def_id))
1519 Def::Variant(def_id) if i + 1 == proj_start => {
1520 Some(parent_def_id(self, def_id))
1523 | Def::Union(def_id)
1525 | Def::TyAlias(def_id)
1526 | Def::Trait(def_id) if i + 1 == proj_start =>
1532 let parenthesized_generic_args = match resolution.base_def() {
1533 // `a::b::Trait(Args)`
1534 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1535 // `a::b::Trait(Args)::TraitItem`
1536 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1537 if i + 2 == proj_start =>
1539 ParenthesizedGenericArgs::Ok
1541 // Avoid duplicated errors
1542 Def::Err => ParenthesizedGenericArgs::Ok,
1548 | Def::Variant(..) if i + 1 == proj_start =>
1550 ParenthesizedGenericArgs::Err
1552 // A warning for now, for compatibility reasons
1553 _ => ParenthesizedGenericArgs::Warn,
1556 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1557 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1560 assert!(!def_id.is_local());
1562 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1563 let n = item_generics.own_counts().lifetimes;
1564 self.type_def_lifetime_params.insert(def_id, n);
1567 self.lower_path_segment(
1572 parenthesized_generic_args,
1580 // Simple case, either no projections, or only fully-qualified.
1581 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1582 if resolution.unresolved_segments() == 0 {
1583 return hir::QPath::Resolved(qself, path);
1586 // Create the innermost type that we're projecting from.
1587 let mut ty = if path.segments.is_empty() {
1588 // If the base path is empty that means there exists a
1589 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1590 qself.expect("missing QSelf for <T>::...")
1592 // Otherwise, the base path is an implicit `Self` type path,
1593 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1594 // `<I as Iterator>::Item::default`.
1595 let new_id = self.next_id();
1596 self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))
1599 // Anything after the base path are associated "extensions",
1600 // out of which all but the last one are associated types,
1601 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1602 // * base path is `std::vec::Vec<T>`
1603 // * "extensions" are `IntoIter`, `Item` and `clone`
1604 // * type nodes are:
1605 // 1. `std::vec::Vec<T>` (created above)
1606 // 2. `<std::vec::Vec<T>>::IntoIter`
1607 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1608 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1609 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1610 let segment = P(self.lower_path_segment(
1615 ParenthesizedGenericArgs::Warn,
1618 let qpath = hir::QPath::TypeRelative(ty, segment);
1620 // It's finished, return the extension of the right node type.
1621 if i == p.segments.len() - 1 {
1625 // Wrap the associated extension in another type node.
1626 let new_id = self.next_id();
1627 ty = self.ty_path(new_id, p.span, qpath);
1630 // Should've returned in the for loop above.
1633 "lower_qpath: no final extension segment in {}..{}",
1639 fn lower_path_extra(
1644 param_mode: ParamMode,
1648 segments: p.segments
1651 self.lower_path_segment(
1656 ParenthesizedGenericArgs::Err,
1657 ImplTraitContext::Disallowed,
1660 .chain(name.map(|name| hir::PathSegment::from_name(name)))
1666 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1667 let def = self.expect_full_def(id);
1668 self.lower_path_extra(def, p, None, param_mode)
1671 fn lower_path_segment(
1674 segment: &PathSegment,
1675 param_mode: ParamMode,
1676 expected_lifetimes: usize,
1677 parenthesized_generic_args: ParenthesizedGenericArgs,
1678 itctx: ImplTraitContext,
1679 ) -> hir::PathSegment {
1680 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1681 let msg = "parenthesized parameters may only be used with a trait";
1682 match **generic_args {
1683 GenericArgs::AngleBracketed(ref data) => {
1684 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1686 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1687 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1688 ParenthesizedGenericArgs::Warn => {
1689 self.sess.buffer_lint(
1690 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1695 (hir::GenericArgs::none(), true)
1697 ParenthesizedGenericArgs::Err => {
1698 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1699 .span_label(data.span, "only traits may use parentheses")
1701 (hir::GenericArgs::none(), true)
1706 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1709 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1710 GenericArg::Lifetime(_) => true,
1713 if !generic_args.parenthesized && !has_lifetimes {
1715 self.elided_path_lifetimes(path_span, expected_lifetimes)
1717 .map(|lt| GenericArg::Lifetime(lt))
1718 .chain(generic_args.args.into_iter())
1722 hir::PathSegment::new(
1723 self.lower_ident(segment.ident),
1729 fn lower_angle_bracketed_parameter_data(
1731 data: &AngleBracketedArgs,
1732 param_mode: ParamMode,
1733 itctx: ImplTraitContext,
1734 ) -> (hir::GenericArgs, bool) {
1735 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1736 let has_types = args.iter().any(|arg| match arg {
1737 ast::GenericArg::Type(_) => true,
1741 args: args.iter().map(|a| self.lower_generic_arg(a, itctx)).collect(),
1742 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(),
1743 parenthesized: false,
1745 !has_types && param_mode == ParamMode::Optional)
1748 fn lower_parenthesized_parameter_data(
1750 data: &ParenthesizedParameterData,
1751 ) -> (hir::PathParameters, bool) {
1752 // Switch to `PassThrough` mode for anonymous lifetimes: this
1753 // means that we permit things like `&Ref<T>`, where `Ref` has
1754 // a hidden lifetime parameter. This is needed for backwards
1755 // compatibility, even in contexts like an impl header where
1756 // we generally don't permit such things (see #51008).
1757 self.with_anonymous_lifetime_mode(
1758 AnonymousLifetimeMode::PassThrough,
1760 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1761 let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
1762 let inputs = inputs.iter().map(|ty| this.lower_ty(ty, DISALLOWED)).collect();
1763 let mk_tup = |this: &mut Self, tys, span| {
1764 let LoweredNodeId { node_id, hir_id } = this.next_id();
1765 P(hir::Ty { node: hir::TyTup(tys), id: node_id, hir_id, span })
1770 parameters: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1773 id: this.next_id().node_id,
1774 name: Symbol::intern(FN_OUTPUT_NAME),
1777 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1778 .unwrap_or_else(|| mk_tup(this, hir::HirVec::new(), span)),
1779 span: output.as_ref().map_or(span, |ty| ty.span),
1782 parenthesized: true,
1790 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1791 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1797 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1798 pat: self.lower_pat(&l.pat),
1799 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1801 attrs: l.attrs.clone(),
1802 source: hir::LocalSource::Normal,
1806 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1808 Mutability::Mutable => hir::MutMutable,
1809 Mutability::Immutable => hir::MutImmutable,
1813 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1814 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1818 pat: self.lower_pat(&arg.pat),
1822 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Spanned<Name>> {
1825 .map(|arg| match arg.pat.node {
1826 PatKind::Ident(_, ident, None) => respan(ident.span, ident.name),
1827 _ => respan(arg.pat.span, keywords::Invalid.name()),
1835 fn_def_id: Option<DefId>,
1836 impl_trait_return_allow: bool,
1837 ) -> P<hir::FnDecl> {
1838 // NOTE: The two last parameters here have to do with impl Trait. If fn_def_id is Some,
1839 // then impl Trait arguments are lowered into generic parameters on the given
1840 // fn_def_id, otherwise impl Trait is disallowed. (for now)
1842 // Furthermore, if impl_trait_return_allow is true, then impl Trait may be used in
1843 // return positions as well. This guards against trait declarations and their impls
1844 // where impl Trait is disallowed. (again for now)
1849 if let Some(def_id) = fn_def_id {
1850 self.lower_ty(&arg.ty, ImplTraitContext::Universal(def_id))
1852 self.lower_ty(&arg.ty, ImplTraitContext::Disallowed)
1856 output: match decl.output {
1857 FunctionRetTy::Ty(ref ty) => match fn_def_id {
1858 Some(def_id) if impl_trait_return_allow => {
1859 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1861 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1863 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1865 variadic: decl.variadic,
1866 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1867 TyKind::ImplicitSelf => true,
1868 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1874 fn lower_param_bound(
1877 itctx: ImplTraitContext,
1878 ) -> hir::ParamBound {
1880 TraitTyParamBound(ref ty, modifier) => hir::TraitTyParamBound(
1881 self.lower_poly_trait_ref(ty, itctx),
1882 self.lower_trait_bound_modifier(modifier),
1884 Outlives(ref lifetime) => {
1885 hir::Outlives(self.lower_lifetime(lifetime))
1890 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1891 let span = l.ident.span;
1892 match self.lower_ident(l.ident) {
1893 x if x == "'static" => self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
1894 x if x == "'_" => match self.anonymous_lifetime_mode {
1895 AnonymousLifetimeMode::CreateParameter => {
1896 let fresh_name = self.collect_fresh_in_band_lifetime(span);
1897 self.new_named_lifetime(l.id, span, fresh_name)
1900 AnonymousLifetimeMode::PassThrough => {
1901 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
1905 self.maybe_collect_in_band_lifetime(span, name);
1906 self.new_named_lifetime(l.id, span, hir::LifetimeName::Name(name))
1911 fn new_named_lifetime(
1915 name: hir::LifetimeName,
1916 ) -> hir::Lifetime {
1918 id: self.lower_node_id(id).node_id,
1924 fn lower_generic_params(
1926 params: &Vec<GenericParam>,
1927 add_bounds: &NodeMap<Vec<ParamBound>>,
1928 itctx: ImplTraitContext,
1929 ) -> hir::HirVec<hir::GenericParam> {
1930 params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect()
1933 fn lower_generic_param(&mut self,
1934 param: &GenericParam,
1935 add_bounds: &NodeMap<Vec<ParamBound>>,
1936 itctx: ImplTraitContext)
1937 -> hir::GenericParam {
1938 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx);
1940 GenericParamKind::Lifetime => {
1941 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
1942 self.is_collecting_in_band_lifetimes = false;
1944 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
1945 let param = hir::GenericParam {
1947 name: lt.name.name(),
1949 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
1951 kind: hir::GenericParamKind::Lifetime {
1957 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
1961 GenericParamKind::Type { ref default, .. } => {
1962 let mut name = self.lower_ident(param.ident);
1964 // Don't expose `Self` (recovered "keyword used as ident" parse error).
1965 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
1966 // Instead, use gensym("Self") to create a distinct name that looks the same.
1967 if name == keywords::SelfType.name() {
1968 name = Symbol::gensym("Self");
1971 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
1972 if !add_bounds.is_empty() {
1973 bounds = bounds.into_iter()
1974 .chain(self.lower_param_bounds(add_bounds, itctx).into_iter())
1979 id: self.lower_node_id(param.id).node_id,
1981 span: param.ident.span,
1982 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
1984 kind: hir::GenericParamKind::Type {
1985 default: default.as_ref().map(|x| {
1986 self.lower_ty(x, ImplTraitContext::Disallowed)
1988 synthetic: param.attrs.iter()
1989 .filter(|attr| attr.check_name("rustc_synthetic"))
1990 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
1992 attrs: self.lower_attrs(¶m.attrs),
2001 generics: &Generics,
2002 itctx: ImplTraitContext)
2005 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2006 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2007 // paths where report_error is called are also the only paths that advance to after
2008 // the match statement, so the error reporting could probably just be moved there.
2009 let mut add_bounds = NodeMap();
2010 for pred in &generics.where_clause.predicates {
2011 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2012 'next_bound: for bound in &bound_pred.bounds {
2013 if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
2014 let report_error = |this: &mut Self| {
2015 this.diagnostic().span_err(
2016 bound_pred.bounded_ty.span,
2017 "`?Trait` bounds are only permitted at the \
2018 point where a type parameter is declared",
2021 // Check if the where clause type is a plain type parameter.
2022 match bound_pred.bounded_ty.node {
2023 TyKind::Path(None, ref path)
2024 if path.segments.len() == 1
2025 && bound_pred.bound_generic_params.is_empty() =>
2027 if let Some(Def::TyParam(def_id)) = self.resolver
2028 .get_resolution(bound_pred.bounded_ty.id)
2029 .map(|d| d.base_def())
2031 if let Some(node_id) =
2032 self.resolver.definitions().as_local_node_id(def_id)
2034 for param in &generics.params {
2036 GenericParamKind::Type { .. } => {
2037 if node_id == param.id {
2038 add_bounds.entry(param.id)
2039 .or_insert(Vec::new())
2040 .push(bound.clone());
2041 continue 'next_bound;
2051 _ => report_error(self),
2059 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2060 where_clause: self.lower_where_clause(&generics.where_clause),
2061 span: generics.span,
2065 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2067 id: self.lower_node_id(wc.id).node_id,
2068 predicates: wc.predicates
2070 .map(|predicate| self.lower_where_predicate(predicate))
2075 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2077 WherePredicate::BoundPredicate(WhereBoundPredicate {
2078 ref bound_generic_params,
2083 self.with_in_scope_lifetime_defs(
2084 &bound_generic_params,
2086 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2087 bound_generic_params: this.lower_generic_params(
2088 bound_generic_params,
2090 ImplTraitContext::Disallowed,
2092 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2095 .filter_map(|bound| match *bound {
2096 // Ignore `?Trait` bounds.
2097 // Tthey were copied into type parameters already.
2098 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
2099 _ => Some(this.lower_param_bound(
2101 ImplTraitContext::Disallowed,
2110 WherePredicate::RegionPredicate(WhereRegionPredicate {
2114 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2116 lifetime: self.lower_lifetime(lifetime),
2117 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2119 WherePredicate::EqPredicate(WhereEqPredicate {
2124 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2125 id: self.lower_node_id(id).node_id,
2126 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2127 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2133 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2135 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2139 .map(|f| self.lower_struct_field(f))
2141 self.lower_node_id(id).node_id,
2143 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2147 .map(|f| self.lower_struct_field(f))
2149 self.lower_node_id(id).node_id,
2151 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2155 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2156 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2157 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2158 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2162 ref_id: self.lower_node_id(p.ref_id).node_id,
2166 fn lower_poly_trait_ref(
2169 itctx: ImplTraitContext,
2170 ) -> hir::PolyTraitRef {
2171 let bound_generic_params =
2172 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx);
2173 let trait_ref = self.with_parent_impl_lifetime_defs(
2174 &bound_generic_params,
2175 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2179 bound_generic_params,
2185 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2188 id: self.lower_node_id(f.id).node_id,
2189 ident: match f.ident {
2190 Some(ident) => ident,
2191 // FIXME(jseyfried) positional field hygiene
2192 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2194 vis: self.lower_visibility(&f.vis, None),
2195 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2196 attrs: self.lower_attrs(&f.attrs),
2200 fn lower_field(&mut self, f: &Field) -> hir::Field {
2202 id: self.next_id().node_id,
2204 expr: P(self.lower_expr(&f.expr)),
2206 is_shorthand: f.is_shorthand,
2210 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2212 ty: self.lower_ty(&mt.ty, itctx),
2213 mutbl: self.lower_mutability(mt.mutbl),
2217 fn lower_param_bounds(&mut self, bounds: &[ParamBound], itctx: ImplTraitContext)
2218 -> hir::ParamBounds {
2219 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx)).collect()
2222 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2223 let mut expr = None;
2225 let mut stmts = vec![];
2227 for (index, stmt) in b.stmts.iter().enumerate() {
2228 if index == b.stmts.len() - 1 {
2229 if let StmtKind::Expr(ref e) = stmt.node {
2230 expr = Some(P(self.lower_expr(e)));
2232 stmts.extend(self.lower_stmt(stmt));
2235 stmts.extend(self.lower_stmt(stmt));
2239 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2244 stmts: stmts.into(),
2246 rules: self.lower_block_check_mode(&b.rules),
2249 recovered: b.recovered,
2257 attrs: &hir::HirVec<Attribute>,
2258 vis: &mut hir::Visibility,
2262 ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2263 ItemKind::Use(ref use_tree) => {
2264 // Start with an empty prefix
2267 span: use_tree.span,
2270 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2272 ItemKind::Static(ref t, m, ref e) => {
2273 let value = self.lower_body(None, |this| this.lower_expr(e));
2275 self.lower_ty(t, ImplTraitContext::Disallowed),
2276 self.lower_mutability(m),
2280 ItemKind::Const(ref t, ref e) => {
2281 let value = self.lower_body(None, |this| this.lower_expr(e));
2282 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2284 ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
2285 let fn_def_id = self.resolver.definitions().local_def_id(id);
2286 self.with_new_scopes(|this| {
2287 let body_id = this.lower_body(Some(decl), |this| {
2288 let body = this.lower_block(body, false);
2289 this.expr_block(body, ThinVec::new())
2291 let (generics, fn_decl) = this.add_in_band_defs(
2294 AnonymousLifetimeMode::PassThrough,
2295 |this| this.lower_fn_decl(decl, Some(fn_def_id), true),
2300 this.lower_unsafety(unsafety),
2301 this.lower_constness(constness),
2308 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2309 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2310 ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2311 ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2312 self.lower_ty(t, ImplTraitContext::Disallowed),
2313 self.lower_generics(generics, ImplTraitContext::Disallowed),
2315 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2317 variants: enum_definition
2320 .map(|x| self.lower_variant(x))
2323 self.lower_generics(generics, ImplTraitContext::Disallowed),
2325 ItemKind::Struct(ref struct_def, ref generics) => {
2326 let struct_def = self.lower_variant_data(struct_def);
2329 self.lower_generics(generics, ImplTraitContext::Disallowed),
2332 ItemKind::Union(ref vdata, ref generics) => {
2333 let vdata = self.lower_variant_data(vdata);
2336 self.lower_generics(generics, ImplTraitContext::Disallowed),
2348 let def_id = self.resolver.definitions().local_def_id(id);
2350 // Lower the "impl header" first. This ordering is important
2351 // for in-band lifetimes! Consider `'a` here:
2353 // impl Foo<'a> for u32 {
2354 // fn method(&'a self) { .. }
2357 // Because we start by lowering the `Foo<'a> for u32`
2358 // part, we will add `'a` to the list of generics on
2359 // the impl. When we then encounter it later in the
2360 // method, it will not be considered an in-band
2361 // lifetime to be added, but rather a reference to a
2363 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2366 AnonymousLifetimeMode::CreateParameter,
2368 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2369 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2372 if let Some(ref trait_ref) = trait_ref {
2373 if let Def::Trait(def_id) = trait_ref.path.def {
2374 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2378 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2380 (trait_ref, lowered_ty)
2384 let new_impl_items = self.with_in_scope_lifetime_defs(
2385 &ast_generics.params,
2389 .map(|item| this.lower_impl_item_ref(item))
2395 self.lower_unsafety(unsafety),
2396 self.lower_impl_polarity(polarity),
2397 self.lower_defaultness(defaultness, true /* [1] */),
2404 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2405 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2408 .map(|item| self.lower_trait_item_ref(item))
2411 self.lower_is_auto(is_auto),
2412 self.lower_unsafety(unsafety),
2413 self.lower_generics(generics, ImplTraitContext::Disallowed),
2418 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2419 self.lower_generics(generics, ImplTraitContext::Disallowed),
2420 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2422 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2425 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2426 // not cause an assertion failure inside the `lower_defaultness` function
2434 vis: &mut hir::Visibility,
2436 attrs: &hir::HirVec<Attribute>,
2438 let path = &tree.prefix;
2441 UseTreeKind::Simple(rename, id1, id2) => {
2442 *name = tree.ident().name;
2444 // First apply the prefix to the path
2445 let mut path = Path {
2449 .chain(path.segments.iter())
2455 // Correctly resolve `self` imports
2456 if path.segments.len() > 1
2457 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2459 let _ = path.segments.pop();
2460 if rename.is_none() {
2461 *name = path.segments.last().unwrap().ident.name;
2465 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2466 let mut defs = self.expect_full_def_from_use(id);
2467 // we want to return *something* from this function, so hang onto the first item
2469 let mut ret_def = defs.next().unwrap_or(Def::Err);
2471 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2472 let vis = vis.clone();
2473 let name = name.clone();
2474 let span = path.span;
2475 self.resolver.definitions().create_def_with_parent(
2479 DefIndexAddressSpace::High,
2482 self.allocate_hir_id_counter(new_node_id, &path);
2484 self.with_hir_id_owner(new_node_id, |this| {
2485 let new_id = this.lower_node_id(new_node_id);
2486 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2487 let item = hir::ItemUse(P(path), hir::UseKind::Single);
2488 let vis = match vis {
2489 hir::Visibility::Public => hir::Visibility::Public,
2490 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2491 hir::Visibility::Inherited => hir::Visibility::Inherited,
2492 hir::Visibility::Restricted { ref path, id: _ } => {
2493 hir::Visibility::Restricted {
2495 // We are allocating a new NodeId here
2496 id: this.next_id().node_id,
2505 hir_id: new_id.hir_id,
2507 attrs: attrs.clone(),
2516 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2517 hir::ItemUse(path, hir::UseKind::Single)
2519 UseTreeKind::Glob => {
2520 let path = P(self.lower_path(
2526 .chain(path.segments.iter())
2531 ParamMode::Explicit,
2533 hir::ItemUse(path, hir::UseKind::Glob)
2535 UseTreeKind::Nested(ref trees) => {
2540 .chain(path.segments.iter())
2543 span: prefix.span.to(path.span),
2546 // Add all the nested PathListItems in the HIR
2547 for &(ref use_tree, id) in trees {
2548 self.allocate_hir_id_counter(id, &use_tree);
2552 } = self.lower_node_id(id);
2554 let mut vis = vis.clone();
2555 let mut name = name.clone();
2557 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2559 self.with_hir_id_owner(new_id, |this| {
2560 let vis = match vis {
2561 hir::Visibility::Public => hir::Visibility::Public,
2562 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2563 hir::Visibility::Inherited => hir::Visibility::Inherited,
2564 hir::Visibility::Restricted { ref path, id: _ } => {
2565 hir::Visibility::Restricted {
2567 // We are allocating a new NodeId here
2568 id: this.next_id().node_id,
2579 attrs: attrs.clone(),
2582 span: use_tree.span,
2588 // Privatize the degenerate import base, used only to check
2589 // the stability of `use a::{};`, to avoid it showing up as
2590 // a re-export by accident when `pub`, e.g. in documentation.
2591 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2592 *vis = hir::Inherited;
2593 hir::ItemUse(path, hir::UseKind::ListStem)
2598 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2599 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2600 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2602 let (generics, node) = match i.node {
2603 TraitItemKind::Const(ref ty, ref default) => (
2604 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2605 hir::TraitItemKind::Const(
2606 self.lower_ty(ty, ImplTraitContext::Disallowed),
2609 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2612 TraitItemKind::Method(ref sig, None) => {
2613 let names = self.lower_fn_args_to_names(&sig.decl);
2614 self.add_in_band_defs(
2617 AnonymousLifetimeMode::PassThrough,
2619 hir::TraitItemKind::Method(
2620 this.lower_method_sig(sig, trait_item_def_id, false),
2621 hir::TraitMethod::Required(names),
2626 TraitItemKind::Method(ref sig, Some(ref body)) => {
2627 let body_id = self.lower_body(Some(&sig.decl), |this| {
2628 let body = this.lower_block(body, false);
2629 this.expr_block(body, ThinVec::new())
2632 self.add_in_band_defs(
2635 AnonymousLifetimeMode::PassThrough,
2637 hir::TraitItemKind::Method(
2638 this.lower_method_sig(sig, trait_item_def_id, false),
2639 hir::TraitMethod::Provided(body_id),
2644 TraitItemKind::Type(ref bounds, ref default) => (
2645 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2646 hir::TraitItemKind::Type(
2647 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2650 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2653 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2659 name: self.lower_ident(i.ident),
2660 attrs: self.lower_attrs(&i.attrs),
2667 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2668 let (kind, has_default) = match i.node {
2669 TraitItemKind::Const(_, ref default) => {
2670 (hir::AssociatedItemKind::Const, default.is_some())
2672 TraitItemKind::Type(_, ref default) => {
2673 (hir::AssociatedItemKind::Type, default.is_some())
2675 TraitItemKind::Method(ref sig, ref default) => (
2676 hir::AssociatedItemKind::Method {
2677 has_self: sig.decl.has_self(),
2681 TraitItemKind::Macro(..) => unimplemented!(),
2684 id: hir::TraitItemId { node_id: i.id },
2685 name: self.lower_ident(i.ident),
2687 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
2692 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
2693 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2694 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
2696 let (generics, node) = match i.node {
2697 ImplItemKind::Const(ref ty, ref expr) => {
2698 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
2700 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2701 hir::ImplItemKind::Const(
2702 self.lower_ty(ty, ImplTraitContext::Disallowed),
2707 ImplItemKind::Method(ref sig, ref body) => {
2708 let body_id = self.lower_body(Some(&sig.decl), |this| {
2709 let body = this.lower_block(body, false);
2710 this.expr_block(body, ThinVec::new())
2712 let impl_trait_return_allow = !self.is_in_trait_impl;
2714 self.add_in_band_defs(
2717 AnonymousLifetimeMode::PassThrough,
2719 hir::ImplItemKind::Method(
2720 this.lower_method_sig(
2723 impl_trait_return_allow,
2730 ImplItemKind::Type(ref ty) => (
2731 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2732 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
2734 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2740 name: self.lower_ident(i.ident),
2741 attrs: self.lower_attrs(&i.attrs),
2743 vis: self.lower_visibility(&i.vis, None),
2744 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2749 // [1] since `default impl` is not yet implemented, this is always true in impls
2752 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
2754 id: hir::ImplItemId { node_id: i.id },
2755 name: self.lower_ident(i.ident),
2757 vis: self.lower_visibility(&i.vis, Some(i.id)),
2758 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2759 kind: match i.node {
2760 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
2761 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
2762 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
2763 has_self: sig.decl.has_self(),
2765 ImplItemKind::Macro(..) => unimplemented!(),
2769 // [1] since `default impl` is not yet implemented, this is always true in impls
2772 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
2775 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
2779 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
2781 ItemKind::Use(ref use_tree) => {
2782 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
2783 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
2786 ItemKind::MacroDef(..) => return SmallVector::new(),
2789 SmallVector::one(hir::ItemId { id: i.id })
2792 fn lower_item_id_use_tree(&mut self,
2795 vec: &mut SmallVector<hir::ItemId>)
2798 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
2799 vec.push(hir::ItemId { id });
2800 self.lower_item_id_use_tree(nested, id, vec);
2802 UseTreeKind::Glob => {}
2803 UseTreeKind::Simple(_, id1, id2) => {
2804 for (_, &id) in self.expect_full_def_from_use(base_id)
2806 .zip([id1, id2].iter())
2808 vec.push(hir::ItemId { id });
2814 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
2815 let mut name = i.ident.name;
2816 let mut vis = self.lower_visibility(&i.vis, None);
2817 let attrs = self.lower_attrs(&i.attrs);
2818 if let ItemKind::MacroDef(ref def) = i.node {
2819 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
2820 let body = self.lower_token_stream(def.stream());
2821 self.exported_macros.push(hir::MacroDef {
2834 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
2836 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2849 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
2850 let node_id = self.lower_node_id(i.id).node_id;
2851 let def_id = self.resolver.definitions().local_def_id(node_id);
2855 attrs: self.lower_attrs(&i.attrs),
2856 node: match i.node {
2857 ForeignItemKind::Fn(ref fdec, ref generics) => {
2858 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
2861 AnonymousLifetimeMode::PassThrough,
2864 // Disallow impl Trait in foreign items
2865 this.lower_fn_decl(fdec, None, false),
2866 this.lower_fn_args_to_names(fdec),
2871 hir::ForeignItemFn(fn_dec, fn_args, generics)
2873 ForeignItemKind::Static(ref t, m) => {
2874 hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
2876 ForeignItemKind::Ty => hir::ForeignItemType,
2877 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
2879 vis: self.lower_visibility(&i.vis, None),
2884 fn lower_method_sig(
2888 impl_trait_return_allow: bool,
2889 ) -> hir::MethodSig {
2892 unsafety: self.lower_unsafety(sig.unsafety),
2893 constness: self.lower_constness(sig.constness),
2894 decl: self.lower_fn_decl(&sig.decl, Some(fn_def_id), impl_trait_return_allow),
2898 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
2900 IsAuto::Yes => hir::IsAuto::Yes,
2901 IsAuto::No => hir::IsAuto::No,
2905 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
2907 Unsafety::Unsafe => hir::Unsafety::Unsafe,
2908 Unsafety::Normal => hir::Unsafety::Normal,
2912 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
2914 Constness::Const => hir::Constness::Const,
2915 Constness::NotConst => hir::Constness::NotConst,
2919 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
2921 UnOp::Deref => hir::UnDeref,
2922 UnOp::Not => hir::UnNot,
2923 UnOp::Neg => hir::UnNeg,
2927 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
2929 node: match b.node {
2930 BinOpKind::Add => hir::BiAdd,
2931 BinOpKind::Sub => hir::BiSub,
2932 BinOpKind::Mul => hir::BiMul,
2933 BinOpKind::Div => hir::BiDiv,
2934 BinOpKind::Rem => hir::BiRem,
2935 BinOpKind::And => hir::BiAnd,
2936 BinOpKind::Or => hir::BiOr,
2937 BinOpKind::BitXor => hir::BiBitXor,
2938 BinOpKind::BitAnd => hir::BiBitAnd,
2939 BinOpKind::BitOr => hir::BiBitOr,
2940 BinOpKind::Shl => hir::BiShl,
2941 BinOpKind::Shr => hir::BiShr,
2942 BinOpKind::Eq => hir::BiEq,
2943 BinOpKind::Lt => hir::BiLt,
2944 BinOpKind::Le => hir::BiLe,
2945 BinOpKind::Ne => hir::BiNe,
2946 BinOpKind::Ge => hir::BiGe,
2947 BinOpKind::Gt => hir::BiGt,
2953 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2954 let node = match p.node {
2955 PatKind::Wild => hir::PatKind::Wild,
2956 PatKind::Ident(ref binding_mode, ident, ref sub) => {
2957 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
2958 // `None` can occur in body-less function signatures
2959 def @ None | def @ Some(Def::Local(_)) => {
2960 let canonical_id = match def {
2961 Some(Def::Local(id)) => id,
2964 hir::PatKind::Binding(
2965 self.lower_binding_mode(binding_mode),
2967 respan(ident.span, ident.name),
2968 sub.as_ref().map(|x| self.lower_pat(x)),
2971 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
2976 segments: hir_vec![hir::PathSegment::from_name(ident.name)],
2981 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
2982 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
2983 let qpath = self.lower_qpath(
2987 ParamMode::Optional,
2988 ImplTraitContext::Disallowed,
2990 hir::PatKind::TupleStruct(
2992 pats.iter().map(|x| self.lower_pat(x)).collect(),
2996 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3000 ParamMode::Optional,
3001 ImplTraitContext::Disallowed,
3003 PatKind::Struct(ref path, ref fields, etc) => {
3004 let qpath = self.lower_qpath(
3008 ParamMode::Optional,
3009 ImplTraitContext::Disallowed,
3016 node: hir::FieldPat {
3017 id: self.next_id().node_id,
3018 ident: f.node.ident,
3019 pat: self.lower_pat(&f.node.pat),
3020 is_shorthand: f.node.is_shorthand,
3024 hir::PatKind::Struct(qpath, fs, etc)
3026 PatKind::Tuple(ref elts, ddpos) => {
3027 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3029 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3030 PatKind::Ref(ref inner, mutbl) => {
3031 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3033 PatKind::Range(ref e1, ref e2, ref end) => hir::PatKind::Range(
3034 P(self.lower_expr(e1)),
3035 P(self.lower_expr(e2)),
3036 self.lower_range_end(end),
3038 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3039 before.iter().map(|x| self.lower_pat(x)).collect(),
3040 slice.as_ref().map(|x| self.lower_pat(x)),
3041 after.iter().map(|x| self.lower_pat(x)).collect(),
3043 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3044 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3047 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3056 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3058 RangeEnd::Included(_) => hir::RangeEnd::Included,
3059 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3063 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3064 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3069 body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3073 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3074 let kind = match e.node {
3075 ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
3076 ExprKind::ObsoleteInPlace(..) => {
3077 self.sess.abort_if_errors();
3078 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3080 ExprKind::Array(ref exprs) => {
3081 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
3083 ExprKind::Repeat(ref expr, ref count) => {
3084 let expr = P(self.lower_expr(expr));
3085 let count = self.lower_anon_const(count);
3086 hir::ExprRepeat(expr, count)
3088 ExprKind::Tup(ref elts) => {
3089 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
3091 ExprKind::Call(ref f, ref args) => {
3092 let f = P(self.lower_expr(f));
3093 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
3095 ExprKind::MethodCall(ref seg, ref args) => {
3096 let hir_seg = self.lower_path_segment(
3099 ParamMode::Optional,
3101 ParenthesizedGenericArgs::Err,
3102 ImplTraitContext::Disallowed,
3104 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3105 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
3107 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3108 let binop = self.lower_binop(binop);
3109 let lhs = P(self.lower_expr(lhs));
3110 let rhs = P(self.lower_expr(rhs));
3111 hir::ExprBinary(binop, lhs, rhs)
3113 ExprKind::Unary(op, ref ohs) => {
3114 let op = self.lower_unop(op);
3115 let ohs = P(self.lower_expr(ohs));
3116 hir::ExprUnary(op, ohs)
3118 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
3119 ExprKind::Cast(ref expr, ref ty) => {
3120 let expr = P(self.lower_expr(expr));
3121 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3123 ExprKind::Type(ref expr, ref ty) => {
3124 let expr = P(self.lower_expr(expr));
3125 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3127 ExprKind::AddrOf(m, ref ohs) => {
3128 let m = self.lower_mutability(m);
3129 let ohs = P(self.lower_expr(ohs));
3130 hir::ExprAddrOf(m, ohs)
3132 // More complicated than you might expect because the else branch
3133 // might be `if let`.
3134 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3135 let else_opt = else_opt.as_ref().map(|els| {
3137 ExprKind::IfLet(..) => {
3138 // wrap the if-let expr in a block
3139 let span = els.span;
3140 let els = P(self.lower_expr(els));
3141 let LoweredNodeId { node_id, hir_id } = self.next_id();
3142 let blk = P(hir::Block {
3147 rules: hir::DefaultBlock,
3149 targeted_by_break: false,
3150 recovered: blk.recovered,
3152 P(self.expr_block(blk, ThinVec::new()))
3154 _ => P(self.lower_expr(els)),
3158 let then_blk = self.lower_block(blk, false);
3159 let then_expr = self.expr_block(then_blk, ThinVec::new());
3161 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3163 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3165 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3166 this.lower_block(body, false),
3167 this.lower_label(opt_label),
3170 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3172 this.lower_block(body, false),
3173 this.lower_label(opt_label),
3174 hir::LoopSource::Loop,
3177 ExprKind::Catch(ref body) => {
3178 self.with_catch_scope(body.id, |this| {
3180 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3181 let mut block = this.lower_block(body, true).into_inner();
3182 let tail = block.expr.take().map_or_else(
3184 let LoweredNodeId { node_id, hir_id } = this.next_id();
3185 let span = this.sess.codemap().end_point(unstable_span);
3189 node: hir::ExprTup(hir_vec![]),
3190 attrs: ThinVec::new(),
3194 |x: P<hir::Expr>| x.into_inner(),
3196 block.expr = Some(this.wrap_in_try_constructor(
3197 "from_ok", tail, unstable_span));
3198 hir::ExprBlock(P(block), None)
3201 ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3202 P(self.lower_expr(expr)),
3203 arms.iter().map(|x| self.lower_arm(x)).collect(),
3204 hir::MatchSource::Normal,
3206 ExprKind::Closure(capture_clause, movability, ref decl, ref body, fn_decl_span) => {
3207 self.with_new_scopes(|this| {
3208 let mut is_generator = false;
3209 let body_id = this.lower_body(Some(decl), |this| {
3210 let e = this.lower_expr(body);
3211 is_generator = this.is_generator;
3214 let generator_option = if is_generator {
3215 if !decl.inputs.is_empty() {
3220 "generators cannot have explicit arguments"
3222 this.sess.abort_if_errors();
3224 Some(match movability {
3225 Movability::Movable => hir::GeneratorMovability::Movable,
3226 Movability::Static => hir::GeneratorMovability::Static,
3229 if movability == Movability::Static {
3234 "closures cannot be static"
3240 this.lower_capture_clause(capture_clause),
3241 this.lower_fn_decl(decl, None, false),
3248 ExprKind::Block(ref blk, opt_label) => {
3249 hir::ExprBlock(self.lower_block(blk,
3250 opt_label.is_some()),
3251 self.lower_label(opt_label))
3253 ExprKind::Assign(ref el, ref er) => {
3254 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3256 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3257 self.lower_binop(op),
3258 P(self.lower_expr(el)),
3259 P(self.lower_expr(er)),
3261 ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3262 ExprKind::Index(ref el, ref er) => {
3263 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3265 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3266 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3267 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3268 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3269 let id = self.next_id();
3270 let e1 = self.lower_expr(e1);
3271 let e2 = self.lower_expr(e2);
3272 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], false));
3273 let ty = self.ty_path(id, span, hir::QPath::Resolved(None, ty_path));
3274 let new_seg = P(hir::PathSegment::from_name(Symbol::intern("new")));
3275 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3276 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3277 hir::ExprCall(new, hir_vec![e1, e2])
3279 ExprKind::Range(ref e1, ref e2, lims) => {
3280 use syntax::ast::RangeLimits::*;
3282 let path = match (e1, e2, lims) {
3283 (&None, &None, HalfOpen) => "RangeFull",
3284 (&Some(..), &None, HalfOpen) => "RangeFrom",
3285 (&None, &Some(..), HalfOpen) => "RangeTo",
3286 (&Some(..), &Some(..), HalfOpen) => "Range",
3287 (&None, &Some(..), Closed) => "RangeToInclusive",
3288 (&Some(..), &Some(..), Closed) => unreachable!(),
3289 (_, &None, Closed) => self.diagnostic()
3290 .span_fatal(e.span, "inclusive range with no end")
3294 let fields = e1.iter()
3295 .map(|e| ("start", e))
3296 .chain(e2.iter().map(|e| ("end", e)))
3298 let expr = P(self.lower_expr(&e));
3300 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3301 let ident = Ident::new(Symbol::intern(s), unstable_span);
3302 self.field(ident, expr, unstable_span)
3304 .collect::<P<[hir::Field]>>();
3306 let is_unit = fields.is_empty();
3308 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3309 let struct_path = iter::once("ops")
3310 .chain(iter::once(path))
3311 .collect::<Vec<_>>();
3312 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
3313 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3315 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3321 hir::ExprPath(struct_path)
3323 hir::ExprStruct(struct_path, fields, None)
3325 span: unstable_span,
3326 attrs: e.attrs.clone(),
3329 ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3333 ParamMode::Optional,
3334 ImplTraitContext::Disallowed,
3336 ExprKind::Break(opt_label, ref opt_expr) => {
3337 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3340 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3343 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3347 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3350 ExprKind::Continue(opt_label) => {
3351 hir::ExprAgain(if self.is_in_loop_condition && opt_label.is_none() {
3354 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3357 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3360 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3361 ExprKind::InlineAsm(ref asm) => {
3362 let hir_asm = hir::InlineAsm {
3363 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3364 outputs: asm.outputs
3366 .map(|out| hir::InlineAsmOutput {
3367 constraint: out.constraint.clone(),
3369 is_indirect: out.is_indirect,
3372 asm: asm.asm.clone(),
3373 asm_str_style: asm.asm_str_style,
3374 clobbers: asm.clobbers.clone().into(),
3375 volatile: asm.volatile,
3376 alignstack: asm.alignstack,
3377 dialect: asm.dialect,
3380 let outputs = asm.outputs
3382 .map(|out| self.lower_expr(&out.expr))
3384 let inputs = asm.inputs
3386 .map(|&(_, ref input)| self.lower_expr(input))
3388 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3390 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3395 ParamMode::Optional,
3396 ImplTraitContext::Disallowed,
3398 fields.iter().map(|x| self.lower_field(x)).collect(),
3399 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3401 ExprKind::Paren(ref ex) => {
3402 let mut ex = self.lower_expr(ex);
3403 // include parens in span, but only if it is a super-span.
3404 if e.span.contains(ex.span) {
3407 // merge attributes into the inner expression.
3408 let mut attrs = e.attrs.clone();
3409 attrs.extend::<Vec<_>>(ex.attrs.into());
3414 ExprKind::Yield(ref opt_expr) => {
3415 self.is_generator = true;
3418 .map(|x| self.lower_expr(x))
3419 .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3420 hir::ExprYield(P(expr))
3423 // Desugar ExprIfLet
3424 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3425 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3428 // match <sub_expr> {
3430 // _ => [<else_opt> | ()]
3433 let mut arms = vec![];
3435 // `<pat> => <body>`
3437 let body = self.lower_block(body, false);
3438 let body_expr = P(self.expr_block(body, ThinVec::new()));
3439 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3440 arms.push(self.arm(pats, body_expr));
3443 // _ => [<else_opt>|()]
3445 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3446 let wildcard_pattern = self.pat_wild(e.span);
3447 let body = if let Some(else_expr) = wildcard_arm {
3448 P(self.lower_expr(else_expr))
3450 self.expr_tuple(e.span, hir_vec![])
3452 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3455 let contains_else_clause = else_opt.is_some();
3457 let sub_expr = P(self.lower_expr(sub_expr));
3462 hir::MatchSource::IfLetDesugar {
3463 contains_else_clause,
3468 // Desugar ExprWhileLet
3469 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3470 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3473 // [opt_ident]: loop {
3474 // match <sub_expr> {
3480 // Note that the block AND the condition are evaluated in the loop scope.
3481 // This is done to allow `break` from inside the condition of the loop.
3482 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3484 this.lower_block(body, false),
3485 this.expr_break(e.span, ThinVec::new()),
3486 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3490 // `<pat> => <body>`
3492 let body_expr = P(self.expr_block(body, ThinVec::new()));
3493 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3494 self.arm(pats, body_expr)
3499 let pat_under = self.pat_wild(e.span);
3500 self.arm(hir_vec![pat_under], break_expr)
3503 // `match <sub_expr> { ... }`
3504 let arms = hir_vec![pat_arm, break_arm];
3505 let match_expr = self.expr(
3507 hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3511 // `[opt_ident]: loop { ... }`
3512 let loop_block = P(self.block_expr(P(match_expr)));
3513 let loop_expr = hir::ExprLoop(
3515 self.lower_label(opt_label),
3516 hir::LoopSource::WhileLet,
3518 // add attributes to the outer returned expr node
3522 // Desugar ExprForLoop
3523 // From: `[opt_ident]: for <pat> in <head> <body>`
3524 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3528 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3530 // [opt_ident]: loop {
3532 // match ::std::iter::Iterator::next(&mut iter) {
3533 // ::std::option::Option::Some(val) => __next = val,
3534 // ::std::option::Option::None => break
3536 // let <pat> = __next;
3537 // StmtExpr(<body>);
3545 let head = self.lower_expr(head);
3546 let head_sp = head.span;
3548 let iter = self.str_to_ident("iter");
3550 let next_ident = self.str_to_ident("__next");
3551 let next_pat = self.pat_ident_binding_mode(
3554 hir::BindingAnnotation::Mutable,
3557 // `::std::option::Option::Some(val) => next = val`
3559 let val_ident = self.str_to_ident("val");
3560 let val_pat = self.pat_ident(pat.span, val_ident);
3561 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
3562 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
3563 let assign = P(self.expr(
3565 hir::ExprAssign(next_expr, val_expr),
3568 let some_pat = self.pat_some(pat.span, val_pat);
3569 self.arm(hir_vec![some_pat], assign)
3572 // `::std::option::Option::None => break`
3575 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
3576 let pat = self.pat_none(e.span);
3577 self.arm(hir_vec![pat], break_expr)
3582 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
3584 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
3586 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
3587 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
3588 let next_path = &["iter", "Iterator", "next"];
3589 let next_path = P(self.expr_std_path(head_sp, next_path, ThinVec::new()));
3590 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
3591 let arms = hir_vec![pat_arm, break_arm];
3595 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
3599 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
3601 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
3605 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
3607 // `let <pat> = __next`
3608 let pat = self.lower_pat(pat);
3609 let pat_let = self.stmt_let_pat(
3613 hir::LocalSource::ForLoopDesugar,
3616 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
3617 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
3618 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
3620 let loop_block = P(self.block_all(
3622 hir_vec![next_let, match_stmt, pat_let, body_stmt],
3626 // `[opt_ident]: loop { ... }`
3627 let loop_expr = hir::ExprLoop(
3629 self.lower_label(opt_label),
3630 hir::LoopSource::ForLoop,
3632 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3633 let loop_expr = P(hir::Expr {
3638 attrs: ThinVec::new(),
3641 // `mut iter => { ... }`
3642 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
3644 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
3645 let into_iter_expr = {
3646 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
3647 let into_iter = P(self.expr_std_path(head_sp, into_iter_path, ThinVec::new()));
3648 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
3651 let match_expr = P(self.expr_match(
3655 hir::MatchSource::ForLoopDesugar,
3658 // `{ let _result = ...; _result }`
3659 // underscore prevents an unused_variables lint if the head diverges
3660 let result_ident = self.str_to_ident("_result");
3661 let (let_stmt, let_stmt_binding) =
3662 self.stmt_let(e.span, false, result_ident, match_expr);
3664 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
3665 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
3666 // add the attributes to the outer returned expr node
3667 return self.expr_block(block, e.attrs.clone());
3670 // Desugar ExprKind::Try
3672 ExprKind::Try(ref sub_expr) => {
3675 // match Try::into_result(<expr>) {
3676 // Ok(val) => #[allow(unreachable_code)] val,
3677 // Err(err) => #[allow(unreachable_code)]
3678 // // If there is an enclosing `catch {...}`
3679 // break 'catch_target Try::from_error(From::from(err)),
3681 // return Try::from_error(From::from(err)),
3685 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
3687 // Try::into_result(<expr>)
3690 let sub_expr = self.lower_expr(sub_expr);
3692 let path = &["ops", "Try", "into_result"];
3693 let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
3694 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
3697 // #[allow(unreachable_code)]
3699 // allow(unreachable_code)
3701 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
3702 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
3703 let uc_nested = attr::mk_nested_word_item(uc_ident);
3704 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
3706 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
3708 let attrs = vec![attr];
3710 // Ok(val) => #[allow(unreachable_code)] val,
3712 let val_ident = self.str_to_ident("val");
3713 let val_pat = self.pat_ident(e.span, val_ident);
3714 let val_expr = P(self.expr_ident_with_attrs(
3718 ThinVec::from(attrs.clone()),
3720 let ok_pat = self.pat_ok(e.span, val_pat);
3722 self.arm(hir_vec![ok_pat], val_expr)
3725 // Err(err) => #[allow(unreachable_code)]
3726 // return Try::from_error(From::from(err)),
3728 let err_ident = self.str_to_ident("err");
3729 let err_local = self.pat_ident(e.span, err_ident);
3731 let path = &["convert", "From", "from"];
3732 let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
3733 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
3735 self.expr_call(e.span, from, hir_vec![err_expr])
3738 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
3739 let thin_attrs = ThinVec::from(attrs);
3740 let catch_scope = self.catch_scopes.last().map(|x| *x);
3741 let ret_expr = if let Some(catch_node) = catch_scope {
3747 target_id: Ok(catch_node),
3749 Some(from_err_expr),
3754 P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
3757 let err_pat = self.pat_err(e.span, err_local);
3758 self.arm(hir_vec![err_pat], ret_expr)
3763 hir_vec![err_arm, ok_arm],
3764 hir::MatchSource::TryDesugar,
3768 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
3771 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3778 attrs: e.attrs.clone(),
3782 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
3783 SmallVector::one(match s.node {
3784 StmtKind::Local(ref l) => Spanned {
3785 node: hir::StmtDecl(
3787 node: hir::DeclLocal(self.lower_local(l)),
3790 self.lower_node_id(s.id).node_id,
3794 StmtKind::Item(ref it) => {
3795 // Can only use the ID once.
3796 let mut id = Some(s.id);
3797 return self.lower_item_id(it)
3799 .map(|item_id| Spanned {
3800 node: hir::StmtDecl(
3802 node: hir::DeclItem(item_id),
3806 .map(|id| self.lower_node_id(id).node_id)
3807 .unwrap_or_else(|| self.next_id().node_id),
3813 StmtKind::Expr(ref e) => Spanned {
3814 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3817 StmtKind::Semi(ref e) => Spanned {
3818 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3821 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
3825 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
3827 CaptureBy::Value => hir::CaptureByValue,
3828 CaptureBy::Ref => hir::CaptureByRef,
3832 /// If an `explicit_owner` is given, this method allocates the `HirId` in
3833 /// the address space of that item instead of the item currently being
3834 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
3835 /// lower a `Visibility` value although we haven't lowered the owning
3836 /// `ImplItem` in question yet.
3837 fn lower_visibility(
3840 explicit_owner: Option<NodeId>,
3841 ) -> hir::Visibility {
3843 VisibilityKind::Public => hir::Public,
3844 VisibilityKind::Crate(sugar) => hir::Visibility::Crate(sugar),
3845 VisibilityKind::Restricted { ref path, id, .. } => hir::Visibility::Restricted {
3846 path: P(self.lower_path(id, path, ParamMode::Explicit)),
3847 id: if let Some(owner) = explicit_owner {
3848 self.lower_node_id_with_owner(id, owner).node_id
3850 self.lower_node_id(id).node_id
3853 VisibilityKind::Inherited => hir::Inherited,
3857 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
3859 Defaultness::Default => hir::Defaultness::Default {
3860 has_value: has_value,
3862 Defaultness::Final => {
3864 hir::Defaultness::Final
3869 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3871 BlockCheckMode::Default => hir::DefaultBlock,
3872 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3876 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3878 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
3879 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
3880 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
3881 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
3885 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3887 CompilerGenerated => hir::CompilerGenerated,
3888 UserProvided => hir::UserProvided,
3892 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
3894 ImplPolarity::Positive => hir::ImplPolarity::Positive,
3895 ImplPolarity::Negative => hir::ImplPolarity::Negative,
3899 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3901 TraitBoundModifier::None => hir::TraitBoundModifier::None,
3902 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3906 // Helper methods for building HIR.
3908 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
3917 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
3919 id: self.next_id().node_id,
3923 is_shorthand: false,
3927 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
3928 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
3929 P(self.expr(span, expr_break, attrs))
3936 args: hir::HirVec<hir::Expr>,
3938 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
3941 fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
3942 self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
3945 fn expr_ident_with_attrs(
3950 attrs: ThinVec<Attribute>,
3952 let expr_path = hir::ExprPath(hir::QPath::Resolved(
3956 def: Def::Local(binding),
3957 segments: hir_vec![hir::PathSegment::from_name(id)],
3961 self.expr(span, expr_path, attrs)
3964 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
3965 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
3971 components: &[&str],
3972 attrs: ThinVec<Attribute>,
3974 let path = self.std_path(span, components, true);
3977 hir::ExprPath(hir::QPath::Resolved(None, P(path))),
3986 arms: hir::HirVec<hir::Arm>,
3987 source: hir::MatchSource,
3989 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
3992 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
3993 self.expr(b.span, hir::ExprBlock(b, None), attrs)
3996 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
3997 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
4000 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
4001 let LoweredNodeId { node_id, hir_id } = self.next_id();
4014 ex: Option<P<hir::Expr>>,
4016 source: hir::LocalSource,
4018 let LoweredNodeId { node_id, hir_id } = self.next_id();
4020 let local = P(hir::Local {
4027 attrs: ThinVec::new(),
4030 let decl = respan(sp, hir::DeclLocal(local));
4031 respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
4040 ) -> (hir::Stmt, NodeId) {
4041 let pat = if mutbl {
4042 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4044 self.pat_ident(sp, ident)
4046 let pat_id = pat.id;
4048 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4053 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4054 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4060 stmts: hir::HirVec<hir::Stmt>,
4061 expr: Option<P<hir::Expr>>,
4063 let LoweredNodeId { node_id, hir_id } = self.next_id();
4070 rules: hir::DefaultBlock,
4072 targeted_by_break: false,
4077 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4078 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4081 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4082 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4085 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4086 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4089 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4090 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4096 components: &[&str],
4097 subpats: hir::HirVec<P<hir::Pat>>,
4099 let path = self.std_path(span, components, true);
4100 let qpath = hir::QPath::Resolved(None, P(path));
4101 let pt = if subpats.is_empty() {
4102 hir::PatKind::Path(qpath)
4104 hir::PatKind::TupleStruct(qpath, subpats, None)
4109 fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
4110 self.pat_ident_binding_mode(span, name, hir::BindingAnnotation::Unannotated)
4113 fn pat_ident_binding_mode(
4117 bm: hir::BindingAnnotation,
4119 let LoweredNodeId { node_id, hir_id } = self.next_id();
4124 node: hir::PatKind::Binding(bm, node_id, Spanned { span, node: name }, None),
4129 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4130 self.pat(span, hir::PatKind::Wild)
4133 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4134 let LoweredNodeId { node_id, hir_id } = self.next_id();
4143 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4144 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4145 /// The path is also resolved according to `is_value`.
4146 fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
4148 .resolve_str_path(span, self.crate_root, components, is_value)
4151 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
4153 let node = match qpath {
4154 hir::QPath::Resolved(None, path) => {
4155 // Turn trait object paths into `TyTraitObject` instead.
4156 if let Def::Trait(_) = path.def {
4157 let principal = hir::PolyTraitRef {
4158 bound_generic_params: hir::HirVec::new(),
4159 trait_ref: hir::TraitRef {
4160 path: path.and_then(|path| path),
4166 // The original ID is taken by the `PolyTraitRef`,
4167 // so the `Ty` itself needs a different one.
4168 id = self.next_id();
4169 hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4171 hir::TyPath(hir::QPath::Resolved(None, path))
4174 _ => hir::TyPath(qpath),
4184 /// Invoked to create the lifetime argument for a type `&T`
4185 /// with no explicit lifetime.
4186 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4187 match self.anonymous_lifetime_mode {
4188 // Intercept when we are in an impl header and introduce an in-band lifetime.
4189 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4191 AnonymousLifetimeMode::CreateParameter => {
4192 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4194 id: self.next_id().node_id,
4200 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4204 /// Invoked to create the lifetime argument(s) for a path like
4205 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4206 /// sorts of cases are deprecated. This may therefore report a warning or an
4207 /// error, depending on the mode.
4208 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4209 match self.anonymous_lifetime_mode {
4210 // NB. We intentionally ignore the create-parameter mode here
4211 // and instead "pass through" to resolve-lifetimes, which will then
4212 // report an error. This is because we don't want to support
4213 // impl elision for deprecated forms like
4215 // impl Foo for std::cell::Ref<u32> // note lack of '_
4216 AnonymousLifetimeMode::CreateParameter => {}
4218 // This is the normal case.
4219 AnonymousLifetimeMode::PassThrough => {}
4223 .map(|_| self.new_implicit_lifetime(span))
4227 /// Invoked to create the lifetime argument(s) for an elided trait object
4228 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4229 /// when the bound is written, even if it is written with `'_` like in
4230 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4231 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4232 match self.anonymous_lifetime_mode {
4233 // NB. We intentionally ignore the create-parameter mode here.
4234 // and instead "pass through" to resolve-lifetimes, which will apply
4235 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4236 // do not act like other elided lifetimes. In other words, given this:
4238 // impl Foo for Box<dyn Debug>
4240 // we do not introduce a fresh `'_` to serve as the bound, but instead
4241 // ultimately translate to the equivalent of:
4243 // impl Foo for Box<dyn Debug + 'static>
4245 // `resolve_lifetime` has the code to make that happen.
4246 AnonymousLifetimeMode::CreateParameter => {}
4248 // This is the normal case.
4249 AnonymousLifetimeMode::PassThrough => {}
4252 self.new_implicit_lifetime(span)
4255 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4257 id: self.next_id().node_id,
4259 name: hir::LifetimeName::Implicit,
4263 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4264 self.sess.buffer_lint_with_diagnostic(
4265 builtin::BARE_TRAIT_OBJECTS,
4268 "trait objects without an explicit `dyn` are deprecated",
4269 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4273 fn wrap_in_try_constructor(
4275 method: &'static str,
4277 unstable_span: Span,
4279 let path = &["ops", "Try", method];
4280 let from_err = P(self.expr_std_path(unstable_span, path,
4282 P(self.expr_call(e.span, from_err, hir_vec![e]))
4286 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4287 // Sorting by span ensures that we get things in order within a
4288 // file, and also puts the files in a sensible order.
4289 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4290 body_ids.sort_by_key(|b| bodies[b].value.span);