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};
49 use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES};
50 use middle::cstore::CrateStore;
51 use rustc_data_structures::indexed_vec::IndexVec;
53 use util::common::FN_OUTPUT_NAME;
54 use util::nodemap::{DefIdMap, FxHashMap, NodeMap};
56 use std::collections::{BTreeMap, HashSet};
63 use syntax::ext::hygiene::{Mark, SyntaxContext};
64 use syntax::print::pprust;
66 use syntax::codemap::{self, respan, CompilerDesugaringKind, Spanned};
67 use syntax::std_inject;
68 use syntax::symbol::{keywords, Symbol};
69 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
70 use syntax::parse::token::Token;
71 use syntax::util::small_vector::SmallVector;
72 use syntax::visit::{self, Visitor};
75 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
77 pub struct LoweringContext<'a> {
78 crate_root: Option<&'static str>,
80 // Use to assign ids to hir nodes that do not directly correspond to an ast node
83 cstore: &'a CrateStore,
85 resolver: &'a mut Resolver,
86 name_map: FxHashMap<Ident, Name>,
88 /// The items being lowered are collected here.
89 items: BTreeMap<NodeId, hir::Item>,
91 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
92 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
93 bodies: BTreeMap<hir::BodyId, hir::Body>,
94 exported_macros: Vec<hir::MacroDef>,
96 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
97 trait_auto_impl: BTreeMap<DefId, NodeId>,
101 catch_scopes: Vec<NodeId>,
102 loop_scopes: Vec<NodeId>,
103 is_in_loop_condition: bool,
104 is_in_trait_impl: bool,
106 /// What to do when we encounter either an "anonymous lifetime
107 /// reference". The term "anonymous" is meant to encompass both
108 /// `'_` lifetimes as well as fully elided cases where nothing is
109 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
110 anonymous_lifetime_mode: AnonymousLifetimeMode,
112 // This is a list of in-band type definitions being generated by
113 // Argument-position `impl Trait`.
114 // When traversing a signature such as `fn foo(x: impl Trait)`,
115 // we record `impl Trait` as a new type parameter, then later
116 // add it on to `foo`s generics.
117 in_band_ty_params: Vec<hir::TyParam>,
119 // Used to create lifetime definitions from in-band lifetime usages.
120 // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
121 // When a named lifetime is encountered in a function or impl header and
122 // has not been defined
123 // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
124 // to this list. The results of this list are then added to the list of
125 // lifetime definitions in the corresponding impl or function generics.
126 lifetimes_to_define: Vec<(Span, hir::LifetimeName)>,
128 // Whether or not in-band lifetimes are being collected. This is used to
129 // indicate whether or not we're in a place where new lifetimes will result
130 // in in-band lifetime definitions, such a function or an impl header.
131 // This will always be false unless the `in_band_lifetimes` feature is
133 is_collecting_in_band_lifetimes: bool,
135 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
136 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
137 // against this list to see if it is already in-scope, or if a definition
138 // needs to be created for it.
139 in_scope_lifetimes: Vec<Name>,
141 type_def_lifetime_params: DefIdMap<usize>,
143 current_hir_id_owner: Vec<(DefIndex, u32)>,
144 item_local_id_counters: NodeMap<u32>,
145 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
149 /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
150 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
152 /// Obtain the resolution for a node id
153 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
155 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
156 /// This should only return `None` during testing.
157 fn definitions(&mut self) -> &mut Definitions;
159 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
160 /// it based on `is_value`.
164 crate_root: Option<&str>,
170 #[derive(Clone, Copy, Debug)]
171 enum ImplTraitContext {
172 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
173 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
174 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
176 /// We store a DefId here so we can look up necessary information later
179 /// Treat `impl Trait` as shorthand for a new universal existential parameter.
180 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
181 /// equivalent to a fresh existential parameter like `abstract type T; fn foo() -> T`.
184 /// `impl Trait` is not accepted in this position.
191 dep_graph: &DepGraph,
193 resolver: &mut Resolver,
195 // We're constructing the HIR here; we don't care what we will
196 // read, since we haven't even constructed the *input* to
198 dep_graph.assert_ignored();
201 crate_root: std_inject::injected_crate_name(),
205 name_map: FxHashMap(),
206 items: BTreeMap::new(),
207 trait_items: BTreeMap::new(),
208 impl_items: BTreeMap::new(),
209 bodies: BTreeMap::new(),
210 trait_impls: BTreeMap::new(),
211 trait_auto_impl: BTreeMap::new(),
212 exported_macros: Vec::new(),
213 catch_scopes: Vec::new(),
214 loop_scopes: Vec::new(),
215 is_in_loop_condition: false,
216 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
217 type_def_lifetime_params: DefIdMap(),
218 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
219 item_local_id_counters: NodeMap(),
220 node_id_to_hir_id: IndexVec::new(),
222 is_in_trait_impl: false,
223 in_band_ty_params: Vec::new(),
224 lifetimes_to_define: Vec::new(),
225 is_collecting_in_band_lifetimes: false,
226 in_scope_lifetimes: Vec::new(),
230 #[derive(Copy, Clone, PartialEq, Eq)]
232 /// Any path in a type context.
234 /// The `module::Type` in `module::Type::method` in an expression.
238 struct LoweredNodeId {
243 enum ParenthesizedGenericArgs {
249 /// What to do when we encounter an **anonymous** lifetime
250 /// reference. Anonymous lifetime references come in two flavors. You
251 /// have implicit, or fully elided, references to lifetimes, like the
252 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
253 /// or `Ref<'_, T>`. These often behave the same, but not always:
255 /// - certain usages of implicit references are deprecated, like
256 /// `Ref<T>`, and we sometimes just give hard errors in those cases
258 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
259 /// the same as `Box<dyn Foo + '_>`.
261 /// We describe the effects of the various modes in terms of three cases:
263 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
264 /// of a `&` (e.g., the missing lifetime in something like `&T`)
265 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
266 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
267 /// elided bounds follow special rules. Note that this only covers
268 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
269 /// '_>` is a case of "modern" elision.
270 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
271 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
272 /// non-deprecated equivalent.
274 /// Currently, the handling of lifetime elision is somewhat spread out
275 /// between HIR lowering and -- as described below -- the
276 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
277 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
278 /// everything into HIR lowering.
279 #[derive(Copy, Clone)]
280 enum AnonymousLifetimeMode {
281 /// For **Modern** cases, create a new anonymous region parameter
282 /// and reference that.
284 /// For **Dyn Bound** cases, pass responsibility to
285 /// `resolve_lifetime` code.
287 /// For **Deprecated** cases, report an error.
290 /// Pass responsibility to `resolve_lifetime` code for all cases.
294 impl<'a> LoweringContext<'a> {
295 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
296 /// Full-crate AST visitor that inserts into a fresh
297 /// `LoweringContext` any information that may be
298 /// needed from arbitrary locations in the crate.
299 /// E.g. The number of lifetime generic parameters
300 /// declared for every type and trait definition.
301 struct MiscCollector<'lcx, 'interner: 'lcx> {
302 lctx: &'lcx mut LoweringContext<'interner>,
305 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
306 fn visit_item(&mut self, item: &'lcx Item) {
307 self.lctx.allocate_hir_id_counter(item.id, item);
310 ItemKind::Struct(_, ref generics)
311 | ItemKind::Union(_, ref generics)
312 | ItemKind::Enum(_, ref generics)
313 | ItemKind::Ty(_, ref generics)
314 | ItemKind::Trait(_, _, ref generics, ..) => {
315 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
319 .filter(|param| param.is_lifetime_param())
321 self.lctx.type_def_lifetime_params.insert(def_id, count);
325 visit::walk_item(self, item);
328 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
329 self.lctx.allocate_hir_id_counter(item.id, item);
330 visit::walk_trait_item(self, item);
333 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
334 self.lctx.allocate_hir_id_counter(item.id, item);
335 visit::walk_impl_item(self, item);
339 struct ItemLowerer<'lcx, 'interner: 'lcx> {
340 lctx: &'lcx mut LoweringContext<'interner>,
343 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
344 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
346 F: FnOnce(&mut Self),
348 let old = self.lctx.is_in_trait_impl;
349 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
355 self.lctx.is_in_trait_impl = old;
359 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
360 fn visit_item(&mut self, item: &'lcx Item) {
361 let mut item_lowered = true;
362 self.lctx.with_hir_id_owner(item.id, |lctx| {
363 if let Some(hir_item) = lctx.lower_item(item) {
364 lctx.items.insert(item.id, hir_item);
366 item_lowered = false;
371 let item_lifetimes = match self.lctx.items.get(&item.id).unwrap().node {
372 hir::Item_::ItemImpl(_, _, _, ref generics, ..)
373 | hir::Item_::ItemTrait(_, _, ref generics, ..) => {
374 generics.lifetimes().cloned().collect::<Vec<_>>()
380 .with_parent_impl_lifetime_defs(&item_lifetimes, |this| {
381 let this = &mut ItemLowerer { lctx: this };
382 if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
383 this.with_trait_impl_ref(opt_trait_ref, |this| {
384 visit::walk_item(this, item)
387 visit::walk_item(this, item);
393 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
394 self.lctx.with_hir_id_owner(item.id, |lctx| {
395 let id = hir::TraitItemId { node_id: item.id };
396 let hir_item = lctx.lower_trait_item(item);
397 lctx.trait_items.insert(id, hir_item);
400 visit::walk_trait_item(self, item);
403 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
404 self.lctx.with_hir_id_owner(item.id, |lctx| {
405 let id = hir::ImplItemId { node_id: item.id };
406 let hir_item = lctx.lower_impl_item(item);
407 lctx.impl_items.insert(id, hir_item);
409 visit::walk_impl_item(self, item);
413 self.lower_node_id(CRATE_NODE_ID);
414 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
416 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
417 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
419 let module = self.lower_mod(&c.module);
420 let attrs = self.lower_attrs(&c.attrs);
421 let body_ids = body_ids(&self.bodies);
425 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
431 exported_macros: hir::HirVec::from(self.exported_macros),
433 trait_items: self.trait_items,
434 impl_items: self.impl_items,
437 trait_impls: self.trait_impls,
438 trait_auto_impl: self.trait_auto_impl,
442 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) {
443 if self.item_local_id_counters.insert(owner, 0).is_some() {
445 "Tried to allocate item_local_id_counter for {:?} twice",
449 // Always allocate the first HirId for the owner itself
450 self.lower_node_id_with_owner(owner, owner);
453 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
455 F: FnOnce(&mut Self) -> hir::HirId,
457 if ast_node_id == DUMMY_NODE_ID {
458 return LoweredNodeId {
459 node_id: DUMMY_NODE_ID,
460 hir_id: hir::DUMMY_HIR_ID,
464 let min_size = ast_node_id.as_usize() + 1;
466 if min_size > self.node_id_to_hir_id.len() {
467 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
470 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
472 if existing_hir_id == hir::DUMMY_HIR_ID {
473 // Generate a new HirId
474 let hir_id = alloc_hir_id(self);
475 self.node_id_to_hir_id[ast_node_id] = hir_id;
477 node_id: ast_node_id,
482 node_id: ast_node_id,
483 hir_id: existing_hir_id,
488 fn with_hir_id_owner<F>(&mut self, owner: NodeId, f: F)
490 F: FnOnce(&mut Self),
492 let counter = self.item_local_id_counters
493 .insert(owner, HIR_ID_COUNTER_LOCKED)
495 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
496 self.current_hir_id_owner.push((def_index, counter));
498 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
500 debug_assert!(def_index == new_def_index);
501 debug_assert!(new_counter >= counter);
503 let prev = self.item_local_id_counters
504 .insert(owner, new_counter)
506 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
509 /// This method allocates a new HirId for the given NodeId and stores it in
510 /// the LoweringContext's NodeId => HirId map.
511 /// Take care not to call this method if the resulting HirId is then not
512 /// actually used in the HIR, as that would trigger an assertion in the
513 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
514 /// properly. Calling the method twice with the same NodeId is fine though.
515 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
516 self.lower_node_id_generic(ast_node_id, |this| {
517 let &mut (def_index, ref mut local_id_counter) =
518 this.current_hir_id_owner.last_mut().unwrap();
519 let local_id = *local_id_counter;
520 *local_id_counter += 1;
523 local_id: hir::ItemLocalId(local_id),
528 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
529 self.lower_node_id_generic(ast_node_id, |this| {
530 let local_id_counter = this.item_local_id_counters.get_mut(&owner).unwrap();
531 let local_id = *local_id_counter;
533 // We want to be sure not to modify the counter in the map while it
534 // is also on the stack. Otherwise we'll get lost updates when writing
535 // back from the stack to the map.
536 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
538 *local_id_counter += 1;
539 let def_index = this.resolver.definitions().opt_def_index(owner).unwrap();
543 local_id: hir::ItemLocalId(local_id),
548 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
549 let body = hir::Body {
550 arguments: decl.map_or(hir_vec![], |decl| {
551 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
553 is_generator: self.is_generator,
557 self.bodies.insert(id, body);
561 fn next_id(&mut self) -> LoweredNodeId {
562 self.lower_node_id(self.sess.next_node_id())
565 fn expect_full_def(&mut self, id: NodeId) -> Def {
566 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
567 if pr.unresolved_segments() != 0 {
568 bug!("path not fully resolved: {:?}", pr);
574 fn diagnostic(&self) -> &errors::Handler {
575 self.sess.diagnostic()
578 fn str_to_ident(&self, s: &'static str) -> Name {
582 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
583 let mark = Mark::fresh(Mark::root());
584 mark.set_expn_info(codemap::ExpnInfo {
586 callee: codemap::NameAndSpan {
587 format: codemap::CompilerDesugaring(reason),
589 allow_internal_unstable: true,
590 allow_internal_unsafe: false,
591 edition: codemap::hygiene::default_edition(),
594 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
597 fn with_anonymous_lifetime_mode<R>(
599 anonymous_lifetime_mode: AnonymousLifetimeMode,
600 op: impl FnOnce(&mut Self) -> R,
602 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
603 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
604 let result = op(self);
605 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
609 /// Creates a new hir::GenericParam for every new lifetime and
610 /// type parameter encountered while evaluating `f`. Definitions
611 /// are created with the parent provided. If no `parent_id` is
612 /// provided, no definitions will be returned.
614 /// Presuming that in-band lifetimes are enabled, then
615 /// `self.anonymous_lifetime_mode` will be updated to match the
616 /// argument while `f` is running (and restored afterwards).
617 fn collect_in_band_defs<T, F>(
620 anonymous_lifetime_mode: AnonymousLifetimeMode,
622 ) -> (Vec<hir::GenericParam>, T)
624 F: FnOnce(&mut LoweringContext) -> T,
626 assert!(!self.is_collecting_in_band_lifetimes);
627 assert!(self.lifetimes_to_define.is_empty());
628 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
630 self.is_collecting_in_band_lifetimes = self.sess.features_untracked().in_band_lifetimes;
631 if self.is_collecting_in_band_lifetimes {
632 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
635 assert!(self.in_band_ty_params.is_empty());
638 self.is_collecting_in_band_lifetimes = false;
639 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
641 let in_band_ty_params = self.in_band_ty_params.split_off(0);
642 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
644 let params = lifetimes_to_define
646 .map(|(span, hir_name)| {
647 let def_node_id = self.next_id().node_id;
649 // Get the name we'll use to make the def-path. Note
650 // that collisions are ok here and this shouldn't
651 // really show up for end-user.
652 let str_name = match hir_name {
653 hir::LifetimeName::Name(n) => n.as_str(),
654 hir::LifetimeName::Fresh(_) => keywords::UnderscoreLifetime.name().as_str(),
655 hir::LifetimeName::Implicit
656 | hir::LifetimeName::Underscore
657 | hir::LifetimeName::Static => {
658 span_bug!(span, "unexpected in-band lifetime name: {:?}", hir_name)
662 // Add a definition for the in-band lifetime def
663 self.resolver.definitions().create_def_with_parent(
666 DefPathData::LifetimeDef(str_name.as_interned_str()),
667 DefIndexAddressSpace::High,
672 hir::GenericParam::Lifetime(hir::LifetimeDef {
673 lifetime: hir::Lifetime {
678 bounds: Vec::new().into(),
679 pure_wrt_drop: false,
686 .map(|tp| hir::GenericParam::Type(tp)),
693 /// When there is a reference to some lifetime `'a`, and in-band
694 /// lifetimes are enabled, then we want to push that lifetime into
695 /// the vector of names to define later. In that case, it will get
696 /// added to the appropriate generics.
697 fn maybe_collect_in_band_lifetime(&mut self, span: Span, name: Name) {
698 if !self.is_collecting_in_band_lifetimes {
702 if self.in_scope_lifetimes.contains(&name) {
706 let hir_name = hir::LifetimeName::Name(name);
708 if self.lifetimes_to_define
710 .any(|(_, lt_name)| *lt_name == hir_name)
715 self.lifetimes_to_define.push((span, hir_name));
718 /// When we have either an elided or `'_` lifetime in an impl
719 /// header, we convert it to
720 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> hir::LifetimeName {
721 assert!(self.is_collecting_in_band_lifetimes);
722 let index = self.lifetimes_to_define.len();
723 let hir_name = hir::LifetimeName::Fresh(index);
724 self.lifetimes_to_define.push((span, hir_name));
728 // Evaluates `f` with the lifetimes in `lt_defs` in-scope.
729 // This is used to track which lifetimes have already been defined, and
730 // which are new in-band lifetimes that need to have a definition created
732 fn with_in_scope_lifetime_defs<'l, T, F>(
734 lt_defs: impl Iterator<Item = &'l LifetimeDef>,
738 F: FnOnce(&mut LoweringContext) -> T,
740 let old_len = self.in_scope_lifetimes.len();
741 let lt_def_names = lt_defs.map(|lt_def| lt_def.lifetime.ident.name);
742 self.in_scope_lifetimes.extend(lt_def_names);
746 self.in_scope_lifetimes.truncate(old_len);
750 // Same as the method above, but accepts `hir::LifetimeDef`s
751 // instead of `ast::LifetimeDef`s.
752 // This should only be used with generics that have already had their
753 // in-band lifetimes added. In practice, this means that this function is
754 // only used when lowering a child item of a trait or impl.
755 fn with_parent_impl_lifetime_defs<T, F>(&mut self, lt_defs: &[hir::LifetimeDef], f: F) -> T
757 F: FnOnce(&mut LoweringContext) -> T,
759 let old_len = self.in_scope_lifetimes.len();
760 let lt_def_names = lt_defs.iter().map(|lt_def| lt_def.lifetime.name.name());
761 self.in_scope_lifetimes.extend(lt_def_names);
765 self.in_scope_lifetimes.truncate(old_len);
769 /// Appends in-band lifetime defs and argument-position `impl
770 /// Trait` defs to the existing set of generics.
772 /// Presuming that in-band lifetimes are enabled, then
773 /// `self.anonymous_lifetime_mode` will be updated to match the
774 /// argument while `f` is running (and restored afterwards).
775 fn add_in_band_defs<F, T>(
779 anonymous_lifetime_mode: AnonymousLifetimeMode,
781 ) -> (hir::Generics, T)
783 F: FnOnce(&mut LoweringContext) -> T,
785 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
786 generics.params.iter().filter_map(|p| match p {
787 GenericParam::Lifetime(ld) => Some(ld),
791 let itctx = ImplTraitContext::Universal(parent_id);
792 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
793 (this.lower_generics(generics, itctx), f(this))
798 lowered_generics.params = lowered_generics
805 (lowered_generics, res)
808 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
810 F: FnOnce(&mut LoweringContext) -> T,
812 let len = self.catch_scopes.len();
813 self.catch_scopes.push(catch_id);
815 let result = f(self);
818 self.catch_scopes.len(),
819 "catch scopes should be added and removed in stack order"
822 self.catch_scopes.pop().unwrap();
827 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
829 F: FnOnce(&mut LoweringContext) -> hir::Expr,
831 let prev = mem::replace(&mut self.is_generator, false);
832 let result = f(self);
833 let r = self.record_body(result, decl);
834 self.is_generator = prev;
838 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
840 F: FnOnce(&mut LoweringContext) -> T,
842 // We're no longer in the base loop's condition; we're in another loop.
843 let was_in_loop_condition = self.is_in_loop_condition;
844 self.is_in_loop_condition = false;
846 let len = self.loop_scopes.len();
847 self.loop_scopes.push(loop_id);
849 let result = f(self);
852 self.loop_scopes.len(),
853 "Loop scopes should be added and removed in stack order"
856 self.loop_scopes.pop().unwrap();
858 self.is_in_loop_condition = was_in_loop_condition;
863 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
865 F: FnOnce(&mut LoweringContext) -> T,
867 let was_in_loop_condition = self.is_in_loop_condition;
868 self.is_in_loop_condition = true;
870 let result = f(self);
872 self.is_in_loop_condition = was_in_loop_condition;
877 fn with_new_scopes<T, F>(&mut self, f: F) -> T
879 F: FnOnce(&mut LoweringContext) -> T,
881 let was_in_loop_condition = self.is_in_loop_condition;
882 self.is_in_loop_condition = false;
884 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
885 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
886 let result = f(self);
887 self.catch_scopes = catch_scopes;
888 self.loop_scopes = loop_scopes;
890 self.is_in_loop_condition = was_in_loop_condition;
895 fn def_key(&mut self, id: DefId) -> DefKey {
897 self.resolver.definitions().def_key(id.index)
899 self.cstore.def_key(id)
903 fn lower_ident(&mut self, ident: Ident) -> Name {
904 let ident = ident.modern();
905 if ident.span.ctxt() == SyntaxContext::empty() {
910 .or_insert_with(|| Symbol::from_ident(ident))
913 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
914 label.map(|label| hir::Label {
915 name: label.ident.name,
916 span: label.ident.span,
920 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
922 Some((id, label)) => {
923 let target_id = if let Def::Label(loop_id) = self.expect_full_def(id) {
924 Ok(self.lower_node_id(loop_id).node_id)
926 Err(hir::LoopIdError::UnresolvedLabel)
929 label: self.lower_label(Some(label)),
934 let target_id = self.loop_scopes
936 .map(|innermost_loop_id| *innermost_loop_id)
937 .map(|id| Ok(self.lower_node_id(id).node_id))
938 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
949 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
952 .map(|a| self.lower_attr(a))
957 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
961 path: attr.path.clone(),
962 tokens: self.lower_token_stream(attr.tokens.clone()),
963 is_sugared_doc: attr.is_sugared_doc,
968 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
971 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
975 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
977 TokenTree::Token(span, token) => self.lower_token(token, span),
978 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
981 delim: delimited.delim,
982 tts: self.lower_token_stream(delimited.tts.into()).into(),
988 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
990 Token::Interpolated(_) => {}
991 other => return TokenTree::Token(span, other).into(),
994 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
995 self.lower_token_stream(tts)
998 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1000 attrs: self.lower_attrs(&arm.attrs),
1001 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1002 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1003 body: P(self.lower_expr(&arm.body)),
1007 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1009 id: self.lower_node_id(b.id).node_id,
1010 name: self.lower_ident(b.ident),
1011 ty: self.lower_ty(&b.ty, itctx),
1016 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1017 let kind = match t.node {
1018 TyKind::Infer => hir::TyInfer,
1019 TyKind::Err => hir::TyErr,
1020 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty, itctx)),
1021 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt, itctx)),
1022 TyKind::Rptr(ref region, ref mt) => {
1023 let span = t.span.shrink_to_lo();
1024 let lifetime = match *region {
1025 Some(ref lt) => self.lower_lifetime(lt),
1026 None => self.elided_ref_lifetime(span),
1028 hir::TyRptr(lifetime, self.lower_mt(mt, itctx))
1030 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1031 f.generic_params.iter().filter_map(|p| match p {
1032 GenericParam::Lifetime(ld) => Some(ld),
1036 this.with_anonymous_lifetime_mode(
1037 AnonymousLifetimeMode::PassThrough,
1039 hir::TyBareFn(P(hir::BareFnTy {
1040 generic_params: this.lower_generic_params(
1043 ImplTraitContext::Disallowed,
1045 unsafety: this.lower_unsafety(f.unsafety),
1047 decl: this.lower_fn_decl(&f.decl, None, false),
1048 arg_names: this.lower_fn_args_to_names(&f.decl),
1054 TyKind::Never => hir::TyNever,
1055 TyKind::Tup(ref tys) => {
1056 hir::TyTup(tys.iter().map(|ty| self.lower_ty(ty, itctx)).collect())
1058 TyKind::Paren(ref ty) => {
1059 return self.lower_ty(ty, itctx);
1061 TyKind::Path(ref qself, ref path) => {
1062 let id = self.lower_node_id(t.id);
1063 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1064 let ty = self.ty_path(id, t.span, qpath);
1065 if let hir::TyTraitObject(..) = ty.node {
1066 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1070 TyKind::ImplicitSelf => hir::TyPath(hir::QPath::Resolved(
1073 def: self.expect_full_def(t.id),
1074 segments: hir_vec![hir::PathSegment::from_name(keywords::SelfType.name())],
1078 TyKind::Array(ref ty, ref length) => {
1079 hir::TyArray(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1081 TyKind::Typeof(ref expr) => {
1082 hir::TyTypeof(self.lower_anon_const(expr))
1084 TyKind::TraitObject(ref bounds, kind) => {
1085 let mut lifetime_bound = None;
1088 .filter_map(|bound| match *bound {
1089 TraitTyParamBound(ref ty, TraitBoundModifier::None) => {
1090 Some(self.lower_poly_trait_ref(ty, itctx))
1092 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
1093 RegionTyParamBound(ref lifetime) => {
1094 if lifetime_bound.is_none() {
1095 lifetime_bound = Some(self.lower_lifetime(lifetime));
1101 let lifetime_bound =
1102 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1103 if kind != TraitObjectSyntax::Dyn {
1104 self.maybe_lint_bare_trait(t.span, t.id, false);
1106 hir::TyTraitObject(bounds, lifetime_bound)
1108 TyKind::ImplTrait(ref bounds) => {
1111 ImplTraitContext::Existential => {
1112 let def_index = self.resolver.definitions().opt_def_index(t.id).unwrap();
1113 let hir_bounds = self.lower_bounds(bounds, itctx);
1114 let (lifetimes, lifetime_defs) =
1115 self.lifetimes_from_impl_trait_bounds(def_index, &hir_bounds);
1117 hir::TyImplTraitExistential(
1119 generics: hir::Generics {
1120 params: lifetime_defs,
1121 where_clause: hir::WhereClause {
1122 id: self.next_id().node_id,
1123 predicates: Vec::new().into(),
1132 ImplTraitContext::Universal(def_id) => {
1133 let def_node_id = self.next_id().node_id;
1135 // Add a definition for the in-band TyParam
1136 let def_index = self.resolver.definitions().create_def_with_parent(
1139 DefPathData::ImplTrait,
1140 DefIndexAddressSpace::High,
1145 let hir_bounds = self.lower_bounds(bounds, itctx);
1146 // Set the name to `impl Bound1 + Bound2`
1147 let name = Symbol::intern(&pprust::ty_to_string(t));
1148 self.in_band_ty_params.push(hir::TyParam {
1154 pure_wrt_drop: false,
1155 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1159 hir::TyPath(hir::QPath::Resolved(
1163 def: Def::TyParam(DefId::local(def_index)),
1164 segments: hir_vec![hir::PathSegment::from_name(name)],
1168 ImplTraitContext::Disallowed => {
1173 "`impl Trait` not allowed outside of function \
1174 and inherent method return types"
1180 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1183 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1192 fn lifetimes_from_impl_trait_bounds(
1194 parent_index: DefIndex,
1195 bounds: &hir::TyParamBounds,
1196 ) -> (HirVec<hir::Lifetime>, HirVec<hir::GenericParam>) {
1197 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1198 // appear in the bounds, excluding lifetimes that are created within the bounds.
1199 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1200 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1201 context: &'r mut LoweringContext<'a>,
1203 collect_elided_lifetimes: bool,
1204 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1205 already_defined_lifetimes: HashSet<hir::LifetimeName>,
1206 output_lifetimes: Vec<hir::Lifetime>,
1207 output_lifetime_params: Vec<hir::GenericParam>,
1210 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1211 fn nested_visit_map<'this>(
1213 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1214 hir::intravisit::NestedVisitorMap::None
1217 fn visit_path_parameters(&mut self, span: Span, parameters: &'v hir::PathParameters) {
1218 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1219 if parameters.parenthesized {
1220 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1221 self.collect_elided_lifetimes = false;
1222 hir::intravisit::walk_path_parameters(self, span, parameters);
1223 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1225 hir::intravisit::walk_path_parameters(self, span, parameters);
1229 fn visit_ty(&mut self, t: &'v hir::Ty) {
1230 // Don't collect elided lifetimes used inside of `fn()` syntax
1231 if let &hir::Ty_::TyBareFn(_) = &t.node {
1232 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1233 self.collect_elided_lifetimes = false;
1235 // Record the "stack height" of `for<'a>` lifetime bindings
1236 // to be able to later fully undo their introduction.
1237 let old_len = self.currently_bound_lifetimes.len();
1238 hir::intravisit::walk_ty(self, t);
1239 self.currently_bound_lifetimes.truncate(old_len);
1241 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1243 hir::intravisit::walk_ty(self, t);
1247 fn visit_poly_trait_ref(
1249 trait_ref: &'v hir::PolyTraitRef,
1250 modifier: hir::TraitBoundModifier,
1252 // Record the "stack height" of `for<'a>` lifetime bindings
1253 // to be able to later fully undo their introduction.
1254 let old_len = self.currently_bound_lifetimes.len();
1255 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1256 self.currently_bound_lifetimes.truncate(old_len);
1259 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1260 // Record the introduction of 'a in `for<'a> ...`
1261 if let hir::GenericParam::Lifetime(ref lt_def) = *param {
1262 // Introduce lifetimes one at a time so that we can handle
1263 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1264 self.currently_bound_lifetimes.push(lt_def.lifetime.name);
1267 hir::intravisit::walk_generic_param(self, param);
1270 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1271 let name = match lifetime.name {
1272 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1273 if self.collect_elided_lifetimes {
1274 // Use `'_` for both implicit and underscore lifetimes in
1275 // `abstract type Foo<'_>: SomeTrait<'_>;`
1276 hir::LifetimeName::Underscore
1281 name @ hir::LifetimeName::Fresh(_) => name,
1282 name @ hir::LifetimeName::Name(_) => name,
1283 hir::LifetimeName::Static => return,
1286 if !self.currently_bound_lifetimes.contains(&name)
1287 && !self.already_defined_lifetimes.contains(&name)
1289 self.already_defined_lifetimes.insert(name);
1291 self.output_lifetimes.push(hir::Lifetime {
1292 id: self.context.next_id().node_id,
1293 span: lifetime.span,
1297 let def_node_id = self.context.next_id().node_id;
1298 self.context.resolver.definitions().create_def_with_parent(
1301 DefPathData::LifetimeDef(name.name().as_interned_str()),
1302 DefIndexAddressSpace::High,
1306 let def_lifetime = hir::Lifetime {
1308 span: lifetime.span,
1311 self.output_lifetime_params
1312 .push(hir::GenericParam::Lifetime(hir::LifetimeDef {
1313 lifetime: def_lifetime,
1314 bounds: Vec::new().into(),
1315 pure_wrt_drop: false,
1322 let mut lifetime_collector = ImplTraitLifetimeCollector {
1324 parent: parent_index,
1325 collect_elided_lifetimes: true,
1326 currently_bound_lifetimes: Vec::new(),
1327 already_defined_lifetimes: HashSet::new(),
1328 output_lifetimes: Vec::new(),
1329 output_lifetime_params: Vec::new(),
1332 for bound in bounds {
1333 hir::intravisit::walk_ty_param_bound(&mut lifetime_collector, &bound);
1337 lifetime_collector.output_lifetimes.into(),
1338 lifetime_collector.output_lifetime_params.into(),
1342 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1347 .map(|x| self.lower_foreign_item(x))
1352 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1359 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1361 node: hir::Variant_ {
1362 name: v.node.ident.name,
1363 attrs: self.lower_attrs(&v.node.attrs),
1364 data: self.lower_variant_data(&v.node.data),
1365 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1374 qself: &Option<QSelf>,
1376 param_mode: ParamMode,
1377 itctx: ImplTraitContext,
1379 let qself_position = qself.as_ref().map(|q| q.position);
1380 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx));
1382 let resolution = self.resolver
1384 .unwrap_or(PathResolution::new(Def::Err));
1386 let proj_start = p.segments.len() - resolution.unresolved_segments();
1387 let path = P(hir::Path {
1388 def: resolution.base_def(),
1389 segments: p.segments[..proj_start]
1392 .map(|(i, segment)| {
1393 let param_mode = match (qself_position, param_mode) {
1394 (Some(j), ParamMode::Optional) if i < j => {
1395 // This segment is part of the trait path in a
1396 // qualified path - one of `a`, `b` or `Trait`
1397 // in `<X as a::b::Trait>::T::U::method`.
1403 // Figure out if this is a type/trait segment,
1404 // which may need lifetime elision performed.
1405 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1406 krate: def_id.krate,
1407 index: this.def_key(def_id).parent.expect("missing parent"),
1409 let type_def_id = match resolution.base_def() {
1410 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1411 Some(parent_def_id(self, def_id))
1413 Def::Variant(def_id) if i + 1 == proj_start => {
1414 Some(parent_def_id(self, def_id))
1417 | Def::Union(def_id)
1419 | Def::TyAlias(def_id)
1420 | Def::Trait(def_id) if i + 1 == proj_start =>
1426 let parenthesized_generic_args = match resolution.base_def() {
1427 // `a::b::Trait(Args)`
1428 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1429 // `a::b::Trait(Args)::TraitItem`
1430 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1431 if i + 2 == proj_start =>
1433 ParenthesizedGenericArgs::Ok
1435 // Avoid duplicated errors
1436 Def::Err => ParenthesizedGenericArgs::Ok,
1442 | Def::Variant(..) if i + 1 == proj_start =>
1444 ParenthesizedGenericArgs::Err
1446 // A warning for now, for compatibility reasons
1447 _ => ParenthesizedGenericArgs::Warn,
1450 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1451 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1454 assert!(!def_id.is_local());
1456 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1457 let n = item_generics.own_counts().lifetimes;
1458 self.type_def_lifetime_params.insert(def_id, n);
1461 self.lower_path_segment(
1466 parenthesized_generic_args,
1474 // Simple case, either no projections, or only fully-qualified.
1475 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1476 if resolution.unresolved_segments() == 0 {
1477 return hir::QPath::Resolved(qself, path);
1480 // Create the innermost type that we're projecting from.
1481 let mut ty = if path.segments.is_empty() {
1482 // If the base path is empty that means there exists a
1483 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1484 qself.expect("missing QSelf for <T>::...")
1486 // Otherwise, the base path is an implicit `Self` type path,
1487 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1488 // `<I as Iterator>::Item::default`.
1489 let new_id = self.next_id();
1490 self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))
1493 // Anything after the base path are associated "extensions",
1494 // out of which all but the last one are associated types,
1495 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1496 // * base path is `std::vec::Vec<T>`
1497 // * "extensions" are `IntoIter`, `Item` and `clone`
1498 // * type nodes are:
1499 // 1. `std::vec::Vec<T>` (created above)
1500 // 2. `<std::vec::Vec<T>>::IntoIter`
1501 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1502 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1503 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1504 let segment = P(self.lower_path_segment(
1509 ParenthesizedGenericArgs::Warn,
1512 let qpath = hir::QPath::TypeRelative(ty, segment);
1514 // It's finished, return the extension of the right node type.
1515 if i == p.segments.len() - 1 {
1519 // Wrap the associated extension in another type node.
1520 let new_id = self.next_id();
1521 ty = self.ty_path(new_id, p.span, qpath);
1524 // Should've returned in the for loop above.
1527 "lower_qpath: no final extension segment in {}..{}",
1533 fn lower_path_extra(
1538 param_mode: ParamMode,
1541 def: self.expect_full_def(id),
1542 segments: p.segments
1545 self.lower_path_segment(
1550 ParenthesizedGenericArgs::Err,
1551 ImplTraitContext::Disallowed,
1554 .chain(name.map(|name| hir::PathSegment::from_name(name)))
1560 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1561 self.lower_path_extra(id, p, None, param_mode)
1564 fn lower_path_segment(
1567 segment: &PathSegment,
1568 param_mode: ParamMode,
1569 expected_lifetimes: usize,
1570 parenthesized_generic_args: ParenthesizedGenericArgs,
1571 itctx: ImplTraitContext,
1572 ) -> hir::PathSegment {
1573 let (mut parameters, infer_types) = if let Some(ref parameters) = segment.parameters {
1574 let msg = "parenthesized parameters may only be used with a trait";
1575 match **parameters {
1576 PathParameters::AngleBracketed(ref data) => {
1577 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1579 PathParameters::Parenthesized(ref data) => match parenthesized_generic_args {
1580 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1581 ParenthesizedGenericArgs::Warn => {
1582 self.sess.buffer_lint(
1583 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1588 (hir::PathParameters::none(), true)
1590 ParenthesizedGenericArgs::Err => {
1591 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1592 .span_label(data.span, "only traits may use parentheses")
1594 (hir::PathParameters::none(), true)
1599 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1602 if !parameters.parenthesized && parameters.lifetimes.is_empty() {
1603 parameters.lifetimes = self.elided_path_lifetimes(path_span, expected_lifetimes);
1606 hir::PathSegment::new(
1607 self.lower_ident(segment.ident),
1613 fn lower_angle_bracketed_parameter_data(
1615 data: &AngleBracketedParameterData,
1616 param_mode: ParamMode,
1617 itctx: ImplTraitContext,
1618 ) -> (hir::PathParameters, bool) {
1619 let &AngleBracketedParameterData {
1626 hir::PathParameters {
1627 lifetimes: self.lower_lifetimes(lifetimes),
1628 types: types.iter().map(|ty| self.lower_ty(ty, itctx)).collect(),
1631 .map(|b| self.lower_ty_binding(b, itctx))
1633 parenthesized: false,
1635 types.is_empty() && param_mode == ParamMode::Optional,
1639 fn lower_parenthesized_parameter_data(
1641 data: &ParenthesizedParameterData,
1642 ) -> (hir::PathParameters, bool) {
1643 // Switch to `PassThrough` mode for anonymous lifetimes: this
1644 // means that we permit things like `&Ref<T>`, where `Ref` has
1645 // a hidden lifetime parameter. This is needed for backwards
1646 // compatibility, even in contexts like an impl header where
1647 // we generally don't permit such things (see #51008).
1648 self.with_anonymous_lifetime_mode(
1649 AnonymousLifetimeMode::PassThrough,
1651 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1652 let &ParenthesizedParameterData {
1659 .map(|ty| this.lower_ty(ty, DISALLOWED))
1661 let mk_tup = |this: &mut Self, tys, span| {
1662 let LoweredNodeId { node_id, hir_id } = this.next_id();
1664 node: hir::TyTup(tys),
1672 hir::PathParameters {
1673 lifetimes: hir::HirVec::new(),
1674 types: hir_vec![mk_tup(this, inputs, span)],
1677 id: this.next_id().node_id,
1678 name: Symbol::intern(FN_OUTPUT_NAME),
1681 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1682 .unwrap_or_else(|| mk_tup(this, hir::HirVec::new(), span)),
1683 span: output.as_ref().map_or(span, |ty| ty.span),
1686 parenthesized: true,
1694 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1695 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1701 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1702 pat: self.lower_pat(&l.pat),
1703 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1705 attrs: l.attrs.clone(),
1706 source: hir::LocalSource::Normal,
1710 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1712 Mutability::Mutable => hir::MutMutable,
1713 Mutability::Immutable => hir::MutImmutable,
1717 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1718 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1722 pat: self.lower_pat(&arg.pat),
1726 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Spanned<Name>> {
1729 .map(|arg| match arg.pat.node {
1730 PatKind::Ident(_, ident, None) => respan(ident.span, ident.name),
1731 _ => respan(arg.pat.span, keywords::Invalid.name()),
1739 fn_def_id: Option<DefId>,
1740 impl_trait_return_allow: bool,
1741 ) -> P<hir::FnDecl> {
1742 // NOTE: The two last parameters here have to do with impl Trait. If fn_def_id is Some,
1743 // then impl Trait arguments are lowered into generic parameters on the given
1744 // fn_def_id, otherwise impl Trait is disallowed. (for now)
1746 // Furthermore, if impl_trait_return_allow is true, then impl Trait may be used in
1747 // return positions as well. This guards against trait declarations and their impls
1748 // where impl Trait is disallowed. (again for now)
1753 if let Some(def_id) = fn_def_id {
1754 self.lower_ty(&arg.ty, ImplTraitContext::Universal(def_id))
1756 self.lower_ty(&arg.ty, ImplTraitContext::Disallowed)
1760 output: match decl.output {
1761 FunctionRetTy::Ty(ref ty) => match fn_def_id {
1762 Some(_) if impl_trait_return_allow => {
1763 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential))
1765 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1767 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1769 variadic: decl.variadic,
1770 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1771 TyKind::ImplicitSelf => true,
1772 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1778 fn lower_ty_param_bound(
1781 itctx: ImplTraitContext,
1782 ) -> hir::TyParamBound {
1784 TraitTyParamBound(ref ty, modifier) => hir::TraitTyParamBound(
1785 self.lower_poly_trait_ref(ty, itctx),
1786 self.lower_trait_bound_modifier(modifier),
1788 RegionTyParamBound(ref lifetime) => {
1789 hir::RegionTyParamBound(self.lower_lifetime(lifetime))
1797 add_bounds: &[TyParamBound],
1798 itctx: ImplTraitContext,
1800 let mut name = self.lower_ident(tp.ident);
1802 // Don't expose `Self` (recovered "keyword used as ident" parse error).
1803 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
1804 // Instead, use gensym("Self") to create a distinct name that looks the same.
1805 if name == keywords::SelfType.name() {
1806 name = Symbol::gensym("Self");
1809 let mut bounds = self.lower_bounds(&tp.bounds, itctx);
1810 if !add_bounds.is_empty() {
1813 .chain(self.lower_bounds(add_bounds, itctx).into_iter())
1818 id: self.lower_node_id(tp.id).node_id,
1823 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
1824 span: tp.ident.span,
1825 pure_wrt_drop: attr::contains_name(&tp.attrs, "may_dangle"),
1828 .filter(|attr| attr.check_name("rustc_synthetic"))
1829 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
1831 attrs: self.lower_attrs(&tp.attrs),
1835 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1836 let span = l.ident.span;
1837 match self.lower_ident(l.ident) {
1838 x if x == "'static" => self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
1839 x if x == "'_" => match self.anonymous_lifetime_mode {
1840 AnonymousLifetimeMode::CreateParameter => {
1841 let fresh_name = self.collect_fresh_in_band_lifetime(span);
1842 self.new_named_lifetime(l.id, span, fresh_name)
1845 AnonymousLifetimeMode::PassThrough => {
1846 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
1850 self.maybe_collect_in_band_lifetime(span, name);
1851 self.new_named_lifetime(l.id, span, hir::LifetimeName::Name(name))
1856 fn new_named_lifetime(
1860 name: hir::LifetimeName,
1861 ) -> hir::Lifetime {
1863 id: self.lower_node_id(id).node_id,
1869 fn lower_lifetime_def(&mut self, l: &LifetimeDef) -> hir::LifetimeDef {
1870 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
1871 self.is_collecting_in_band_lifetimes = false;
1873 let def = hir::LifetimeDef {
1874 lifetime: self.lower_lifetime(&l.lifetime),
1875 bounds: self.lower_lifetimes(&l.bounds),
1876 pure_wrt_drop: attr::contains_name(&l.attrs, "may_dangle"),
1880 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
1885 fn lower_lifetimes(&mut self, lts: &Vec<Lifetime>) -> hir::HirVec<hir::Lifetime> {
1886 lts.iter().map(|l| self.lower_lifetime(l)).collect()
1889 fn lower_generic_params(
1891 params: &Vec<GenericParam>,
1892 add_bounds: &NodeMap<Vec<TyParamBound>>,
1893 itctx: ImplTraitContext,
1894 ) -> hir::HirVec<hir::GenericParam> {
1897 .map(|param| match *param {
1898 GenericParam::Lifetime(ref lifetime_def) => {
1899 hir::GenericParam::Lifetime(self.lower_lifetime_def(lifetime_def))
1901 GenericParam::Type(ref ty_param) => hir::GenericParam::Type(self.lower_ty_param(
1903 add_bounds.get(&ty_param.id).map_or(&[][..], |x| &x),
1910 fn lower_generics(&mut self, g: &Generics, itctx: ImplTraitContext) -> hir::Generics {
1911 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
1912 // FIXME: This could probably be done with less rightward drift. Also looks like two control
1913 // paths where report_error is called are also the only paths that advance to after
1914 // the match statement, so the error reporting could probably just be moved there.
1915 let mut add_bounds = NodeMap();
1916 for pred in &g.where_clause.predicates {
1917 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
1918 'next_bound: for bound in &bound_pred.bounds {
1919 if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
1920 let report_error = |this: &mut Self| {
1921 this.diagnostic().span_err(
1922 bound_pred.bounded_ty.span,
1923 "`?Trait` bounds are only permitted at the \
1924 point where a type parameter is declared",
1927 // Check if the where clause type is a plain type parameter.
1928 match bound_pred.bounded_ty.node {
1929 TyKind::Path(None, ref path)
1930 if path.segments.len() == 1
1931 && bound_pred.bound_generic_params.is_empty() =>
1933 if let Some(Def::TyParam(def_id)) = self.resolver
1934 .get_resolution(bound_pred.bounded_ty.id)
1935 .map(|d| d.base_def())
1937 if let Some(node_id) =
1938 self.resolver.definitions().as_local_node_id(def_id)
1940 for param in &g.params {
1941 if let GenericParam::Type(ref ty_param) = *param {
1942 if node_id == ty_param.id {
1945 .or_insert(Vec::new())
1946 .push(bound.clone());
1947 continue 'next_bound;
1955 _ => report_error(self),
1963 params: self.lower_generic_params(&g.params, &add_bounds, itctx),
1964 where_clause: self.lower_where_clause(&g.where_clause),
1969 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
1971 id: self.lower_node_id(wc.id).node_id,
1972 predicates: wc.predicates
1974 .map(|predicate| self.lower_where_predicate(predicate))
1979 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
1981 WherePredicate::BoundPredicate(WhereBoundPredicate {
1982 ref bound_generic_params,
1987 self.with_in_scope_lifetime_defs(
1988 bound_generic_params.iter().filter_map(|p| match p {
1989 GenericParam::Lifetime(ld) => Some(ld),
1993 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1994 bound_generic_params: this.lower_generic_params(
1995 bound_generic_params,
1997 ImplTraitContext::Disallowed,
1999 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2002 .filter_map(|bound| match *bound {
2003 // Ignore `?Trait` bounds.
2004 // Tthey were copied into type parameters already.
2005 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
2006 _ => Some(this.lower_ty_param_bound(
2008 ImplTraitContext::Disallowed,
2017 WherePredicate::RegionPredicate(WhereRegionPredicate {
2021 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2023 lifetime: self.lower_lifetime(lifetime),
2026 .map(|bound| self.lower_lifetime(bound))
2029 WherePredicate::EqPredicate(WhereEqPredicate {
2034 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2035 id: self.lower_node_id(id).node_id,
2036 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2037 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2043 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2045 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2049 .map(|f| self.lower_struct_field(f))
2051 self.lower_node_id(id).node_id,
2053 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2057 .map(|f| self.lower_struct_field(f))
2059 self.lower_node_id(id).node_id,
2061 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2065 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2066 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2067 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2068 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2072 ref_id: self.lower_node_id(p.ref_id).node_id,
2076 fn lower_poly_trait_ref(
2079 itctx: ImplTraitContext,
2080 ) -> hir::PolyTraitRef {
2081 let bound_generic_params =
2082 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx);
2083 let trait_ref = self.with_parent_impl_lifetime_defs(
2084 &bound_generic_params
2086 .filter_map(|p| match *p {
2087 hir::GenericParam::Lifetime(ref ld) => Some(ld.clone()),
2090 .collect::<Vec<_>>(),
2091 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2095 bound_generic_params,
2101 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2104 id: self.lower_node_id(f.id).node_id,
2105 ident: match f.ident {
2106 Some(ident) => ident,
2107 // FIXME(jseyfried) positional field hygiene
2108 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2110 vis: self.lower_visibility(&f.vis, None),
2111 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2112 attrs: self.lower_attrs(&f.attrs),
2116 fn lower_field(&mut self, f: &Field) -> hir::Field {
2118 id: self.next_id().node_id,
2120 expr: P(self.lower_expr(&f.expr)),
2122 is_shorthand: f.is_shorthand,
2126 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2128 ty: self.lower_ty(&mt.ty, itctx),
2129 mutbl: self.lower_mutability(mt.mutbl),
2135 bounds: &[TyParamBound],
2136 itctx: ImplTraitContext,
2137 ) -> hir::TyParamBounds {
2140 .map(|bound| self.lower_ty_param_bound(bound, itctx))
2144 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2145 let mut expr = None;
2147 let mut stmts = vec![];
2149 for (index, stmt) in b.stmts.iter().enumerate() {
2150 if index == b.stmts.len() - 1 {
2151 if let StmtKind::Expr(ref e) = stmt.node {
2152 expr = Some(P(self.lower_expr(e)));
2154 stmts.extend(self.lower_stmt(stmt));
2157 stmts.extend(self.lower_stmt(stmt));
2161 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2166 stmts: stmts.into(),
2168 rules: self.lower_block_check_mode(&b.rules),
2171 recovered: b.recovered,
2179 attrs: &hir::HirVec<Attribute>,
2180 vis: &mut hir::Visibility,
2184 ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2185 ItemKind::Use(ref use_tree) => {
2186 // Start with an empty prefix
2189 span: use_tree.span,
2192 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2194 ItemKind::Static(ref t, m, ref e) => {
2195 let value = self.lower_body(None, |this| this.lower_expr(e));
2197 self.lower_ty(t, ImplTraitContext::Disallowed),
2198 self.lower_mutability(m),
2202 ItemKind::Const(ref t, ref e) => {
2203 let value = self.lower_body(None, |this| this.lower_expr(e));
2204 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2206 ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
2207 let fn_def_id = self.resolver.definitions().local_def_id(id);
2208 self.with_new_scopes(|this| {
2209 let body_id = this.lower_body(Some(decl), |this| {
2210 let body = this.lower_block(body, false);
2211 this.expr_block(body, ThinVec::new())
2213 let (generics, fn_decl) = this.add_in_band_defs(
2216 AnonymousLifetimeMode::PassThrough,
2217 |this| this.lower_fn_decl(decl, Some(fn_def_id), true),
2222 this.lower_unsafety(unsafety),
2223 this.lower_constness(constness),
2230 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2231 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2232 ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2233 ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2234 self.lower_ty(t, ImplTraitContext::Disallowed),
2235 self.lower_generics(generics, ImplTraitContext::Disallowed),
2237 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2239 variants: enum_definition
2242 .map(|x| self.lower_variant(x))
2245 self.lower_generics(generics, ImplTraitContext::Disallowed),
2247 ItemKind::Struct(ref struct_def, ref generics) => {
2248 let struct_def = self.lower_variant_data(struct_def);
2251 self.lower_generics(generics, ImplTraitContext::Disallowed),
2254 ItemKind::Union(ref vdata, ref generics) => {
2255 let vdata = self.lower_variant_data(vdata);
2258 self.lower_generics(generics, ImplTraitContext::Disallowed),
2270 let def_id = self.resolver.definitions().local_def_id(id);
2272 // Lower the "impl header" first. This ordering is important
2273 // for in-band lifetimes! Consider `'a` here:
2275 // impl Foo<'a> for u32 {
2276 // fn method(&'a self) { .. }
2279 // Because we start by lowering the `Foo<'a> for u32`
2280 // part, we will add `'a` to the list of generics on
2281 // the impl. When we then encounter it later in the
2282 // method, it will not be considered an in-band
2283 // lifetime to be added, but rather a reference to a
2285 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2288 AnonymousLifetimeMode::CreateParameter,
2290 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2291 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2294 if let Some(ref trait_ref) = trait_ref {
2295 if let Def::Trait(def_id) = trait_ref.path.def {
2296 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2300 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2302 (trait_ref, lowered_ty)
2306 let new_impl_items = self.with_in_scope_lifetime_defs(
2307 ast_generics.params.iter().filter_map(|p| match p {
2308 GenericParam::Lifetime(ld) => Some(ld),
2314 .map(|item| this.lower_impl_item_ref(item))
2320 self.lower_unsafety(unsafety),
2321 self.lower_impl_polarity(polarity),
2322 self.lower_defaultness(defaultness, true /* [1] */),
2329 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2330 let bounds = self.lower_bounds(bounds, ImplTraitContext::Disallowed);
2333 .map(|item| self.lower_trait_item_ref(item))
2336 self.lower_is_auto(is_auto),
2337 self.lower_unsafety(unsafety),
2338 self.lower_generics(generics, ImplTraitContext::Disallowed),
2343 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2344 self.lower_generics(generics, ImplTraitContext::Disallowed),
2345 self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2347 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2350 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2351 // not cause an assertion failure inside the `lower_defaultness` function
2359 vis: &mut hir::Visibility,
2361 attrs: &hir::HirVec<Attribute>,
2363 let path = &tree.prefix;
2366 UseTreeKind::Simple(rename) => {
2367 *name = tree.ident().name;
2369 // First apply the prefix to the path
2370 let mut path = Path {
2374 .chain(path.segments.iter())
2380 // Correctly resolve `self` imports
2381 if path.segments.len() > 1
2382 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2384 let _ = path.segments.pop();
2385 if rename.is_none() {
2386 *name = path.segments.last().unwrap().ident.name;
2390 let path = P(self.lower_path(id, &path, ParamMode::Explicit));
2391 hir::ItemUse(path, hir::UseKind::Single)
2393 UseTreeKind::Glob => {
2394 let path = P(self.lower_path(
2400 .chain(path.segments.iter())
2405 ParamMode::Explicit,
2407 hir::ItemUse(path, hir::UseKind::Glob)
2409 UseTreeKind::Nested(ref trees) => {
2414 .chain(path.segments.iter())
2417 span: prefix.span.to(path.span),
2420 // Add all the nested PathListItems in the HIR
2421 for &(ref use_tree, id) in trees {
2422 self.allocate_hir_id_counter(id, &use_tree);
2426 } = self.lower_node_id(id);
2428 let mut vis = vis.clone();
2429 let mut name = name.clone();
2431 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2433 self.with_hir_id_owner(new_id, |this| {
2434 let vis = match vis {
2435 hir::Visibility::Public => hir::Visibility::Public,
2436 hir::Visibility::Crate => hir::Visibility::Crate,
2437 hir::Visibility::Inherited => hir::Visibility::Inherited,
2438 hir::Visibility::Restricted { ref path, id: _ } => {
2439 hir::Visibility::Restricted {
2441 // We are allocating a new NodeId here
2442 id: this.next_id().node_id,
2453 attrs: attrs.clone(),
2456 span: use_tree.span,
2462 // Privatize the degenerate import base, used only to check
2463 // the stability of `use a::{};`, to avoid it showing up as
2464 // a re-export by accident when `pub`, e.g. in documentation.
2465 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2466 *vis = hir::Inherited;
2467 hir::ItemUse(path, hir::UseKind::ListStem)
2472 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2473 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2474 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2476 let (generics, node) = match i.node {
2477 TraitItemKind::Const(ref ty, ref default) => (
2478 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2479 hir::TraitItemKind::Const(
2480 self.lower_ty(ty, ImplTraitContext::Disallowed),
2483 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2486 TraitItemKind::Method(ref sig, None) => {
2487 let names = self.lower_fn_args_to_names(&sig.decl);
2488 self.add_in_band_defs(
2491 AnonymousLifetimeMode::PassThrough,
2493 hir::TraitItemKind::Method(
2494 this.lower_method_sig(sig, trait_item_def_id, false),
2495 hir::TraitMethod::Required(names),
2500 TraitItemKind::Method(ref sig, Some(ref body)) => {
2501 let body_id = self.lower_body(Some(&sig.decl), |this| {
2502 let body = this.lower_block(body, false);
2503 this.expr_block(body, ThinVec::new())
2506 self.add_in_band_defs(
2509 AnonymousLifetimeMode::PassThrough,
2511 hir::TraitItemKind::Method(
2512 this.lower_method_sig(sig, trait_item_def_id, false),
2513 hir::TraitMethod::Provided(body_id),
2518 TraitItemKind::Type(ref bounds, ref default) => (
2519 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2520 hir::TraitItemKind::Type(
2521 self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2524 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2527 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2533 name: self.lower_ident(i.ident),
2534 attrs: self.lower_attrs(&i.attrs),
2541 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2542 let (kind, has_default) = match i.node {
2543 TraitItemKind::Const(_, ref default) => {
2544 (hir::AssociatedItemKind::Const, default.is_some())
2546 TraitItemKind::Type(_, ref default) => {
2547 (hir::AssociatedItemKind::Type, default.is_some())
2549 TraitItemKind::Method(ref sig, ref default) => (
2550 hir::AssociatedItemKind::Method {
2551 has_self: sig.decl.has_self(),
2555 TraitItemKind::Macro(..) => unimplemented!(),
2558 id: hir::TraitItemId { node_id: i.id },
2559 name: self.lower_ident(i.ident),
2561 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
2566 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
2567 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2568 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
2570 let (generics, node) = match i.node {
2571 ImplItemKind::Const(ref ty, ref expr) => {
2572 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
2574 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2575 hir::ImplItemKind::Const(
2576 self.lower_ty(ty, ImplTraitContext::Disallowed),
2581 ImplItemKind::Method(ref sig, ref body) => {
2582 let body_id = self.lower_body(Some(&sig.decl), |this| {
2583 let body = this.lower_block(body, false);
2584 this.expr_block(body, ThinVec::new())
2586 let impl_trait_return_allow = !self.is_in_trait_impl;
2588 self.add_in_band_defs(
2591 AnonymousLifetimeMode::PassThrough,
2593 hir::ImplItemKind::Method(
2594 this.lower_method_sig(
2597 impl_trait_return_allow,
2604 ImplItemKind::Type(ref ty) => (
2605 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2606 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
2608 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2614 name: self.lower_ident(i.ident),
2615 attrs: self.lower_attrs(&i.attrs),
2617 vis: self.lower_visibility(&i.vis, None),
2618 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2623 // [1] since `default impl` is not yet implemented, this is always true in impls
2626 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
2628 id: hir::ImplItemId { node_id: i.id },
2629 name: self.lower_ident(i.ident),
2631 vis: self.lower_visibility(&i.vis, Some(i.id)),
2632 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2633 kind: match i.node {
2634 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
2635 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
2636 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
2637 has_self: sig.decl.has_self(),
2639 ImplItemKind::Macro(..) => unimplemented!(),
2643 // [1] since `default impl` is not yet implemented, this is always true in impls
2646 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
2649 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
2653 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
2655 ItemKind::Use(ref use_tree) => {
2656 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
2657 self.lower_item_id_use_tree(use_tree, &mut vec);
2660 ItemKind::MacroDef(..) => return SmallVector::new(),
2663 SmallVector::one(hir::ItemId { id: i.id })
2666 fn lower_item_id_use_tree(&self, tree: &UseTree, vec: &mut SmallVector<hir::ItemId>) {
2668 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
2669 vec.push(hir::ItemId { id });
2670 self.lower_item_id_use_tree(nested, vec);
2672 UseTreeKind::Glob => {}
2673 UseTreeKind::Simple(..) => {}
2677 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
2678 let mut name = i.ident.name;
2679 let mut vis = self.lower_visibility(&i.vis, None);
2680 let attrs = self.lower_attrs(&i.attrs);
2681 if let ItemKind::MacroDef(ref def) = i.node {
2682 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
2683 let body = self.lower_token_stream(def.stream());
2684 self.exported_macros.push(hir::MacroDef {
2697 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
2699 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2712 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
2713 let node_id = self.lower_node_id(i.id).node_id;
2714 let def_id = self.resolver.definitions().local_def_id(node_id);
2718 attrs: self.lower_attrs(&i.attrs),
2719 node: match i.node {
2720 ForeignItemKind::Fn(ref fdec, ref generics) => {
2721 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
2724 AnonymousLifetimeMode::PassThrough,
2727 // Disallow impl Trait in foreign items
2728 this.lower_fn_decl(fdec, None, false),
2729 this.lower_fn_args_to_names(fdec),
2734 hir::ForeignItemFn(fn_dec, fn_args, generics)
2736 ForeignItemKind::Static(ref t, m) => {
2737 hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
2739 ForeignItemKind::Ty => hir::ForeignItemType,
2740 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
2742 vis: self.lower_visibility(&i.vis, None),
2747 fn lower_method_sig(
2751 impl_trait_return_allow: bool,
2752 ) -> hir::MethodSig {
2755 unsafety: self.lower_unsafety(sig.unsafety),
2756 constness: self.lower_constness(sig.constness),
2757 decl: self.lower_fn_decl(&sig.decl, Some(fn_def_id), impl_trait_return_allow),
2761 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
2763 IsAuto::Yes => hir::IsAuto::Yes,
2764 IsAuto::No => hir::IsAuto::No,
2768 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
2770 Unsafety::Unsafe => hir::Unsafety::Unsafe,
2771 Unsafety::Normal => hir::Unsafety::Normal,
2775 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
2777 Constness::Const => hir::Constness::Const,
2778 Constness::NotConst => hir::Constness::NotConst,
2782 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
2784 UnOp::Deref => hir::UnDeref,
2785 UnOp::Not => hir::UnNot,
2786 UnOp::Neg => hir::UnNeg,
2790 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
2792 node: match b.node {
2793 BinOpKind::Add => hir::BiAdd,
2794 BinOpKind::Sub => hir::BiSub,
2795 BinOpKind::Mul => hir::BiMul,
2796 BinOpKind::Div => hir::BiDiv,
2797 BinOpKind::Rem => hir::BiRem,
2798 BinOpKind::And => hir::BiAnd,
2799 BinOpKind::Or => hir::BiOr,
2800 BinOpKind::BitXor => hir::BiBitXor,
2801 BinOpKind::BitAnd => hir::BiBitAnd,
2802 BinOpKind::BitOr => hir::BiBitOr,
2803 BinOpKind::Shl => hir::BiShl,
2804 BinOpKind::Shr => hir::BiShr,
2805 BinOpKind::Eq => hir::BiEq,
2806 BinOpKind::Lt => hir::BiLt,
2807 BinOpKind::Le => hir::BiLe,
2808 BinOpKind::Ne => hir::BiNe,
2809 BinOpKind::Ge => hir::BiGe,
2810 BinOpKind::Gt => hir::BiGt,
2816 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2817 let node = match p.node {
2818 PatKind::Wild => hir::PatKind::Wild,
2819 PatKind::Ident(ref binding_mode, ident, ref sub) => {
2820 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
2821 // `None` can occur in body-less function signatures
2822 def @ None | def @ Some(Def::Local(_)) => {
2823 let canonical_id = match def {
2824 Some(Def::Local(id)) => id,
2827 hir::PatKind::Binding(
2828 self.lower_binding_mode(binding_mode),
2830 respan(ident.span, ident.name),
2831 sub.as_ref().map(|x| self.lower_pat(x)),
2834 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
2839 segments: hir_vec![hir::PathSegment::from_name(ident.name)],
2844 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
2845 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
2846 let qpath = self.lower_qpath(
2850 ParamMode::Optional,
2851 ImplTraitContext::Disallowed,
2853 hir::PatKind::TupleStruct(
2855 pats.iter().map(|x| self.lower_pat(x)).collect(),
2859 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
2863 ParamMode::Optional,
2864 ImplTraitContext::Disallowed,
2866 PatKind::Struct(ref path, ref fields, etc) => {
2867 let qpath = self.lower_qpath(
2871 ParamMode::Optional,
2872 ImplTraitContext::Disallowed,
2879 node: hir::FieldPat {
2880 id: self.next_id().node_id,
2881 ident: f.node.ident,
2882 pat: self.lower_pat(&f.node.pat),
2883 is_shorthand: f.node.is_shorthand,
2887 hir::PatKind::Struct(qpath, fs, etc)
2889 PatKind::Tuple(ref elts, ddpos) => {
2890 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
2892 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
2893 PatKind::Ref(ref inner, mutbl) => {
2894 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
2896 PatKind::Range(ref e1, ref e2, ref end) => hir::PatKind::Range(
2897 P(self.lower_expr(e1)),
2898 P(self.lower_expr(e2)),
2899 self.lower_range_end(end),
2901 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
2902 before.iter().map(|x| self.lower_pat(x)).collect(),
2903 slice.as_ref().map(|x| self.lower_pat(x)),
2904 after.iter().map(|x| self.lower_pat(x)).collect(),
2906 PatKind::Paren(ref inner) => return self.lower_pat(inner),
2907 PatKind::Mac(_) => panic!("Shouldn't exist here"),
2910 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
2919 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
2921 RangeEnd::Included(_) => hir::RangeEnd::Included,
2922 RangeEnd::Excluded => hir::RangeEnd::Excluded,
2926 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2927 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
2932 body: self.lower_body(None, |this| this.lower_expr(&c.value)),
2936 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
2937 let kind = match e.node {
2938 ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
2939 ExprKind::ObsoleteInPlace(..) => {
2940 self.sess.abort_if_errors();
2941 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
2943 ExprKind::Array(ref exprs) => {
2944 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
2946 ExprKind::Repeat(ref expr, ref count) => {
2947 let expr = P(self.lower_expr(expr));
2948 let count = self.lower_anon_const(count);
2949 hir::ExprRepeat(expr, count)
2951 ExprKind::Tup(ref elts) => {
2952 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
2954 ExprKind::Call(ref f, ref args) => {
2955 let f = P(self.lower_expr(f));
2956 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
2958 ExprKind::MethodCall(ref seg, ref args) => {
2959 let hir_seg = self.lower_path_segment(
2962 ParamMode::Optional,
2964 ParenthesizedGenericArgs::Err,
2965 ImplTraitContext::Disallowed,
2967 let args = args.iter().map(|x| self.lower_expr(x)).collect();
2968 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
2970 ExprKind::Binary(binop, ref lhs, ref rhs) => {
2971 let binop = self.lower_binop(binop);
2972 let lhs = P(self.lower_expr(lhs));
2973 let rhs = P(self.lower_expr(rhs));
2974 hir::ExprBinary(binop, lhs, rhs)
2976 ExprKind::Unary(op, ref ohs) => {
2977 let op = self.lower_unop(op);
2978 let ohs = P(self.lower_expr(ohs));
2979 hir::ExprUnary(op, ohs)
2981 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
2982 ExprKind::Cast(ref expr, ref ty) => {
2983 let expr = P(self.lower_expr(expr));
2984 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
2986 ExprKind::Type(ref expr, ref ty) => {
2987 let expr = P(self.lower_expr(expr));
2988 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
2990 ExprKind::AddrOf(m, ref ohs) => {
2991 let m = self.lower_mutability(m);
2992 let ohs = P(self.lower_expr(ohs));
2993 hir::ExprAddrOf(m, ohs)
2995 // More complicated than you might expect because the else branch
2996 // might be `if let`.
2997 ExprKind::If(ref cond, ref blk, ref else_opt) => {
2998 let else_opt = else_opt.as_ref().map(|els| {
3000 ExprKind::IfLet(..) => {
3001 // wrap the if-let expr in a block
3002 let span = els.span;
3003 let els = P(self.lower_expr(els));
3004 let LoweredNodeId { node_id, hir_id } = self.next_id();
3005 let blk = P(hir::Block {
3010 rules: hir::DefaultBlock,
3012 targeted_by_break: false,
3013 recovered: blk.recovered,
3015 P(self.expr_block(blk, ThinVec::new()))
3017 _ => P(self.lower_expr(els)),
3021 let then_blk = self.lower_block(blk, false);
3022 let then_expr = self.expr_block(then_blk, ThinVec::new());
3024 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3026 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3028 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3029 this.lower_block(body, false),
3030 this.lower_label(opt_label),
3033 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3035 this.lower_block(body, false),
3036 this.lower_label(opt_label),
3037 hir::LoopSource::Loop,
3040 ExprKind::Catch(ref body) => {
3041 self.with_catch_scope(body.id, |this| {
3043 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3044 let mut block = this.lower_block(body, true).into_inner();
3045 let tail = block.expr.take().map_or_else(
3047 let LoweredNodeId { node_id, hir_id } = this.next_id();
3048 let span = this.sess.codemap().end_point(unstable_span);
3052 node: hir::ExprTup(hir_vec![]),
3053 attrs: ThinVec::new(),
3057 |x: P<hir::Expr>| x.into_inner(),
3059 block.expr = Some(this.wrap_in_try_constructor(
3060 "from_ok", tail, unstable_span));
3061 hir::ExprBlock(P(block), None)
3064 ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3065 P(self.lower_expr(expr)),
3066 arms.iter().map(|x| self.lower_arm(x)).collect(),
3067 hir::MatchSource::Normal,
3069 ExprKind::Closure(capture_clause, movability, ref decl, ref body, fn_decl_span) => {
3070 self.with_new_scopes(|this| {
3071 let mut is_generator = false;
3072 let body_id = this.lower_body(Some(decl), |this| {
3073 let e = this.lower_expr(body);
3074 is_generator = this.is_generator;
3077 let generator_option = if is_generator {
3078 if !decl.inputs.is_empty() {
3083 "generators cannot have explicit arguments"
3085 this.sess.abort_if_errors();
3087 Some(match movability {
3088 Movability::Movable => hir::GeneratorMovability::Movable,
3089 Movability::Static => hir::GeneratorMovability::Static,
3092 if movability == Movability::Static {
3097 "closures cannot be static"
3103 this.lower_capture_clause(capture_clause),
3104 this.lower_fn_decl(decl, None, false),
3111 ExprKind::Block(ref blk, opt_label) => {
3112 hir::ExprBlock(self.lower_block(blk,
3113 opt_label.is_some()),
3114 self.lower_label(opt_label))
3116 ExprKind::Assign(ref el, ref er) => {
3117 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3119 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3120 self.lower_binop(op),
3121 P(self.lower_expr(el)),
3122 P(self.lower_expr(er)),
3124 ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3125 ExprKind::Index(ref el, ref er) => {
3126 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3128 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3129 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3130 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3131 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3132 let id = self.next_id();
3133 let e1 = self.lower_expr(e1);
3134 let e2 = self.lower_expr(e2);
3135 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], false));
3136 let ty = self.ty_path(id, span, hir::QPath::Resolved(None, ty_path));
3137 let new_seg = P(hir::PathSegment::from_name(Symbol::intern("new")));
3138 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3139 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3140 hir::ExprCall(new, hir_vec![e1, e2])
3142 ExprKind::Range(ref e1, ref e2, lims) => {
3143 use syntax::ast::RangeLimits::*;
3145 let path = match (e1, e2, lims) {
3146 (&None, &None, HalfOpen) => "RangeFull",
3147 (&Some(..), &None, HalfOpen) => "RangeFrom",
3148 (&None, &Some(..), HalfOpen) => "RangeTo",
3149 (&Some(..), &Some(..), HalfOpen) => "Range",
3150 (&None, &Some(..), Closed) => "RangeToInclusive",
3151 (&Some(..), &Some(..), Closed) => unreachable!(),
3152 (_, &None, Closed) => self.diagnostic()
3153 .span_fatal(e.span, "inclusive range with no end")
3157 let fields = e1.iter()
3158 .map(|e| ("start", e))
3159 .chain(e2.iter().map(|e| ("end", e)))
3161 let expr = P(self.lower_expr(&e));
3163 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3164 let ident = Ident::new(Symbol::intern(s), unstable_span);
3165 self.field(ident, expr, unstable_span)
3167 .collect::<P<[hir::Field]>>();
3169 let is_unit = fields.is_empty();
3171 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3172 let struct_path = iter::once("ops")
3173 .chain(iter::once(path))
3174 .collect::<Vec<_>>();
3175 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
3176 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3178 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3184 hir::ExprPath(struct_path)
3186 hir::ExprStruct(struct_path, fields, None)
3188 span: unstable_span,
3189 attrs: e.attrs.clone(),
3192 ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3196 ParamMode::Optional,
3197 ImplTraitContext::Disallowed,
3199 ExprKind::Break(opt_label, ref opt_expr) => {
3200 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3203 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3206 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3210 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3213 ExprKind::Continue(opt_label) => {
3214 hir::ExprAgain(if self.is_in_loop_condition && opt_label.is_none() {
3217 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3220 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3223 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3224 ExprKind::InlineAsm(ref asm) => {
3225 let hir_asm = hir::InlineAsm {
3226 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3227 outputs: asm.outputs
3229 .map(|out| hir::InlineAsmOutput {
3230 constraint: out.constraint.clone(),
3232 is_indirect: out.is_indirect,
3235 asm: asm.asm.clone(),
3236 asm_str_style: asm.asm_str_style,
3237 clobbers: asm.clobbers.clone().into(),
3238 volatile: asm.volatile,
3239 alignstack: asm.alignstack,
3240 dialect: asm.dialect,
3243 let outputs = asm.outputs
3245 .map(|out| self.lower_expr(&out.expr))
3247 let inputs = asm.inputs
3249 .map(|&(_, ref input)| self.lower_expr(input))
3251 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3253 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3258 ParamMode::Optional,
3259 ImplTraitContext::Disallowed,
3261 fields.iter().map(|x| self.lower_field(x)).collect(),
3262 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3264 ExprKind::Paren(ref ex) => {
3265 let mut ex = self.lower_expr(ex);
3266 // include parens in span, but only if it is a super-span.
3267 if e.span.contains(ex.span) {
3270 // merge attributes into the inner expression.
3271 let mut attrs = e.attrs.clone();
3272 attrs.extend::<Vec<_>>(ex.attrs.into());
3277 ExprKind::Yield(ref opt_expr) => {
3278 self.is_generator = true;
3281 .map(|x| self.lower_expr(x))
3282 .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3283 hir::ExprYield(P(expr))
3286 // Desugar ExprIfLet
3287 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3288 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3291 // match <sub_expr> {
3293 // _ => [<else_opt> | ()]
3296 let mut arms = vec![];
3298 // `<pat> => <body>`
3300 let body = self.lower_block(body, false);
3301 let body_expr = P(self.expr_block(body, ThinVec::new()));
3302 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3303 arms.push(self.arm(pats, body_expr));
3306 // _ => [<else_opt>|()]
3308 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3309 let wildcard_pattern = self.pat_wild(e.span);
3310 let body = if let Some(else_expr) = wildcard_arm {
3311 P(self.lower_expr(else_expr))
3313 self.expr_tuple(e.span, hir_vec![])
3315 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3318 let contains_else_clause = else_opt.is_some();
3320 let sub_expr = P(self.lower_expr(sub_expr));
3325 hir::MatchSource::IfLetDesugar {
3326 contains_else_clause,
3331 // Desugar ExprWhileLet
3332 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3333 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3336 // [opt_ident]: loop {
3337 // match <sub_expr> {
3343 // Note that the block AND the condition are evaluated in the loop scope.
3344 // This is done to allow `break` from inside the condition of the loop.
3345 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3347 this.lower_block(body, false),
3348 this.expr_break(e.span, ThinVec::new()),
3349 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3353 // `<pat> => <body>`
3355 let body_expr = P(self.expr_block(body, ThinVec::new()));
3356 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3357 self.arm(pats, body_expr)
3362 let pat_under = self.pat_wild(e.span);
3363 self.arm(hir_vec![pat_under], break_expr)
3366 // `match <sub_expr> { ... }`
3367 let arms = hir_vec![pat_arm, break_arm];
3368 let match_expr = self.expr(
3370 hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3374 // `[opt_ident]: loop { ... }`
3375 let loop_block = P(self.block_expr(P(match_expr)));
3376 let loop_expr = hir::ExprLoop(
3378 self.lower_label(opt_label),
3379 hir::LoopSource::WhileLet,
3381 // add attributes to the outer returned expr node
3385 // Desugar ExprForLoop
3386 // From: `[opt_ident]: for <pat> in <head> <body>`
3387 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3391 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3393 // [opt_ident]: loop {
3395 // match ::std::iter::Iterator::next(&mut iter) {
3396 // ::std::option::Option::Some(val) => __next = val,
3397 // ::std::option::Option::None => break
3399 // let <pat> = __next;
3400 // StmtExpr(<body>);
3408 let head = self.lower_expr(head);
3409 let head_sp = head.span;
3411 let iter = self.str_to_ident("iter");
3413 let next_ident = self.str_to_ident("__next");
3414 let next_pat = self.pat_ident_binding_mode(
3417 hir::BindingAnnotation::Mutable,
3420 // `::std::option::Option::Some(val) => next = val`
3422 let val_ident = self.str_to_ident("val");
3423 let val_pat = self.pat_ident(pat.span, val_ident);
3424 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
3425 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
3426 let assign = P(self.expr(
3428 hir::ExprAssign(next_expr, val_expr),
3431 let some_pat = self.pat_some(pat.span, val_pat);
3432 self.arm(hir_vec![some_pat], assign)
3435 // `::std::option::Option::None => break`
3438 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
3439 let pat = self.pat_none(e.span);
3440 self.arm(hir_vec![pat], break_expr)
3445 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
3447 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
3449 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
3450 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
3451 let next_path = &["iter", "Iterator", "next"];
3452 let next_path = P(self.expr_std_path(head_sp, next_path, ThinVec::new()));
3453 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
3454 let arms = hir_vec![pat_arm, break_arm];
3458 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
3462 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
3464 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
3468 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
3470 // `let <pat> = __next`
3471 let pat = self.lower_pat(pat);
3472 let pat_let = self.stmt_let_pat(
3476 hir::LocalSource::ForLoopDesugar,
3479 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
3480 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
3481 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
3483 let loop_block = P(self.block_all(
3485 hir_vec![next_let, match_stmt, pat_let, body_stmt],
3489 // `[opt_ident]: loop { ... }`
3490 let loop_expr = hir::ExprLoop(
3492 self.lower_label(opt_label),
3493 hir::LoopSource::ForLoop,
3495 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3496 let loop_expr = P(hir::Expr {
3501 attrs: ThinVec::new(),
3504 // `mut iter => { ... }`
3505 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
3507 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
3508 let into_iter_expr = {
3509 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
3510 let into_iter = P(self.expr_std_path(head_sp, into_iter_path, ThinVec::new()));
3511 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
3514 let match_expr = P(self.expr_match(
3518 hir::MatchSource::ForLoopDesugar,
3521 // `{ let _result = ...; _result }`
3522 // underscore prevents an unused_variables lint if the head diverges
3523 let result_ident = self.str_to_ident("_result");
3524 let (let_stmt, let_stmt_binding) =
3525 self.stmt_let(e.span, false, result_ident, match_expr);
3527 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
3528 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
3529 // add the attributes to the outer returned expr node
3530 return self.expr_block(block, e.attrs.clone());
3533 // Desugar ExprKind::Try
3535 ExprKind::Try(ref sub_expr) => {
3538 // match Try::into_result(<expr>) {
3539 // Ok(val) => #[allow(unreachable_code)] val,
3540 // Err(err) => #[allow(unreachable_code)]
3541 // // If there is an enclosing `catch {...}`
3542 // break 'catch_target Try::from_error(From::from(err)),
3544 // return Try::from_error(From::from(err)),
3548 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
3550 // Try::into_result(<expr>)
3553 let sub_expr = self.lower_expr(sub_expr);
3555 let path = &["ops", "Try", "into_result"];
3556 let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
3557 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
3560 // #[allow(unreachable_code)]
3562 // allow(unreachable_code)
3564 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
3565 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
3566 let uc_nested = attr::mk_nested_word_item(uc_ident);
3567 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
3569 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
3571 let attrs = vec![attr];
3573 // Ok(val) => #[allow(unreachable_code)] val,
3575 let val_ident = self.str_to_ident("val");
3576 let val_pat = self.pat_ident(e.span, val_ident);
3577 let val_expr = P(self.expr_ident_with_attrs(
3581 ThinVec::from(attrs.clone()),
3583 let ok_pat = self.pat_ok(e.span, val_pat);
3585 self.arm(hir_vec![ok_pat], val_expr)
3588 // Err(err) => #[allow(unreachable_code)]
3589 // return Try::from_error(From::from(err)),
3591 let err_ident = self.str_to_ident("err");
3592 let err_local = self.pat_ident(e.span, err_ident);
3594 let path = &["convert", "From", "from"];
3595 let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
3596 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
3598 self.expr_call(e.span, from, hir_vec![err_expr])
3601 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
3602 let thin_attrs = ThinVec::from(attrs);
3603 let catch_scope = self.catch_scopes.last().map(|x| *x);
3604 let ret_expr = if let Some(catch_node) = catch_scope {
3610 target_id: Ok(catch_node),
3612 Some(from_err_expr),
3617 P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
3620 let err_pat = self.pat_err(e.span, err_local);
3621 self.arm(hir_vec![err_pat], ret_expr)
3626 hir_vec![err_arm, ok_arm],
3627 hir::MatchSource::TryDesugar,
3631 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
3634 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3641 attrs: e.attrs.clone(),
3645 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
3646 SmallVector::one(match s.node {
3647 StmtKind::Local(ref l) => Spanned {
3648 node: hir::StmtDecl(
3650 node: hir::DeclLocal(self.lower_local(l)),
3653 self.lower_node_id(s.id).node_id,
3657 StmtKind::Item(ref it) => {
3658 // Can only use the ID once.
3659 let mut id = Some(s.id);
3660 return self.lower_item_id(it)
3662 .map(|item_id| Spanned {
3663 node: hir::StmtDecl(
3665 node: hir::DeclItem(item_id),
3669 .map(|id| self.lower_node_id(id).node_id)
3670 .unwrap_or_else(|| self.next_id().node_id),
3676 StmtKind::Expr(ref e) => Spanned {
3677 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3680 StmtKind::Semi(ref e) => Spanned {
3681 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3684 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
3688 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
3690 CaptureBy::Value => hir::CaptureByValue,
3691 CaptureBy::Ref => hir::CaptureByRef,
3695 /// If an `explicit_owner` is given, this method allocates the `HirId` in
3696 /// the address space of that item instead of the item currently being
3697 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
3698 /// lower a `Visibility` value although we haven't lowered the owning
3699 /// `ImplItem` in question yet.
3700 fn lower_visibility(
3703 explicit_owner: Option<NodeId>,
3704 ) -> hir::Visibility {
3706 VisibilityKind::Public => hir::Public,
3707 VisibilityKind::Crate(..) => hir::Visibility::Crate,
3708 VisibilityKind::Restricted { ref path, id, .. } => hir::Visibility::Restricted {
3709 path: P(self.lower_path(id, path, ParamMode::Explicit)),
3710 id: if let Some(owner) = explicit_owner {
3711 self.lower_node_id_with_owner(id, owner).node_id
3713 self.lower_node_id(id).node_id
3716 VisibilityKind::Inherited => hir::Inherited,
3720 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
3722 Defaultness::Default => hir::Defaultness::Default {
3723 has_value: has_value,
3725 Defaultness::Final => {
3727 hir::Defaultness::Final
3732 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3734 BlockCheckMode::Default => hir::DefaultBlock,
3735 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3739 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3741 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
3742 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
3743 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
3744 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
3748 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3750 CompilerGenerated => hir::CompilerGenerated,
3751 UserProvided => hir::UserProvided,
3755 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
3757 ImplPolarity::Positive => hir::ImplPolarity::Positive,
3758 ImplPolarity::Negative => hir::ImplPolarity::Negative,
3762 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3764 TraitBoundModifier::None => hir::TraitBoundModifier::None,
3765 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3769 // Helper methods for building HIR.
3771 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
3780 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
3782 id: self.next_id().node_id,
3786 is_shorthand: false,
3790 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
3791 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
3792 P(self.expr(span, expr_break, attrs))
3799 args: hir::HirVec<hir::Expr>,
3801 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
3804 fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
3805 self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
3808 fn expr_ident_with_attrs(
3813 attrs: ThinVec<Attribute>,
3815 let expr_path = hir::ExprPath(hir::QPath::Resolved(
3819 def: Def::Local(binding),
3820 segments: hir_vec![hir::PathSegment::from_name(id)],
3824 self.expr(span, expr_path, attrs)
3827 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
3828 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
3834 components: &[&str],
3835 attrs: ThinVec<Attribute>,
3837 let path = self.std_path(span, components, true);
3840 hir::ExprPath(hir::QPath::Resolved(None, P(path))),
3849 arms: hir::HirVec<hir::Arm>,
3850 source: hir::MatchSource,
3852 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
3855 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
3856 self.expr(b.span, hir::ExprBlock(b, None), attrs)
3859 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
3860 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
3863 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
3864 let LoweredNodeId { node_id, hir_id } = self.next_id();
3877 ex: Option<P<hir::Expr>>,
3879 source: hir::LocalSource,
3881 let LoweredNodeId { node_id, hir_id } = self.next_id();
3883 let local = P(hir::Local {
3890 attrs: ThinVec::new(),
3893 let decl = respan(sp, hir::DeclLocal(local));
3894 respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
3903 ) -> (hir::Stmt, NodeId) {
3904 let pat = if mutbl {
3905 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
3907 self.pat_ident(sp, ident)
3909 let pat_id = pat.id;
3911 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
3916 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
3917 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
3923 stmts: hir::HirVec<hir::Stmt>,
3924 expr: Option<P<hir::Expr>>,
3926 let LoweredNodeId { node_id, hir_id } = self.next_id();
3933 rules: hir::DefaultBlock,
3935 targeted_by_break: false,
3940 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3941 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
3944 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3945 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
3948 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3949 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
3952 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
3953 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
3959 components: &[&str],
3960 subpats: hir::HirVec<P<hir::Pat>>,
3962 let path = self.std_path(span, components, true);
3963 let qpath = hir::QPath::Resolved(None, P(path));
3964 let pt = if subpats.is_empty() {
3965 hir::PatKind::Path(qpath)
3967 hir::PatKind::TupleStruct(qpath, subpats, None)
3972 fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
3973 self.pat_ident_binding_mode(span, name, hir::BindingAnnotation::Unannotated)
3976 fn pat_ident_binding_mode(
3980 bm: hir::BindingAnnotation,
3982 let LoweredNodeId { node_id, hir_id } = self.next_id();
3987 node: hir::PatKind::Binding(bm, node_id, Spanned { span, node: name }, None),
3992 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
3993 self.pat(span, hir::PatKind::Wild)
3996 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
3997 let LoweredNodeId { node_id, hir_id } = self.next_id();
4006 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4007 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4008 /// The path is also resolved according to `is_value`.
4009 fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
4011 .resolve_str_path(span, self.crate_root, components, is_value)
4014 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
4016 let node = match qpath {
4017 hir::QPath::Resolved(None, path) => {
4018 // Turn trait object paths into `TyTraitObject` instead.
4019 if let Def::Trait(_) = path.def {
4020 let principal = hir::PolyTraitRef {
4021 bound_generic_params: hir::HirVec::new(),
4022 trait_ref: hir::TraitRef {
4023 path: path.and_then(|path| path),
4029 // The original ID is taken by the `PolyTraitRef`,
4030 // so the `Ty` itself needs a different one.
4031 id = self.next_id();
4032 hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4034 hir::TyPath(hir::QPath::Resolved(None, path))
4037 _ => hir::TyPath(qpath),
4047 /// Invoked to create the lifetime argument for a type `&T`
4048 /// with no explicit lifetime.
4049 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4050 match self.anonymous_lifetime_mode {
4051 // Intercept when we are in an impl header and introduce an in-band lifetime.
4052 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4054 AnonymousLifetimeMode::CreateParameter => {
4055 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4057 id: self.next_id().node_id,
4063 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4067 /// Invoked to create the lifetime argument(s) for a path like
4068 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4069 /// sorts of cases are deprecated. This may therefore report a warning or an
4070 /// error, depending on the mode.
4071 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4072 match self.anonymous_lifetime_mode {
4073 // NB. We intentionally ignore the create-parameter mode here
4074 // and instead "pass through" to resolve-lifetimes, which will then
4075 // report an error. This is because we don't want to support
4076 // impl elision for deprecated forms like
4078 // impl Foo for std::cell::Ref<u32> // note lack of '_
4079 AnonymousLifetimeMode::CreateParameter => {}
4081 // This is the normal case.
4082 AnonymousLifetimeMode::PassThrough => {}
4086 .map(|_| self.new_implicit_lifetime(span))
4090 /// Invoked to create the lifetime argument(s) for an elided trait object
4091 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4092 /// when the bound is written, even if it is written with `'_` like in
4093 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4094 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4095 match self.anonymous_lifetime_mode {
4096 // NB. We intentionally ignore the create-parameter mode here.
4097 // and instead "pass through" to resolve-lifetimes, which will apply
4098 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4099 // do not act like other elided lifetimes. In other words, given this:
4101 // impl Foo for Box<dyn Debug>
4103 // we do not introduce a fresh `'_` to serve as the bound, but instead
4104 // ultimately translate to the equivalent of:
4106 // impl Foo for Box<dyn Debug + 'static>
4108 // `resolve_lifetime` has the code to make that happen.
4109 AnonymousLifetimeMode::CreateParameter => {}
4111 // This is the normal case.
4112 AnonymousLifetimeMode::PassThrough => {}
4115 self.new_implicit_lifetime(span)
4118 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4120 id: self.next_id().node_id,
4122 name: hir::LifetimeName::Implicit,
4126 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4127 self.sess.buffer_lint_with_diagnostic(
4128 builtin::BARE_TRAIT_OBJECTS,
4131 "trait objects without an explicit `dyn` are deprecated",
4132 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4136 fn wrap_in_try_constructor(
4138 method: &'static str,
4140 unstable_span: Span,
4142 let path = &["ops", "Try", method];
4143 let from_err = P(self.expr_std_path(unstable_span, path,
4145 P(self.expr_call(e.span, from_err, hir_vec![e]))
4149 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4150 // Sorting by span ensures that we get things in order within a
4151 // file, and also puts the files in a sensible order.
4152 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4153 body_ids.sort_by_key(|b| bodies[b].value.span);