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 {
709 lifetime: hir::Lifetime {
717 .chain(in_band_ty_params.into_iter())
723 /// When there is a reference to some lifetime `'a`, and in-band
724 /// lifetimes are enabled, then we want to push that lifetime into
725 /// the vector of names to define later. In that case, it will get
726 /// added to the appropriate generics.
727 fn maybe_collect_in_band_lifetime(&mut self, span: Span, name: Name) {
728 if !self.is_collecting_in_band_lifetimes {
732 if self.in_scope_lifetimes.contains(&name) {
736 let hir_name = hir::LifetimeName::Name(name);
738 if self.lifetimes_to_define.iter().any(|(_, lt_name)| *lt_name == hir_name) {
742 self.lifetimes_to_define.push((span, hir_name));
745 /// When we have either an elided or `'_` lifetime in an impl
746 /// header, we convert it to
747 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> hir::LifetimeName {
748 assert!(self.is_collecting_in_band_lifetimes);
749 let index = self.lifetimes_to_define.len();
750 let hir_name = hir::LifetimeName::Fresh(index);
751 self.lifetimes_to_define.push((span, hir_name));
755 // Evaluates `f` with the lifetimes in `params` in-scope.
756 // This is used to track which lifetimes have already been defined, and
757 // which are new in-band lifetimes that need to have a definition created
759 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &Vec<GenericParam>, f: F) -> T
761 F: FnOnce(&mut LoweringContext) -> T,
763 let old_len = self.in_scope_lifetimes.len();
764 let lt_def_names = params.iter().filter_map(|param| match param.kind {
765 GenericParamKind::Lifetime { .. } => Some(param.ident.name),
768 self.in_scope_lifetimes.extend(lt_def_names);
772 self.in_scope_lifetimes.truncate(old_len);
776 // Same as the method above, but accepts `hir::GenericParam`s
777 // instead of `ast::GenericParam`s.
778 // This should only be used with generics that have already had their
779 // in-band lifetimes added. In practice, this means that this function is
780 // only used when lowering a child item of a trait or impl.
781 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
782 params: &HirVec<hir::GenericParam>,
785 F: FnOnce(&mut LoweringContext) -> T,
787 let old_len = self.in_scope_lifetimes.len();
788 let lt_def_names = params.iter().filter_map(|param| match param.kind {
789 hir::GenericParamKind::Lifetime { .. } => Some(param.name),
792 self.in_scope_lifetimes.extend(lt_def_names);
796 self.in_scope_lifetimes.truncate(old_len);
800 /// Appends in-band lifetime defs and argument-position `impl
801 /// Trait` defs to the existing set of generics.
803 /// Presuming that in-band lifetimes are enabled, then
804 /// `self.anonymous_lifetime_mode` will be updated to match the
805 /// argument while `f` is running (and restored afterwards).
806 fn add_in_band_defs<F, T>(
810 anonymous_lifetime_mode: AnonymousLifetimeMode,
812 ) -> (hir::Generics, T)
814 F: FnOnce(&mut LoweringContext) -> T,
816 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
819 let itctx = ImplTraitContext::Universal(parent_id);
820 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
821 (this.lower_generics(generics, itctx), f(this))
826 lowered_generics.params = lowered_generics
833 (lowered_generics, res)
836 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
838 F: FnOnce(&mut LoweringContext) -> T,
840 let len = self.catch_scopes.len();
841 self.catch_scopes.push(catch_id);
843 let result = f(self);
846 self.catch_scopes.len(),
847 "catch scopes should be added and removed in stack order"
850 self.catch_scopes.pop().unwrap();
855 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
857 F: FnOnce(&mut LoweringContext) -> hir::Expr,
859 let prev = mem::replace(&mut self.is_generator, false);
860 let result = f(self);
861 let r = self.record_body(result, decl);
862 self.is_generator = prev;
866 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
868 F: FnOnce(&mut LoweringContext) -> T,
870 // We're no longer in the base loop's condition; we're in another loop.
871 let was_in_loop_condition = self.is_in_loop_condition;
872 self.is_in_loop_condition = false;
874 let len = self.loop_scopes.len();
875 self.loop_scopes.push(loop_id);
877 let result = f(self);
880 self.loop_scopes.len(),
881 "Loop scopes should be added and removed in stack order"
884 self.loop_scopes.pop().unwrap();
886 self.is_in_loop_condition = was_in_loop_condition;
891 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
893 F: FnOnce(&mut LoweringContext) -> T,
895 let was_in_loop_condition = self.is_in_loop_condition;
896 self.is_in_loop_condition = true;
898 let result = f(self);
900 self.is_in_loop_condition = was_in_loop_condition;
905 fn with_new_scopes<T, F>(&mut self, f: F) -> T
907 F: FnOnce(&mut LoweringContext) -> T,
909 let was_in_loop_condition = self.is_in_loop_condition;
910 self.is_in_loop_condition = false;
912 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
913 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
914 let result = f(self);
915 self.catch_scopes = catch_scopes;
916 self.loop_scopes = loop_scopes;
918 self.is_in_loop_condition = was_in_loop_condition;
923 fn def_key(&mut self, id: DefId) -> DefKey {
925 self.resolver.definitions().def_key(id.index)
927 self.cstore.def_key(id)
931 fn lower_ident(&mut self, ident: Ident) -> Name {
932 let ident = ident.modern();
933 if ident.span.ctxt() == SyntaxContext::empty() {
938 .or_insert_with(|| Symbol::from_ident(ident))
941 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
942 label.map(|label| hir::Label {
943 name: label.ident.name,
944 span: label.ident.span,
948 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
950 Some((id, label)) => {
951 let target_id = if let Def::Label(loop_id) = self.expect_full_def(id) {
952 Ok(self.lower_node_id(loop_id).node_id)
954 Err(hir::LoopIdError::UnresolvedLabel)
957 label: self.lower_label(Some(label)),
962 let target_id = self.loop_scopes
964 .map(|innermost_loop_id| *innermost_loop_id)
965 .map(|id| Ok(self.lower_node_id(id).node_id))
966 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
977 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
980 .map(|a| self.lower_attr(a))
985 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
989 path: attr.path.clone(),
990 tokens: self.lower_token_stream(attr.tokens.clone()),
991 is_sugared_doc: attr.is_sugared_doc,
996 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
999 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1003 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1005 TokenTree::Token(span, token) => self.lower_token(token, span),
1006 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1009 delim: delimited.delim,
1010 tts: self.lower_token_stream(delimited.tts.into()).into(),
1016 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1018 Token::Interpolated(_) => {}
1019 other => return TokenTree::Token(span, other).into(),
1022 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1023 self.lower_token_stream(tts)
1026 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1028 attrs: self.lower_attrs(&arm.attrs),
1029 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1030 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1031 body: P(self.lower_expr(&arm.body)),
1035 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1037 id: self.lower_node_id(b.id).node_id,
1038 name: self.lower_ident(b.ident),
1039 ty: self.lower_ty(&b.ty, itctx),
1044 fn lower_generic_arg(&mut self,
1045 arg: &ast::GenericArg,
1046 itctx: ImplTraitContext)
1047 -> hir::GenericArg {
1049 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1050 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty(&ty, itctx)),
1054 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1055 let kind = match t.node {
1056 TyKind::Infer => hir::TyInfer,
1057 TyKind::Err => hir::TyErr,
1058 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty, itctx)),
1059 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt, itctx)),
1060 TyKind::Rptr(ref region, ref mt) => {
1061 let span = t.span.shrink_to_lo();
1062 let lifetime = match *region {
1063 Some(ref lt) => self.lower_lifetime(lt),
1064 None => self.elided_ref_lifetime(span),
1066 hir::TyRptr(lifetime, self.lower_mt(mt, itctx))
1068 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1071 this.with_anonymous_lifetime_mode(
1072 AnonymousLifetimeMode::PassThrough,
1074 hir::TyBareFn(P(hir::BareFnTy {
1075 generic_params: this.lower_generic_params(
1078 ImplTraitContext::Disallowed,
1080 unsafety: this.lower_unsafety(f.unsafety),
1082 decl: this.lower_fn_decl(&f.decl, None, false),
1083 arg_names: this.lower_fn_args_to_names(&f.decl),
1089 TyKind::Never => hir::TyNever,
1090 TyKind::Tup(ref tys) => {
1091 hir::TyTup(tys.iter().map(|ty| self.lower_ty(ty, itctx)).collect())
1093 TyKind::Paren(ref ty) => {
1094 return self.lower_ty(ty, itctx);
1096 TyKind::Path(ref qself, ref path) => {
1097 let id = self.lower_node_id(t.id);
1098 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1099 let ty = self.ty_path(id, t.span, qpath);
1100 if let hir::TyTraitObject(..) = ty.node {
1101 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1105 TyKind::ImplicitSelf => hir::TyPath(hir::QPath::Resolved(
1108 def: self.expect_full_def(t.id),
1109 segments: hir_vec![hir::PathSegment::from_name(keywords::SelfType.name())],
1113 TyKind::Array(ref ty, ref length) => {
1114 hir::TyArray(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1116 TyKind::Typeof(ref expr) => {
1117 hir::TyTypeof(self.lower_anon_const(expr))
1119 TyKind::TraitObject(ref bounds, kind) => {
1120 let mut lifetime_bound = None;
1123 .filter_map(|bound| match *bound {
1124 TraitTyParamBound(ref ty, TraitBoundModifier::None) => {
1125 Some(self.lower_poly_trait_ref(ty, itctx))
1127 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
1128 Outlives(ref lifetime) => {
1129 if lifetime_bound.is_none() {
1130 lifetime_bound = Some(self.lower_lifetime(lifetime));
1136 let lifetime_bound =
1137 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1138 if kind != TraitObjectSyntax::Dyn {
1139 self.maybe_lint_bare_trait(t.span, t.id, false);
1141 hir::TyTraitObject(bounds, lifetime_bound)
1143 TyKind::ImplTrait(ref bounds) => {
1146 ImplTraitContext::Existential(fn_def_id) => {
1148 // We need to manually repeat the code of `next_id` because the lowering
1149 // needs to happen while the owner_id is pointing to the item itself,
1150 // because items are their own owners
1151 let exist_ty_node_id = self.sess.next_node_id();
1153 // Make sure we know that some funky desugaring has been going on here.
1154 // This is a first: there is code in other places like for loop
1155 // desugaring that explicitly states that we don't want to track that.
1156 // Not tracking it makes lints in rustc and clippy very fragile as
1157 // frequently opened issues show.
1158 let exist_ty_span = self.allow_internal_unstable(
1159 CompilerDesugaringKind::ExistentialReturnType,
1163 // Pull a new definition from the ether
1164 let exist_ty_def_index = self
1167 .create_def_with_parent(
1170 DefPathData::ExistentialImplTrait,
1171 DefIndexAddressSpace::High,
1176 // the `t` is just for printing debug messages
1177 self.allocate_hir_id_counter(exist_ty_node_id, t);
1179 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1180 lctx.lower_bounds(bounds, itctx)
1183 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1189 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1190 let exist_ty_item_kind = hir::ItemExistential(hir::ExistTy {
1191 generics: hir::Generics {
1192 params: lifetime_defs,
1193 where_clause: hir::WhereClause {
1194 id: lctx.next_id().node_id,
1195 predicates: Vec::new().into(),
1200 impl_trait_fn: Some(fn_def_id),
1202 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1203 // Generate an `existential type Foo: Trait;` declaration
1204 trace!("creating existential type with id {:#?}", exist_ty_id);
1205 // Set the name to `impl Bound1 + Bound2`
1206 let exist_ty_name = Symbol::intern(&pprust::ty_to_string(t));
1208 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1209 let exist_ty_item = hir::Item {
1210 id: exist_ty_id.node_id,
1211 hir_id: exist_ty_id.hir_id,
1212 name: exist_ty_name,
1213 attrs: Default::default(),
1214 node: exist_ty_item_kind,
1215 vis: hir::Visibility::Inherited,
1216 span: exist_ty_span,
1219 // Insert the item into the global list. This usually happens
1220 // automatically for all AST items. But this existential type item
1221 // does not actually exist in the AST.
1222 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1224 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1225 hir::TyImplTraitExistential(
1227 id: exist_ty_id.node_id
1229 DefId::local(exist_ty_def_index),
1234 ImplTraitContext::Universal(def_id) => {
1235 let def_node_id = self.next_id().node_id;
1237 // Add a definition for the in-band TyParam
1238 let def_index = self.resolver.definitions().create_def_with_parent(
1241 DefPathData::UniversalImplTrait,
1242 DefIndexAddressSpace::High,
1247 let hir_bounds = self.lower_param_bounds(bounds, itctx);
1248 // Set the name to `impl Bound1 + Bound2`
1249 let name = Symbol::intern(&pprust::ty_to_string(t));
1250 self.in_band_ty_params.push(hir::GenericParam {
1254 pure_wrt_drop: false,
1256 kind: hir::GenericParamKind::Type {
1258 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1263 hir::TyPath(hir::QPath::Resolved(
1267 def: Def::TyParam(DefId::local(def_index)),
1268 segments: hir_vec![hir::PathSegment::from_name(name)],
1272 ImplTraitContext::Disallowed => {
1277 "`impl Trait` not allowed outside of function \
1278 and inherent method return types"
1284 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1287 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1296 fn lifetimes_from_impl_trait_bounds(
1298 exist_ty_id: NodeId,
1299 parent_index: DefIndex,
1300 bounds: &hir::ParamBounds,
1301 ) -> (HirVec<hir::Lifetime>, HirVec<hir::GenericParam>) {
1302 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1303 // appear in the bounds, excluding lifetimes that are created within the bounds.
1304 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1305 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1306 context: &'r mut LoweringContext<'a>,
1308 exist_ty_id: NodeId,
1309 collect_elided_lifetimes: bool,
1310 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1311 already_defined_lifetimes: HashSet<hir::LifetimeName>,
1312 output_lifetimes: Vec<hir::Lifetime>,
1313 output_lifetime_params: Vec<hir::GenericParam>,
1316 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1317 fn nested_visit_map<'this>(
1319 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1320 hir::intravisit::NestedVisitorMap::None
1323 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1324 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1325 if parameters.parenthesized {
1326 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1327 self.collect_elided_lifetimes = false;
1328 hir::intravisit::walk_generic_args(self, span, parameters);
1329 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1331 hir::intravisit::walk_generic_args(self, span, parameters);
1335 fn visit_ty(&mut self, t: &'v hir::Ty) {
1336 // Don't collect elided lifetimes used inside of `fn()` syntax
1337 if let &hir::Ty_::TyBareFn(_) = &t.node {
1338 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1339 self.collect_elided_lifetimes = false;
1341 // Record the "stack height" of `for<'a>` lifetime bindings
1342 // to be able to later fully undo their introduction.
1343 let old_len = self.currently_bound_lifetimes.len();
1344 hir::intravisit::walk_ty(self, t);
1345 self.currently_bound_lifetimes.truncate(old_len);
1347 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1349 hir::intravisit::walk_ty(self, t);
1353 fn visit_poly_trait_ref(
1355 trait_ref: &'v hir::PolyTraitRef,
1356 modifier: hir::TraitBoundModifier,
1358 // Record the "stack height" of `for<'a>` lifetime bindings
1359 // to be able to later fully undo their introduction.
1360 let old_len = self.currently_bound_lifetimes.len();
1361 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1362 self.currently_bound_lifetimes.truncate(old_len);
1365 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1366 // Record the introduction of 'a in `for<'a> ...`
1367 if let hir::GenericParamKind::Lifetime { lt_name, .. } = param.kind {
1368 // Introduce lifetimes one at a time so that we can handle
1369 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1370 self.currently_bound_lifetimes.push(lt_name);
1373 hir::intravisit::walk_generic_param(self, param);
1376 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1377 let name = match lifetime.name {
1378 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1379 if self.collect_elided_lifetimes {
1380 // Use `'_` for both implicit and underscore lifetimes in
1381 // `abstract type Foo<'_>: SomeTrait<'_>;`
1382 hir::LifetimeName::Underscore
1387 name @ hir::LifetimeName::Fresh(_) => name,
1388 name @ hir::LifetimeName::Name(_) => name,
1389 hir::LifetimeName::Static => return,
1392 if !self.currently_bound_lifetimes.contains(&name)
1393 && !self.already_defined_lifetimes.contains(&name)
1395 self.already_defined_lifetimes.insert(name);
1397 self.output_lifetimes.push(hir::Lifetime {
1398 id: self.context.next_id().node_id,
1399 span: lifetime.span,
1403 // We need to manually create the ids here, because the
1404 // definitions will go into the explicit `existential type`
1405 // declaration and thus need to have their owner set to that item
1406 let def_node_id = self.context.sess.next_node_id();
1407 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1408 self.context.resolver.definitions().create_def_with_parent(
1411 DefPathData::LifetimeParam(name.name().as_interned_str()),
1412 DefIndexAddressSpace::High,
1417 self.output_lifetime_params.push(hir::GenericParam {
1420 span: lifetime.span,
1421 pure_wrt_drop: false,
1422 bounds: vec![].into(),
1423 kind: hir::GenericParamKind::Lifetime {
1426 lifetime: hir::Lifetime {
1428 span: lifetime.span,
1437 let mut lifetime_collector = ImplTraitLifetimeCollector {
1439 parent: parent_index,
1441 collect_elided_lifetimes: true,
1442 currently_bound_lifetimes: Vec::new(),
1443 already_defined_lifetimes: HashSet::new(),
1444 output_lifetimes: Vec::new(),
1445 output_lifetime_params: Vec::new(),
1448 for bound in bounds {
1449 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1453 lifetime_collector.output_lifetimes.into(),
1454 lifetime_collector.output_lifetime_params.into(),
1458 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1463 .map(|x| self.lower_foreign_item(x))
1468 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1475 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1477 node: hir::Variant_ {
1478 name: v.node.ident.name,
1479 attrs: self.lower_attrs(&v.node.attrs),
1480 data: self.lower_variant_data(&v.node.data),
1481 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1490 qself: &Option<QSelf>,
1492 param_mode: ParamMode,
1493 itctx: ImplTraitContext,
1495 let qself_position = qself.as_ref().map(|q| q.position);
1496 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx));
1498 let resolution = self.resolver
1500 .unwrap_or(PathResolution::new(Def::Err));
1502 let proj_start = p.segments.len() - resolution.unresolved_segments();
1503 let path = P(hir::Path {
1504 def: resolution.base_def(),
1505 segments: p.segments[..proj_start]
1508 .map(|(i, segment)| {
1509 let param_mode = match (qself_position, param_mode) {
1510 (Some(j), ParamMode::Optional) if i < j => {
1511 // This segment is part of the trait path in a
1512 // qualified path - one of `a`, `b` or `Trait`
1513 // in `<X as a::b::Trait>::T::U::method`.
1519 // Figure out if this is a type/trait segment,
1520 // which may need lifetime elision performed.
1521 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1522 krate: def_id.krate,
1523 index: this.def_key(def_id).parent.expect("missing parent"),
1525 let type_def_id = match resolution.base_def() {
1526 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1527 Some(parent_def_id(self, def_id))
1529 Def::Variant(def_id) if i + 1 == proj_start => {
1530 Some(parent_def_id(self, def_id))
1533 | Def::Union(def_id)
1535 | Def::TyAlias(def_id)
1536 | Def::Trait(def_id) if i + 1 == proj_start =>
1542 let parenthesized_generic_args = match resolution.base_def() {
1543 // `a::b::Trait(Args)`
1544 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1545 // `a::b::Trait(Args)::TraitItem`
1546 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1547 if i + 2 == proj_start =>
1549 ParenthesizedGenericArgs::Ok
1551 // Avoid duplicated errors
1552 Def::Err => ParenthesizedGenericArgs::Ok,
1558 | Def::Variant(..) if i + 1 == proj_start =>
1560 ParenthesizedGenericArgs::Err
1562 // A warning for now, for compatibility reasons
1563 _ => ParenthesizedGenericArgs::Warn,
1566 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1567 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1570 assert!(!def_id.is_local());
1572 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1573 let n = item_generics.own_counts().lifetimes;
1574 self.type_def_lifetime_params.insert(def_id, n);
1577 self.lower_path_segment(
1582 parenthesized_generic_args,
1590 // Simple case, either no projections, or only fully-qualified.
1591 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1592 if resolution.unresolved_segments() == 0 {
1593 return hir::QPath::Resolved(qself, path);
1596 // Create the innermost type that we're projecting from.
1597 let mut ty = if path.segments.is_empty() {
1598 // If the base path is empty that means there exists a
1599 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1600 qself.expect("missing QSelf for <T>::...")
1602 // Otherwise, the base path is an implicit `Self` type path,
1603 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1604 // `<I as Iterator>::Item::default`.
1605 let new_id = self.next_id();
1606 self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))
1609 // Anything after the base path are associated "extensions",
1610 // out of which all but the last one are associated types,
1611 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1612 // * base path is `std::vec::Vec<T>`
1613 // * "extensions" are `IntoIter`, `Item` and `clone`
1614 // * type nodes are:
1615 // 1. `std::vec::Vec<T>` (created above)
1616 // 2. `<std::vec::Vec<T>>::IntoIter`
1617 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1618 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1619 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1620 let segment = P(self.lower_path_segment(
1625 ParenthesizedGenericArgs::Warn,
1628 let qpath = hir::QPath::TypeRelative(ty, segment);
1630 // It's finished, return the extension of the right node type.
1631 if i == p.segments.len() - 1 {
1635 // Wrap the associated extension in another type node.
1636 let new_id = self.next_id();
1637 ty = self.ty_path(new_id, p.span, qpath);
1640 // Should've returned in the for loop above.
1643 "lower_qpath: no final extension segment in {}..{}",
1649 fn lower_path_extra(
1654 param_mode: ParamMode,
1658 segments: p.segments
1661 self.lower_path_segment(
1666 ParenthesizedGenericArgs::Err,
1667 ImplTraitContext::Disallowed,
1670 .chain(name.map(|name| hir::PathSegment::from_name(name)))
1676 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1677 let def = self.expect_full_def(id);
1678 self.lower_path_extra(def, p, None, param_mode)
1681 fn lower_path_segment(
1684 segment: &PathSegment,
1685 param_mode: ParamMode,
1686 expected_lifetimes: usize,
1687 parenthesized_generic_args: ParenthesizedGenericArgs,
1688 itctx: ImplTraitContext,
1689 ) -> hir::PathSegment {
1690 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1691 let msg = "parenthesized parameters may only be used with a trait";
1692 match **generic_args {
1693 GenericArgs::AngleBracketed(ref data) => {
1694 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1696 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1697 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1698 ParenthesizedGenericArgs::Warn => {
1699 self.sess.buffer_lint(
1700 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1705 (hir::GenericArgs::none(), true)
1707 ParenthesizedGenericArgs::Err => {
1708 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1709 .span_label(data.span, "only traits may use parentheses")
1711 (hir::GenericArgs::none(), true)
1716 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1719 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1720 GenericArg::Lifetime(_) => true,
1723 if !generic_args.parenthesized && !has_lifetimes {
1725 self.elided_path_lifetimes(path_span, expected_lifetimes)
1727 .map(|lt| GenericArg::Lifetime(lt))
1728 .chain(generic_args.args.into_iter())
1732 hir::PathSegment::new(
1733 self.lower_ident(segment.ident),
1739 fn lower_angle_bracketed_parameter_data(
1741 data: &AngleBracketedArgs,
1742 param_mode: ParamMode,
1743 itctx: ImplTraitContext,
1744 ) -> (hir::GenericArgs, bool) {
1745 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1746 let has_types = args.iter().any(|arg| match arg {
1747 ast::GenericArg::Type(_) => true,
1751 args: args.iter().map(|a| self.lower_generic_arg(a, itctx)).collect(),
1752 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(),
1753 parenthesized: false,
1755 !has_types && param_mode == ParamMode::Optional)
1758 fn lower_parenthesized_parameter_data(
1760 data: &ParenthesizedParameterData,
1761 ) -> (hir::PathParameters, bool) {
1762 // Switch to `PassThrough` mode for anonymous lifetimes: this
1763 // means that we permit things like `&Ref<T>`, where `Ref` has
1764 // a hidden lifetime parameter. This is needed for backwards
1765 // compatibility, even in contexts like an impl header where
1766 // we generally don't permit such things (see #51008).
1767 self.with_anonymous_lifetime_mode(
1768 AnonymousLifetimeMode::PassThrough,
1770 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1771 let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
1772 let inputs = inputs.iter().map(|ty| this.lower_ty(ty, DISALLOWED)).collect();
1773 let mk_tup = |this: &mut Self, tys, span| {
1774 let LoweredNodeId { node_id, hir_id } = this.next_id();
1775 P(hir::Ty { node: hir::TyTup(tys), id: node_id, hir_id, span })
1780 parameters: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1783 id: this.next_id().node_id,
1784 name: Symbol::intern(FN_OUTPUT_NAME),
1787 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1788 .unwrap_or_else(|| mk_tup(this, hir::HirVec::new(), span)),
1789 span: output.as_ref().map_or(span, |ty| ty.span),
1792 parenthesized: true,
1800 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1801 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1807 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1808 pat: self.lower_pat(&l.pat),
1809 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1811 attrs: l.attrs.clone(),
1812 source: hir::LocalSource::Normal,
1816 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1818 Mutability::Mutable => hir::MutMutable,
1819 Mutability::Immutable => hir::MutImmutable,
1823 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1824 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1828 pat: self.lower_pat(&arg.pat),
1832 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Spanned<Name>> {
1835 .map(|arg| match arg.pat.node {
1836 PatKind::Ident(_, ident, None) => respan(ident.span, ident.name),
1837 _ => respan(arg.pat.span, keywords::Invalid.name()),
1845 fn_def_id: Option<DefId>,
1846 impl_trait_return_allow: bool,
1847 ) -> P<hir::FnDecl> {
1848 // NOTE: The two last parameters here have to do with impl Trait. If fn_def_id is Some,
1849 // then impl Trait arguments are lowered into generic parameters on the given
1850 // fn_def_id, otherwise impl Trait is disallowed. (for now)
1852 // Furthermore, if impl_trait_return_allow is true, then impl Trait may be used in
1853 // return positions as well. This guards against trait declarations and their impls
1854 // where impl Trait is disallowed. (again for now)
1859 if let Some(def_id) = fn_def_id {
1860 self.lower_ty(&arg.ty, ImplTraitContext::Universal(def_id))
1862 self.lower_ty(&arg.ty, ImplTraitContext::Disallowed)
1866 output: match decl.output {
1867 FunctionRetTy::Ty(ref ty) => match fn_def_id {
1868 Some(def_id) if impl_trait_return_allow => {
1869 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1871 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1873 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1875 variadic: decl.variadic,
1876 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1877 TyKind::ImplicitSelf => true,
1878 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1884 fn lower_param_bound(
1887 itctx: ImplTraitContext,
1888 ) -> hir::ParamBound {
1890 TraitTyParamBound(ref ty, modifier) => hir::TraitTyParamBound(
1891 self.lower_poly_trait_ref(ty, itctx),
1892 self.lower_trait_bound_modifier(modifier),
1894 Outlives(ref lifetime) => {
1895 hir::Outlives(self.lower_lifetime(lifetime))
1900 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1901 let span = l.ident.span;
1902 match self.lower_ident(l.ident) {
1903 x if x == "'static" => self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
1904 x if x == "'_" => match self.anonymous_lifetime_mode {
1905 AnonymousLifetimeMode::CreateParameter => {
1906 let fresh_name = self.collect_fresh_in_band_lifetime(span);
1907 self.new_named_lifetime(l.id, span, fresh_name)
1910 AnonymousLifetimeMode::PassThrough => {
1911 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
1915 self.maybe_collect_in_band_lifetime(span, name);
1916 self.new_named_lifetime(l.id, span, hir::LifetimeName::Name(name))
1921 fn new_named_lifetime(
1925 name: hir::LifetimeName,
1926 ) -> hir::Lifetime {
1928 id: self.lower_node_id(id).node_id,
1934 fn lower_generic_params(
1936 params: &Vec<GenericParam>,
1937 add_bounds: &NodeMap<Vec<ParamBound>>,
1938 itctx: ImplTraitContext,
1939 ) -> hir::HirVec<hir::GenericParam> {
1940 params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect()
1943 fn lower_generic_param(&mut self,
1944 param: &GenericParam,
1945 add_bounds: &NodeMap<Vec<ParamBound>>,
1946 itctx: ImplTraitContext)
1947 -> hir::GenericParam {
1948 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx);
1950 GenericParamKind::Lifetime { ref lifetime } => {
1951 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
1952 self.is_collecting_in_band_lifetimes = false;
1954 let lifetime = self.lower_lifetime(lifetime);
1955 let param = hir::GenericParam {
1957 name: lifetime.name.name(),
1958 span: lifetime.span,
1959 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
1961 kind: hir::GenericParamKind::Lifetime {
1962 lt_name: lifetime.name,
1968 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
1972 GenericParamKind::Type { ref default, .. } => {
1973 let mut name = self.lower_ident(param.ident);
1975 // Don't expose `Self` (recovered "keyword used as ident" parse error).
1976 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
1977 // Instead, use gensym("Self") to create a distinct name that looks the same.
1978 if name == keywords::SelfType.name() {
1979 name = Symbol::gensym("Self");
1982 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
1983 if !add_bounds.is_empty() {
1984 bounds = bounds.into_iter()
1985 .chain(self.lower_param_bounds(add_bounds, itctx).into_iter())
1990 id: self.lower_node_id(param.id).node_id,
1992 span: param.ident.span,
1993 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
1995 kind: hir::GenericParamKind::Type {
1996 default: default.as_ref().map(|x| {
1997 self.lower_ty(x, ImplTraitContext::Disallowed)
1999 synthetic: param.attrs.iter()
2000 .filter(|attr| attr.check_name("rustc_synthetic"))
2001 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2003 attrs: self.lower_attrs(¶m.attrs),
2012 generics: &Generics,
2013 itctx: ImplTraitContext)
2016 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2017 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2018 // paths where report_error is called are also the only paths that advance to after
2019 // the match statement, so the error reporting could probably just be moved there.
2020 let mut add_bounds = NodeMap();
2021 for pred in &generics.where_clause.predicates {
2022 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2023 'next_bound: for bound in &bound_pred.bounds {
2024 if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
2025 let report_error = |this: &mut Self| {
2026 this.diagnostic().span_err(
2027 bound_pred.bounded_ty.span,
2028 "`?Trait` bounds are only permitted at the \
2029 point where a type parameter is declared",
2032 // Check if the where clause type is a plain type parameter.
2033 match bound_pred.bounded_ty.node {
2034 TyKind::Path(None, ref path)
2035 if path.segments.len() == 1
2036 && bound_pred.bound_generic_params.is_empty() =>
2038 if let Some(Def::TyParam(def_id)) = self.resolver
2039 .get_resolution(bound_pred.bounded_ty.id)
2040 .map(|d| d.base_def())
2042 if let Some(node_id) =
2043 self.resolver.definitions().as_local_node_id(def_id)
2045 for param in &generics.params {
2047 GenericParamKind::Type { .. } => {
2048 if node_id == param.id {
2049 add_bounds.entry(param.id)
2050 .or_insert(Vec::new())
2051 .push(bound.clone());
2052 continue 'next_bound;
2062 _ => report_error(self),
2070 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2071 where_clause: self.lower_where_clause(&generics.where_clause),
2072 span: generics.span,
2076 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2078 id: self.lower_node_id(wc.id).node_id,
2079 predicates: wc.predicates
2081 .map(|predicate| self.lower_where_predicate(predicate))
2086 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2088 WherePredicate::BoundPredicate(WhereBoundPredicate {
2089 ref bound_generic_params,
2094 self.with_in_scope_lifetime_defs(
2095 &bound_generic_params,
2097 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2098 bound_generic_params: this.lower_generic_params(
2099 bound_generic_params,
2101 ImplTraitContext::Disallowed,
2103 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2106 .filter_map(|bound| match *bound {
2107 // Ignore `?Trait` bounds.
2108 // Tthey were copied into type parameters already.
2109 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
2110 _ => Some(this.lower_param_bound(
2112 ImplTraitContext::Disallowed,
2121 WherePredicate::RegionPredicate(WhereRegionPredicate {
2125 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2127 lifetime: self.lower_lifetime(lifetime),
2128 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2130 WherePredicate::EqPredicate(WhereEqPredicate {
2135 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2136 id: self.lower_node_id(id).node_id,
2137 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2138 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2144 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2146 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2150 .map(|f| self.lower_struct_field(f))
2152 self.lower_node_id(id).node_id,
2154 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2158 .map(|f| self.lower_struct_field(f))
2160 self.lower_node_id(id).node_id,
2162 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2166 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2167 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2168 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2169 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2173 ref_id: self.lower_node_id(p.ref_id).node_id,
2177 fn lower_poly_trait_ref(
2180 itctx: ImplTraitContext,
2181 ) -> hir::PolyTraitRef {
2182 let bound_generic_params =
2183 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx);
2184 let trait_ref = self.with_parent_impl_lifetime_defs(
2185 &bound_generic_params,
2186 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2190 bound_generic_params,
2196 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2199 id: self.lower_node_id(f.id).node_id,
2200 ident: match f.ident {
2201 Some(ident) => ident,
2202 // FIXME(jseyfried) positional field hygiene
2203 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2205 vis: self.lower_visibility(&f.vis, None),
2206 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2207 attrs: self.lower_attrs(&f.attrs),
2211 fn lower_field(&mut self, f: &Field) -> hir::Field {
2213 id: self.next_id().node_id,
2215 expr: P(self.lower_expr(&f.expr)),
2217 is_shorthand: f.is_shorthand,
2221 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2223 ty: self.lower_ty(&mt.ty, itctx),
2224 mutbl: self.lower_mutability(mt.mutbl),
2228 fn lower_param_bounds(&mut self, bounds: &[ParamBound], itctx: ImplTraitContext)
2229 -> hir::ParamBounds {
2230 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx)).collect()
2233 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2234 let mut expr = None;
2236 let mut stmts = vec![];
2238 for (index, stmt) in b.stmts.iter().enumerate() {
2239 if index == b.stmts.len() - 1 {
2240 if let StmtKind::Expr(ref e) = stmt.node {
2241 expr = Some(P(self.lower_expr(e)));
2243 stmts.extend(self.lower_stmt(stmt));
2246 stmts.extend(self.lower_stmt(stmt));
2250 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2255 stmts: stmts.into(),
2257 rules: self.lower_block_check_mode(&b.rules),
2260 recovered: b.recovered,
2268 attrs: &hir::HirVec<Attribute>,
2269 vis: &mut hir::Visibility,
2273 ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2274 ItemKind::Use(ref use_tree) => {
2275 // Start with an empty prefix
2278 span: use_tree.span,
2281 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2283 ItemKind::Static(ref t, m, ref e) => {
2284 let value = self.lower_body(None, |this| this.lower_expr(e));
2286 self.lower_ty(t, ImplTraitContext::Disallowed),
2287 self.lower_mutability(m),
2291 ItemKind::Const(ref t, ref e) => {
2292 let value = self.lower_body(None, |this| this.lower_expr(e));
2293 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2295 ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
2296 let fn_def_id = self.resolver.definitions().local_def_id(id);
2297 self.with_new_scopes(|this| {
2298 let body_id = this.lower_body(Some(decl), |this| {
2299 let body = this.lower_block(body, false);
2300 this.expr_block(body, ThinVec::new())
2302 let (generics, fn_decl) = this.add_in_band_defs(
2305 AnonymousLifetimeMode::PassThrough,
2306 |this| this.lower_fn_decl(decl, Some(fn_def_id), true),
2311 this.lower_unsafety(unsafety),
2312 this.lower_constness(constness),
2319 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2320 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2321 ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2322 ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2323 self.lower_ty(t, ImplTraitContext::Disallowed),
2324 self.lower_generics(generics, ImplTraitContext::Disallowed),
2326 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2328 variants: enum_definition
2331 .map(|x| self.lower_variant(x))
2334 self.lower_generics(generics, ImplTraitContext::Disallowed),
2336 ItemKind::Struct(ref struct_def, ref generics) => {
2337 let struct_def = self.lower_variant_data(struct_def);
2340 self.lower_generics(generics, ImplTraitContext::Disallowed),
2343 ItemKind::Union(ref vdata, ref generics) => {
2344 let vdata = self.lower_variant_data(vdata);
2347 self.lower_generics(generics, ImplTraitContext::Disallowed),
2359 let def_id = self.resolver.definitions().local_def_id(id);
2361 // Lower the "impl header" first. This ordering is important
2362 // for in-band lifetimes! Consider `'a` here:
2364 // impl Foo<'a> for u32 {
2365 // fn method(&'a self) { .. }
2368 // Because we start by lowering the `Foo<'a> for u32`
2369 // part, we will add `'a` to the list of generics on
2370 // the impl. When we then encounter it later in the
2371 // method, it will not be considered an in-band
2372 // lifetime to be added, but rather a reference to a
2374 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2377 AnonymousLifetimeMode::CreateParameter,
2379 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2380 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2383 if let Some(ref trait_ref) = trait_ref {
2384 if let Def::Trait(def_id) = trait_ref.path.def {
2385 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2389 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2391 (trait_ref, lowered_ty)
2395 let new_impl_items = self.with_in_scope_lifetime_defs(
2396 &ast_generics.params,
2400 .map(|item| this.lower_impl_item_ref(item))
2406 self.lower_unsafety(unsafety),
2407 self.lower_impl_polarity(polarity),
2408 self.lower_defaultness(defaultness, true /* [1] */),
2415 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2416 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2419 .map(|item| self.lower_trait_item_ref(item))
2422 self.lower_is_auto(is_auto),
2423 self.lower_unsafety(unsafety),
2424 self.lower_generics(generics, ImplTraitContext::Disallowed),
2429 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2430 self.lower_generics(generics, ImplTraitContext::Disallowed),
2431 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2433 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2436 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2437 // not cause an assertion failure inside the `lower_defaultness` function
2445 vis: &mut hir::Visibility,
2447 attrs: &hir::HirVec<Attribute>,
2449 let path = &tree.prefix;
2452 UseTreeKind::Simple(rename, id1, id2) => {
2453 *name = tree.ident().name;
2455 // First apply the prefix to the path
2456 let mut path = Path {
2460 .chain(path.segments.iter())
2466 // Correctly resolve `self` imports
2467 if path.segments.len() > 1
2468 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2470 let _ = path.segments.pop();
2471 if rename.is_none() {
2472 *name = path.segments.last().unwrap().ident.name;
2476 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2477 let mut defs = self.expect_full_def_from_use(id);
2478 // we want to return *something* from this function, so hang onto the first item
2480 let mut ret_def = defs.next().unwrap_or(Def::Err);
2482 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2483 let vis = vis.clone();
2484 let name = name.clone();
2485 let span = path.span;
2486 self.resolver.definitions().create_def_with_parent(
2490 DefIndexAddressSpace::High,
2493 self.allocate_hir_id_counter(new_node_id, &path);
2495 self.with_hir_id_owner(new_node_id, |this| {
2496 let new_id = this.lower_node_id(new_node_id);
2497 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2498 let item = hir::ItemUse(P(path), hir::UseKind::Single);
2499 let vis = match vis {
2500 hir::Visibility::Public => hir::Visibility::Public,
2501 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2502 hir::Visibility::Inherited => hir::Visibility::Inherited,
2503 hir::Visibility::Restricted { ref path, id: _ } => {
2504 hir::Visibility::Restricted {
2506 // We are allocating a new NodeId here
2507 id: this.next_id().node_id,
2516 hir_id: new_id.hir_id,
2518 attrs: attrs.clone(),
2527 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2528 hir::ItemUse(path, hir::UseKind::Single)
2530 UseTreeKind::Glob => {
2531 let path = P(self.lower_path(
2537 .chain(path.segments.iter())
2542 ParamMode::Explicit,
2544 hir::ItemUse(path, hir::UseKind::Glob)
2546 UseTreeKind::Nested(ref trees) => {
2551 .chain(path.segments.iter())
2554 span: prefix.span.to(path.span),
2557 // Add all the nested PathListItems in the HIR
2558 for &(ref use_tree, id) in trees {
2559 self.allocate_hir_id_counter(id, &use_tree);
2563 } = self.lower_node_id(id);
2565 let mut vis = vis.clone();
2566 let mut name = name.clone();
2568 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2570 self.with_hir_id_owner(new_id, |this| {
2571 let vis = match vis {
2572 hir::Visibility::Public => hir::Visibility::Public,
2573 hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2574 hir::Visibility::Inherited => hir::Visibility::Inherited,
2575 hir::Visibility::Restricted { ref path, id: _ } => {
2576 hir::Visibility::Restricted {
2578 // We are allocating a new NodeId here
2579 id: this.next_id().node_id,
2590 attrs: attrs.clone(),
2593 span: use_tree.span,
2599 // Privatize the degenerate import base, used only to check
2600 // the stability of `use a::{};`, to avoid it showing up as
2601 // a re-export by accident when `pub`, e.g. in documentation.
2602 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2603 *vis = hir::Inherited;
2604 hir::ItemUse(path, hir::UseKind::ListStem)
2609 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2610 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2611 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2613 let (generics, node) = match i.node {
2614 TraitItemKind::Const(ref ty, ref default) => (
2615 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2616 hir::TraitItemKind::Const(
2617 self.lower_ty(ty, ImplTraitContext::Disallowed),
2620 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2623 TraitItemKind::Method(ref sig, None) => {
2624 let names = self.lower_fn_args_to_names(&sig.decl);
2625 self.add_in_band_defs(
2628 AnonymousLifetimeMode::PassThrough,
2630 hir::TraitItemKind::Method(
2631 this.lower_method_sig(sig, trait_item_def_id, false),
2632 hir::TraitMethod::Required(names),
2637 TraitItemKind::Method(ref sig, Some(ref body)) => {
2638 let body_id = self.lower_body(Some(&sig.decl), |this| {
2639 let body = this.lower_block(body, false);
2640 this.expr_block(body, ThinVec::new())
2643 self.add_in_band_defs(
2646 AnonymousLifetimeMode::PassThrough,
2648 hir::TraitItemKind::Method(
2649 this.lower_method_sig(sig, trait_item_def_id, false),
2650 hir::TraitMethod::Provided(body_id),
2655 TraitItemKind::Type(ref bounds, ref default) => (
2656 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2657 hir::TraitItemKind::Type(
2658 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2661 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2664 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2670 name: self.lower_ident(i.ident),
2671 attrs: self.lower_attrs(&i.attrs),
2678 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2679 let (kind, has_default) = match i.node {
2680 TraitItemKind::Const(_, ref default) => {
2681 (hir::AssociatedItemKind::Const, default.is_some())
2683 TraitItemKind::Type(_, ref default) => {
2684 (hir::AssociatedItemKind::Type, default.is_some())
2686 TraitItemKind::Method(ref sig, ref default) => (
2687 hir::AssociatedItemKind::Method {
2688 has_self: sig.decl.has_self(),
2692 TraitItemKind::Macro(..) => unimplemented!(),
2695 id: hir::TraitItemId { node_id: i.id },
2696 name: self.lower_ident(i.ident),
2698 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
2703 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
2704 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2705 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
2707 let (generics, node) = match i.node {
2708 ImplItemKind::Const(ref ty, ref expr) => {
2709 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
2711 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2712 hir::ImplItemKind::Const(
2713 self.lower_ty(ty, ImplTraitContext::Disallowed),
2718 ImplItemKind::Method(ref sig, ref body) => {
2719 let body_id = self.lower_body(Some(&sig.decl), |this| {
2720 let body = this.lower_block(body, false);
2721 this.expr_block(body, ThinVec::new())
2723 let impl_trait_return_allow = !self.is_in_trait_impl;
2725 self.add_in_band_defs(
2728 AnonymousLifetimeMode::PassThrough,
2730 hir::ImplItemKind::Method(
2731 this.lower_method_sig(
2734 impl_trait_return_allow,
2741 ImplItemKind::Type(ref ty) => (
2742 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2743 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
2745 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2751 name: self.lower_ident(i.ident),
2752 attrs: self.lower_attrs(&i.attrs),
2754 vis: self.lower_visibility(&i.vis, None),
2755 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2760 // [1] since `default impl` is not yet implemented, this is always true in impls
2763 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
2765 id: hir::ImplItemId { node_id: i.id },
2766 name: self.lower_ident(i.ident),
2768 vis: self.lower_visibility(&i.vis, Some(i.id)),
2769 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2770 kind: match i.node {
2771 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
2772 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
2773 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
2774 has_self: sig.decl.has_self(),
2776 ImplItemKind::Macro(..) => unimplemented!(),
2780 // [1] since `default impl` is not yet implemented, this is always true in impls
2783 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
2786 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
2790 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
2792 ItemKind::Use(ref use_tree) => {
2793 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
2794 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
2797 ItemKind::MacroDef(..) => return SmallVector::new(),
2800 SmallVector::one(hir::ItemId { id: i.id })
2803 fn lower_item_id_use_tree(&mut self,
2806 vec: &mut SmallVector<hir::ItemId>)
2809 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
2810 vec.push(hir::ItemId { id });
2811 self.lower_item_id_use_tree(nested, id, vec);
2813 UseTreeKind::Glob => {}
2814 UseTreeKind::Simple(_, id1, id2) => {
2815 for (_, &id) in self.expect_full_def_from_use(base_id)
2817 .zip([id1, id2].iter())
2819 vec.push(hir::ItemId { id });
2825 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
2826 let mut name = i.ident.name;
2827 let mut vis = self.lower_visibility(&i.vis, None);
2828 let attrs = self.lower_attrs(&i.attrs);
2829 if let ItemKind::MacroDef(ref def) = i.node {
2830 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
2831 let body = self.lower_token_stream(def.stream());
2832 self.exported_macros.push(hir::MacroDef {
2845 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
2847 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2860 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
2861 let node_id = self.lower_node_id(i.id).node_id;
2862 let def_id = self.resolver.definitions().local_def_id(node_id);
2866 attrs: self.lower_attrs(&i.attrs),
2867 node: match i.node {
2868 ForeignItemKind::Fn(ref fdec, ref generics) => {
2869 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
2872 AnonymousLifetimeMode::PassThrough,
2875 // Disallow impl Trait in foreign items
2876 this.lower_fn_decl(fdec, None, false),
2877 this.lower_fn_args_to_names(fdec),
2882 hir::ForeignItemFn(fn_dec, fn_args, generics)
2884 ForeignItemKind::Static(ref t, m) => {
2885 hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
2887 ForeignItemKind::Ty => hir::ForeignItemType,
2888 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
2890 vis: self.lower_visibility(&i.vis, None),
2895 fn lower_method_sig(
2899 impl_trait_return_allow: bool,
2900 ) -> hir::MethodSig {
2903 unsafety: self.lower_unsafety(sig.unsafety),
2904 constness: self.lower_constness(sig.constness),
2905 decl: self.lower_fn_decl(&sig.decl, Some(fn_def_id), impl_trait_return_allow),
2909 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
2911 IsAuto::Yes => hir::IsAuto::Yes,
2912 IsAuto::No => hir::IsAuto::No,
2916 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
2918 Unsafety::Unsafe => hir::Unsafety::Unsafe,
2919 Unsafety::Normal => hir::Unsafety::Normal,
2923 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
2925 Constness::Const => hir::Constness::Const,
2926 Constness::NotConst => hir::Constness::NotConst,
2930 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
2932 UnOp::Deref => hir::UnDeref,
2933 UnOp::Not => hir::UnNot,
2934 UnOp::Neg => hir::UnNeg,
2938 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
2940 node: match b.node {
2941 BinOpKind::Add => hir::BiAdd,
2942 BinOpKind::Sub => hir::BiSub,
2943 BinOpKind::Mul => hir::BiMul,
2944 BinOpKind::Div => hir::BiDiv,
2945 BinOpKind::Rem => hir::BiRem,
2946 BinOpKind::And => hir::BiAnd,
2947 BinOpKind::Or => hir::BiOr,
2948 BinOpKind::BitXor => hir::BiBitXor,
2949 BinOpKind::BitAnd => hir::BiBitAnd,
2950 BinOpKind::BitOr => hir::BiBitOr,
2951 BinOpKind::Shl => hir::BiShl,
2952 BinOpKind::Shr => hir::BiShr,
2953 BinOpKind::Eq => hir::BiEq,
2954 BinOpKind::Lt => hir::BiLt,
2955 BinOpKind::Le => hir::BiLe,
2956 BinOpKind::Ne => hir::BiNe,
2957 BinOpKind::Ge => hir::BiGe,
2958 BinOpKind::Gt => hir::BiGt,
2964 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2965 let node = match p.node {
2966 PatKind::Wild => hir::PatKind::Wild,
2967 PatKind::Ident(ref binding_mode, ident, ref sub) => {
2968 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
2969 // `None` can occur in body-less function signatures
2970 def @ None | def @ Some(Def::Local(_)) => {
2971 let canonical_id = match def {
2972 Some(Def::Local(id)) => id,
2975 hir::PatKind::Binding(
2976 self.lower_binding_mode(binding_mode),
2978 respan(ident.span, ident.name),
2979 sub.as_ref().map(|x| self.lower_pat(x)),
2982 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
2987 segments: hir_vec![hir::PathSegment::from_name(ident.name)],
2992 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
2993 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
2994 let qpath = self.lower_qpath(
2998 ParamMode::Optional,
2999 ImplTraitContext::Disallowed,
3001 hir::PatKind::TupleStruct(
3003 pats.iter().map(|x| self.lower_pat(x)).collect(),
3007 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3011 ParamMode::Optional,
3012 ImplTraitContext::Disallowed,
3014 PatKind::Struct(ref path, ref fields, etc) => {
3015 let qpath = self.lower_qpath(
3019 ParamMode::Optional,
3020 ImplTraitContext::Disallowed,
3027 node: hir::FieldPat {
3028 id: self.next_id().node_id,
3029 ident: f.node.ident,
3030 pat: self.lower_pat(&f.node.pat),
3031 is_shorthand: f.node.is_shorthand,
3035 hir::PatKind::Struct(qpath, fs, etc)
3037 PatKind::Tuple(ref elts, ddpos) => {
3038 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3040 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3041 PatKind::Ref(ref inner, mutbl) => {
3042 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3044 PatKind::Range(ref e1, ref e2, ref end) => hir::PatKind::Range(
3045 P(self.lower_expr(e1)),
3046 P(self.lower_expr(e2)),
3047 self.lower_range_end(end),
3049 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3050 before.iter().map(|x| self.lower_pat(x)).collect(),
3051 slice.as_ref().map(|x| self.lower_pat(x)),
3052 after.iter().map(|x| self.lower_pat(x)).collect(),
3054 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3055 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3058 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3067 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3069 RangeEnd::Included(_) => hir::RangeEnd::Included,
3070 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3074 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3075 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3080 body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3084 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3085 let kind = match e.node {
3086 ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
3087 ExprKind::ObsoleteInPlace(..) => {
3088 self.sess.abort_if_errors();
3089 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3091 ExprKind::Array(ref exprs) => {
3092 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
3094 ExprKind::Repeat(ref expr, ref count) => {
3095 let expr = P(self.lower_expr(expr));
3096 let count = self.lower_anon_const(count);
3097 hir::ExprRepeat(expr, count)
3099 ExprKind::Tup(ref elts) => {
3100 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
3102 ExprKind::Call(ref f, ref args) => {
3103 let f = P(self.lower_expr(f));
3104 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
3106 ExprKind::MethodCall(ref seg, ref args) => {
3107 let hir_seg = self.lower_path_segment(
3110 ParamMode::Optional,
3112 ParenthesizedGenericArgs::Err,
3113 ImplTraitContext::Disallowed,
3115 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3116 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
3118 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3119 let binop = self.lower_binop(binop);
3120 let lhs = P(self.lower_expr(lhs));
3121 let rhs = P(self.lower_expr(rhs));
3122 hir::ExprBinary(binop, lhs, rhs)
3124 ExprKind::Unary(op, ref ohs) => {
3125 let op = self.lower_unop(op);
3126 let ohs = P(self.lower_expr(ohs));
3127 hir::ExprUnary(op, ohs)
3129 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
3130 ExprKind::Cast(ref expr, ref ty) => {
3131 let expr = P(self.lower_expr(expr));
3132 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3134 ExprKind::Type(ref expr, ref ty) => {
3135 let expr = P(self.lower_expr(expr));
3136 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3138 ExprKind::AddrOf(m, ref ohs) => {
3139 let m = self.lower_mutability(m);
3140 let ohs = P(self.lower_expr(ohs));
3141 hir::ExprAddrOf(m, ohs)
3143 // More complicated than you might expect because the else branch
3144 // might be `if let`.
3145 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3146 let else_opt = else_opt.as_ref().map(|els| {
3148 ExprKind::IfLet(..) => {
3149 // wrap the if-let expr in a block
3150 let span = els.span;
3151 let els = P(self.lower_expr(els));
3152 let LoweredNodeId { node_id, hir_id } = self.next_id();
3153 let blk = P(hir::Block {
3158 rules: hir::DefaultBlock,
3160 targeted_by_break: false,
3161 recovered: blk.recovered,
3163 P(self.expr_block(blk, ThinVec::new()))
3165 _ => P(self.lower_expr(els)),
3169 let then_blk = self.lower_block(blk, false);
3170 let then_expr = self.expr_block(then_blk, ThinVec::new());
3172 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3174 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3176 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3177 this.lower_block(body, false),
3178 this.lower_label(opt_label),
3181 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3183 this.lower_block(body, false),
3184 this.lower_label(opt_label),
3185 hir::LoopSource::Loop,
3188 ExprKind::Catch(ref body) => {
3189 self.with_catch_scope(body.id, |this| {
3191 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3192 let mut block = this.lower_block(body, true).into_inner();
3193 let tail = block.expr.take().map_or_else(
3195 let LoweredNodeId { node_id, hir_id } = this.next_id();
3196 let span = this.sess.codemap().end_point(unstable_span);
3200 node: hir::ExprTup(hir_vec![]),
3201 attrs: ThinVec::new(),
3205 |x: P<hir::Expr>| x.into_inner(),
3207 block.expr = Some(this.wrap_in_try_constructor(
3208 "from_ok", tail, unstable_span));
3209 hir::ExprBlock(P(block), None)
3212 ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3213 P(self.lower_expr(expr)),
3214 arms.iter().map(|x| self.lower_arm(x)).collect(),
3215 hir::MatchSource::Normal,
3217 ExprKind::Closure(capture_clause, movability, ref decl, ref body, fn_decl_span) => {
3218 self.with_new_scopes(|this| {
3219 let mut is_generator = false;
3220 let body_id = this.lower_body(Some(decl), |this| {
3221 let e = this.lower_expr(body);
3222 is_generator = this.is_generator;
3225 let generator_option = if is_generator {
3226 if !decl.inputs.is_empty() {
3231 "generators cannot have explicit arguments"
3233 this.sess.abort_if_errors();
3235 Some(match movability {
3236 Movability::Movable => hir::GeneratorMovability::Movable,
3237 Movability::Static => hir::GeneratorMovability::Static,
3240 if movability == Movability::Static {
3245 "closures cannot be static"
3251 this.lower_capture_clause(capture_clause),
3252 this.lower_fn_decl(decl, None, false),
3259 ExprKind::Block(ref blk, opt_label) => {
3260 hir::ExprBlock(self.lower_block(blk,
3261 opt_label.is_some()),
3262 self.lower_label(opt_label))
3264 ExprKind::Assign(ref el, ref er) => {
3265 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3267 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3268 self.lower_binop(op),
3269 P(self.lower_expr(el)),
3270 P(self.lower_expr(er)),
3272 ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3273 ExprKind::Index(ref el, ref er) => {
3274 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3276 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3277 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3278 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3279 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3280 let id = self.next_id();
3281 let e1 = self.lower_expr(e1);
3282 let e2 = self.lower_expr(e2);
3283 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], false));
3284 let ty = self.ty_path(id, span, hir::QPath::Resolved(None, ty_path));
3285 let new_seg = P(hir::PathSegment::from_name(Symbol::intern("new")));
3286 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3287 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3288 hir::ExprCall(new, hir_vec![e1, e2])
3290 ExprKind::Range(ref e1, ref e2, lims) => {
3291 use syntax::ast::RangeLimits::*;
3293 let path = match (e1, e2, lims) {
3294 (&None, &None, HalfOpen) => "RangeFull",
3295 (&Some(..), &None, HalfOpen) => "RangeFrom",
3296 (&None, &Some(..), HalfOpen) => "RangeTo",
3297 (&Some(..), &Some(..), HalfOpen) => "Range",
3298 (&None, &Some(..), Closed) => "RangeToInclusive",
3299 (&Some(..), &Some(..), Closed) => unreachable!(),
3300 (_, &None, Closed) => self.diagnostic()
3301 .span_fatal(e.span, "inclusive range with no end")
3305 let fields = e1.iter()
3306 .map(|e| ("start", e))
3307 .chain(e2.iter().map(|e| ("end", e)))
3309 let expr = P(self.lower_expr(&e));
3311 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3312 let ident = Ident::new(Symbol::intern(s), unstable_span);
3313 self.field(ident, expr, unstable_span)
3315 .collect::<P<[hir::Field]>>();
3317 let is_unit = fields.is_empty();
3319 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3320 let struct_path = iter::once("ops")
3321 .chain(iter::once(path))
3322 .collect::<Vec<_>>();
3323 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
3324 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3326 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3332 hir::ExprPath(struct_path)
3334 hir::ExprStruct(struct_path, fields, None)
3336 span: unstable_span,
3337 attrs: e.attrs.clone(),
3340 ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3344 ParamMode::Optional,
3345 ImplTraitContext::Disallowed,
3347 ExprKind::Break(opt_label, ref opt_expr) => {
3348 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3351 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3354 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3358 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3361 ExprKind::Continue(opt_label) => {
3362 hir::ExprAgain(if self.is_in_loop_condition && opt_label.is_none() {
3365 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3368 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3371 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3372 ExprKind::InlineAsm(ref asm) => {
3373 let hir_asm = hir::InlineAsm {
3374 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3375 outputs: asm.outputs
3377 .map(|out| hir::InlineAsmOutput {
3378 constraint: out.constraint.clone(),
3380 is_indirect: out.is_indirect,
3383 asm: asm.asm.clone(),
3384 asm_str_style: asm.asm_str_style,
3385 clobbers: asm.clobbers.clone().into(),
3386 volatile: asm.volatile,
3387 alignstack: asm.alignstack,
3388 dialect: asm.dialect,
3391 let outputs = asm.outputs
3393 .map(|out| self.lower_expr(&out.expr))
3395 let inputs = asm.inputs
3397 .map(|&(_, ref input)| self.lower_expr(input))
3399 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3401 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3406 ParamMode::Optional,
3407 ImplTraitContext::Disallowed,
3409 fields.iter().map(|x| self.lower_field(x)).collect(),
3410 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3412 ExprKind::Paren(ref ex) => {
3413 let mut ex = self.lower_expr(ex);
3414 // include parens in span, but only if it is a super-span.
3415 if e.span.contains(ex.span) {
3418 // merge attributes into the inner expression.
3419 let mut attrs = e.attrs.clone();
3420 attrs.extend::<Vec<_>>(ex.attrs.into());
3425 ExprKind::Yield(ref opt_expr) => {
3426 self.is_generator = true;
3429 .map(|x| self.lower_expr(x))
3430 .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3431 hir::ExprYield(P(expr))
3434 // Desugar ExprIfLet
3435 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3436 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3439 // match <sub_expr> {
3441 // _ => [<else_opt> | ()]
3444 let mut arms = vec![];
3446 // `<pat> => <body>`
3448 let body = self.lower_block(body, false);
3449 let body_expr = P(self.expr_block(body, ThinVec::new()));
3450 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3451 arms.push(self.arm(pats, body_expr));
3454 // _ => [<else_opt>|()]
3456 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3457 let wildcard_pattern = self.pat_wild(e.span);
3458 let body = if let Some(else_expr) = wildcard_arm {
3459 P(self.lower_expr(else_expr))
3461 self.expr_tuple(e.span, hir_vec![])
3463 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3466 let contains_else_clause = else_opt.is_some();
3468 let sub_expr = P(self.lower_expr(sub_expr));
3473 hir::MatchSource::IfLetDesugar {
3474 contains_else_clause,
3479 // Desugar ExprWhileLet
3480 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3481 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3484 // [opt_ident]: loop {
3485 // match <sub_expr> {
3491 // Note that the block AND the condition are evaluated in the loop scope.
3492 // This is done to allow `break` from inside the condition of the loop.
3493 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3495 this.lower_block(body, false),
3496 this.expr_break(e.span, ThinVec::new()),
3497 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3501 // `<pat> => <body>`
3503 let body_expr = P(self.expr_block(body, ThinVec::new()));
3504 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3505 self.arm(pats, body_expr)
3510 let pat_under = self.pat_wild(e.span);
3511 self.arm(hir_vec![pat_under], break_expr)
3514 // `match <sub_expr> { ... }`
3515 let arms = hir_vec![pat_arm, break_arm];
3516 let match_expr = self.expr(
3518 hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3522 // `[opt_ident]: loop { ... }`
3523 let loop_block = P(self.block_expr(P(match_expr)));
3524 let loop_expr = hir::ExprLoop(
3526 self.lower_label(opt_label),
3527 hir::LoopSource::WhileLet,
3529 // add attributes to the outer returned expr node
3533 // Desugar ExprForLoop
3534 // From: `[opt_ident]: for <pat> in <head> <body>`
3535 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3539 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3541 // [opt_ident]: loop {
3543 // match ::std::iter::Iterator::next(&mut iter) {
3544 // ::std::option::Option::Some(val) => __next = val,
3545 // ::std::option::Option::None => break
3547 // let <pat> = __next;
3548 // StmtExpr(<body>);
3556 let head = self.lower_expr(head);
3557 let head_sp = head.span;
3559 let iter = self.str_to_ident("iter");
3561 let next_ident = self.str_to_ident("__next");
3562 let next_pat = self.pat_ident_binding_mode(
3565 hir::BindingAnnotation::Mutable,
3568 // `::std::option::Option::Some(val) => next = val`
3570 let val_ident = self.str_to_ident("val");
3571 let val_pat = self.pat_ident(pat.span, val_ident);
3572 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
3573 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
3574 let assign = P(self.expr(
3576 hir::ExprAssign(next_expr, val_expr),
3579 let some_pat = self.pat_some(pat.span, val_pat);
3580 self.arm(hir_vec![some_pat], assign)
3583 // `::std::option::Option::None => break`
3586 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
3587 let pat = self.pat_none(e.span);
3588 self.arm(hir_vec![pat], break_expr)
3593 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
3595 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
3597 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
3598 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
3599 let next_path = &["iter", "Iterator", "next"];
3600 let next_path = P(self.expr_std_path(head_sp, next_path, ThinVec::new()));
3601 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
3602 let arms = hir_vec![pat_arm, break_arm];
3606 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
3610 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
3612 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
3616 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
3618 // `let <pat> = __next`
3619 let pat = self.lower_pat(pat);
3620 let pat_let = self.stmt_let_pat(
3624 hir::LocalSource::ForLoopDesugar,
3627 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
3628 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
3629 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
3631 let loop_block = P(self.block_all(
3633 hir_vec![next_let, match_stmt, pat_let, body_stmt],
3637 // `[opt_ident]: loop { ... }`
3638 let loop_expr = hir::ExprLoop(
3640 self.lower_label(opt_label),
3641 hir::LoopSource::ForLoop,
3643 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3644 let loop_expr = P(hir::Expr {
3649 attrs: ThinVec::new(),
3652 // `mut iter => { ... }`
3653 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
3655 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
3656 let into_iter_expr = {
3657 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
3658 let into_iter = P(self.expr_std_path(head_sp, into_iter_path, ThinVec::new()));
3659 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
3662 let match_expr = P(self.expr_match(
3666 hir::MatchSource::ForLoopDesugar,
3669 // `{ let _result = ...; _result }`
3670 // underscore prevents an unused_variables lint if the head diverges
3671 let result_ident = self.str_to_ident("_result");
3672 let (let_stmt, let_stmt_binding) =
3673 self.stmt_let(e.span, false, result_ident, match_expr);
3675 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
3676 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
3677 // add the attributes to the outer returned expr node
3678 return self.expr_block(block, e.attrs.clone());
3681 // Desugar ExprKind::Try
3683 ExprKind::Try(ref sub_expr) => {
3686 // match Try::into_result(<expr>) {
3687 // Ok(val) => #[allow(unreachable_code)] val,
3688 // Err(err) => #[allow(unreachable_code)]
3689 // // If there is an enclosing `catch {...}`
3690 // break 'catch_target Try::from_error(From::from(err)),
3692 // return Try::from_error(From::from(err)),
3696 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
3698 // Try::into_result(<expr>)
3701 let sub_expr = self.lower_expr(sub_expr);
3703 let path = &["ops", "Try", "into_result"];
3704 let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
3705 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
3708 // #[allow(unreachable_code)]
3710 // allow(unreachable_code)
3712 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
3713 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
3714 let uc_nested = attr::mk_nested_word_item(uc_ident);
3715 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
3717 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
3719 let attrs = vec![attr];
3721 // Ok(val) => #[allow(unreachable_code)] val,
3723 let val_ident = self.str_to_ident("val");
3724 let val_pat = self.pat_ident(e.span, val_ident);
3725 let val_expr = P(self.expr_ident_with_attrs(
3729 ThinVec::from(attrs.clone()),
3731 let ok_pat = self.pat_ok(e.span, val_pat);
3733 self.arm(hir_vec![ok_pat], val_expr)
3736 // Err(err) => #[allow(unreachable_code)]
3737 // return Try::from_error(From::from(err)),
3739 let err_ident = self.str_to_ident("err");
3740 let err_local = self.pat_ident(e.span, err_ident);
3742 let path = &["convert", "From", "from"];
3743 let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
3744 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
3746 self.expr_call(e.span, from, hir_vec![err_expr])
3749 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
3750 let thin_attrs = ThinVec::from(attrs);
3751 let catch_scope = self.catch_scopes.last().map(|x| *x);
3752 let ret_expr = if let Some(catch_node) = catch_scope {
3758 target_id: Ok(catch_node),
3760 Some(from_err_expr),
3765 P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
3768 let err_pat = self.pat_err(e.span, err_local);
3769 self.arm(hir_vec![err_pat], ret_expr)
3774 hir_vec![err_arm, ok_arm],
3775 hir::MatchSource::TryDesugar,
3779 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
3782 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3789 attrs: e.attrs.clone(),
3793 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
3794 SmallVector::one(match s.node {
3795 StmtKind::Local(ref l) => Spanned {
3796 node: hir::StmtDecl(
3798 node: hir::DeclLocal(self.lower_local(l)),
3801 self.lower_node_id(s.id).node_id,
3805 StmtKind::Item(ref it) => {
3806 // Can only use the ID once.
3807 let mut id = Some(s.id);
3808 return self.lower_item_id(it)
3810 .map(|item_id| Spanned {
3811 node: hir::StmtDecl(
3813 node: hir::DeclItem(item_id),
3817 .map(|id| self.lower_node_id(id).node_id)
3818 .unwrap_or_else(|| self.next_id().node_id),
3824 StmtKind::Expr(ref e) => Spanned {
3825 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3828 StmtKind::Semi(ref e) => Spanned {
3829 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3832 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
3836 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
3838 CaptureBy::Value => hir::CaptureByValue,
3839 CaptureBy::Ref => hir::CaptureByRef,
3843 /// If an `explicit_owner` is given, this method allocates the `HirId` in
3844 /// the address space of that item instead of the item currently being
3845 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
3846 /// lower a `Visibility` value although we haven't lowered the owning
3847 /// `ImplItem` in question yet.
3848 fn lower_visibility(
3851 explicit_owner: Option<NodeId>,
3852 ) -> hir::Visibility {
3854 VisibilityKind::Public => hir::Public,
3855 VisibilityKind::Crate(sugar) => hir::Visibility::Crate(sugar),
3856 VisibilityKind::Restricted { ref path, id, .. } => hir::Visibility::Restricted {
3857 path: P(self.lower_path(id, path, ParamMode::Explicit)),
3858 id: if let Some(owner) = explicit_owner {
3859 self.lower_node_id_with_owner(id, owner).node_id
3861 self.lower_node_id(id).node_id
3864 VisibilityKind::Inherited => hir::Inherited,
3868 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
3870 Defaultness::Default => hir::Defaultness::Default {
3871 has_value: has_value,
3873 Defaultness::Final => {
3875 hir::Defaultness::Final
3880 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3882 BlockCheckMode::Default => hir::DefaultBlock,
3883 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3887 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3889 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
3890 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
3891 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
3892 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
3896 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3898 CompilerGenerated => hir::CompilerGenerated,
3899 UserProvided => hir::UserProvided,
3903 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
3905 ImplPolarity::Positive => hir::ImplPolarity::Positive,
3906 ImplPolarity::Negative => hir::ImplPolarity::Negative,
3910 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3912 TraitBoundModifier::None => hir::TraitBoundModifier::None,
3913 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3917 // Helper methods for building HIR.
3919 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
3928 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
3930 id: self.next_id().node_id,
3934 is_shorthand: false,
3938 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
3939 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
3940 P(self.expr(span, expr_break, attrs))
3947 args: hir::HirVec<hir::Expr>,
3949 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
3952 fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
3953 self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
3956 fn expr_ident_with_attrs(
3961 attrs: ThinVec<Attribute>,
3963 let expr_path = hir::ExprPath(hir::QPath::Resolved(
3967 def: Def::Local(binding),
3968 segments: hir_vec![hir::PathSegment::from_name(id)],
3972 self.expr(span, expr_path, attrs)
3975 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
3976 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
3982 components: &[&str],
3983 attrs: ThinVec<Attribute>,
3985 let path = self.std_path(span, components, true);
3988 hir::ExprPath(hir::QPath::Resolved(None, P(path))),
3997 arms: hir::HirVec<hir::Arm>,
3998 source: hir::MatchSource,
4000 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
4003 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4004 self.expr(b.span, hir::ExprBlock(b, None), attrs)
4007 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4008 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
4011 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
4012 let LoweredNodeId { node_id, hir_id } = self.next_id();
4025 ex: Option<P<hir::Expr>>,
4027 source: hir::LocalSource,
4029 let LoweredNodeId { node_id, hir_id } = self.next_id();
4031 let local = P(hir::Local {
4038 attrs: ThinVec::new(),
4041 let decl = respan(sp, hir::DeclLocal(local));
4042 respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
4051 ) -> (hir::Stmt, NodeId) {
4052 let pat = if mutbl {
4053 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4055 self.pat_ident(sp, ident)
4057 let pat_id = pat.id;
4059 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4064 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4065 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4071 stmts: hir::HirVec<hir::Stmt>,
4072 expr: Option<P<hir::Expr>>,
4074 let LoweredNodeId { node_id, hir_id } = self.next_id();
4081 rules: hir::DefaultBlock,
4083 targeted_by_break: false,
4088 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4089 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4092 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4093 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4096 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4097 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4100 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4101 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4107 components: &[&str],
4108 subpats: hir::HirVec<P<hir::Pat>>,
4110 let path = self.std_path(span, components, true);
4111 let qpath = hir::QPath::Resolved(None, P(path));
4112 let pt = if subpats.is_empty() {
4113 hir::PatKind::Path(qpath)
4115 hir::PatKind::TupleStruct(qpath, subpats, None)
4120 fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
4121 self.pat_ident_binding_mode(span, name, hir::BindingAnnotation::Unannotated)
4124 fn pat_ident_binding_mode(
4128 bm: hir::BindingAnnotation,
4130 let LoweredNodeId { node_id, hir_id } = self.next_id();
4135 node: hir::PatKind::Binding(bm, node_id, Spanned { span, node: name }, None),
4140 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4141 self.pat(span, hir::PatKind::Wild)
4144 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4145 let LoweredNodeId { node_id, hir_id } = self.next_id();
4154 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4155 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4156 /// The path is also resolved according to `is_value`.
4157 fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
4159 .resolve_str_path(span, self.crate_root, components, is_value)
4162 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
4164 let node = match qpath {
4165 hir::QPath::Resolved(None, path) => {
4166 // Turn trait object paths into `TyTraitObject` instead.
4167 if let Def::Trait(_) = path.def {
4168 let principal = hir::PolyTraitRef {
4169 bound_generic_params: hir::HirVec::new(),
4170 trait_ref: hir::TraitRef {
4171 path: path.and_then(|path| path),
4177 // The original ID is taken by the `PolyTraitRef`,
4178 // so the `Ty` itself needs a different one.
4179 id = self.next_id();
4180 hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4182 hir::TyPath(hir::QPath::Resolved(None, path))
4185 _ => hir::TyPath(qpath),
4195 /// Invoked to create the lifetime argument for a type `&T`
4196 /// with no explicit lifetime.
4197 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4198 match self.anonymous_lifetime_mode {
4199 // Intercept when we are in an impl header and introduce an in-band lifetime.
4200 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4202 AnonymousLifetimeMode::CreateParameter => {
4203 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4205 id: self.next_id().node_id,
4211 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4215 /// Invoked to create the lifetime argument(s) for a path like
4216 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4217 /// sorts of cases are deprecated. This may therefore report a warning or an
4218 /// error, depending on the mode.
4219 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4220 match self.anonymous_lifetime_mode {
4221 // NB. We intentionally ignore the create-parameter mode here
4222 // and instead "pass through" to resolve-lifetimes, which will then
4223 // report an error. This is because we don't want to support
4224 // impl elision for deprecated forms like
4226 // impl Foo for std::cell::Ref<u32> // note lack of '_
4227 AnonymousLifetimeMode::CreateParameter => {}
4229 // This is the normal case.
4230 AnonymousLifetimeMode::PassThrough => {}
4234 .map(|_| self.new_implicit_lifetime(span))
4238 /// Invoked to create the lifetime argument(s) for an elided trait object
4239 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4240 /// when the bound is written, even if it is written with `'_` like in
4241 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4242 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4243 match self.anonymous_lifetime_mode {
4244 // NB. We intentionally ignore the create-parameter mode here.
4245 // and instead "pass through" to resolve-lifetimes, which will apply
4246 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4247 // do not act like other elided lifetimes. In other words, given this:
4249 // impl Foo for Box<dyn Debug>
4251 // we do not introduce a fresh `'_` to serve as the bound, but instead
4252 // ultimately translate to the equivalent of:
4254 // impl Foo for Box<dyn Debug + 'static>
4256 // `resolve_lifetime` has the code to make that happen.
4257 AnonymousLifetimeMode::CreateParameter => {}
4259 // This is the normal case.
4260 AnonymousLifetimeMode::PassThrough => {}
4263 self.new_implicit_lifetime(span)
4266 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4268 id: self.next_id().node_id,
4270 name: hir::LifetimeName::Implicit,
4274 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4275 self.sess.buffer_lint_with_diagnostic(
4276 builtin::BARE_TRAIT_OBJECTS,
4279 "trait objects without an explicit `dyn` are deprecated",
4280 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4284 fn wrap_in_try_constructor(
4286 method: &'static str,
4288 unstable_span: Span,
4290 let path = &["ops", "Try", method];
4291 let from_err = P(self.expr_std_path(unstable_span, path,
4293 P(self.expr_call(e.span, from_err, hir_vec![e]))
4297 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4298 // Sorting by span ensures that we get things in order within a
4299 // file, and also puts the files in a sensible order.
4300 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4301 body_ids.sort_by_key(|b| bodies[b].value.span);