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;
44 use hir::{self, ParamName};
46 use hir::map::{DefKey, DefPathData, Definitions};
47 use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX};
48 use hir::def::{Def, PathResolution, PerNS};
50 use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
51 ELIDED_LIFETIMES_IN_PATHS};
52 use middle::cstore::CrateStore;
53 use rustc_data_structures::fx::FxHashSet;
54 use rustc_data_structures::indexed_vec::IndexVec;
55 use rustc_data_structures::small_vec::OneVector;
56 use rustc_data_structures::thin_vec::ThinVec;
58 use util::common::FN_OUTPUT_NAME;
59 use util::nodemap::{DefIdMap, NodeMap};
61 use std::collections::BTreeMap;
69 use syntax::ext::hygiene::{Mark, SyntaxContext};
70 use syntax::feature_gate::{emit_feature_err, GateIssue};
71 use syntax::print::pprust;
73 use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned};
74 use syntax::std_inject;
75 use syntax::symbol::{keywords, Symbol};
76 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
77 use syntax::parse::token::Token;
78 use syntax::visit::{self, Visitor};
79 use syntax_pos::{Span, MultiSpan};
81 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
83 pub struct LoweringContext<'a> {
84 crate_root: Option<&'static str>,
86 // Use to assign ids to hir nodes that do not directly correspond to an ast node
89 cstore: &'a dyn CrateStore,
91 resolver: &'a mut dyn Resolver,
93 /// The items being lowered are collected here.
94 items: BTreeMap<NodeId, hir::Item>,
96 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
97 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
98 bodies: BTreeMap<hir::BodyId, hir::Body>,
99 exported_macros: Vec<hir::MacroDef>,
101 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
102 trait_auto_impl: BTreeMap<DefId, NodeId>,
106 catch_scopes: Vec<NodeId>,
107 loop_scopes: Vec<NodeId>,
108 is_in_loop_condition: bool,
109 is_in_trait_impl: bool,
111 /// What to do when we encounter either an "anonymous lifetime
112 /// reference". The term "anonymous" is meant to encompass both
113 /// `'_` lifetimes as well as fully elided cases where nothing is
114 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
115 anonymous_lifetime_mode: AnonymousLifetimeMode,
117 // Used to create lifetime definitions from in-band lifetime usages.
118 // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
119 // When a named lifetime is encountered in a function or impl header and
120 // has not been defined
121 // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
122 // to this list. The results of this list are then added to the list of
123 // lifetime definitions in the corresponding impl or function generics.
124 lifetimes_to_define: Vec<(Span, ParamName)>,
126 // Whether or not in-band lifetimes are being collected. This is used to
127 // indicate whether or not we're in a place where new lifetimes will result
128 // in in-band lifetime definitions, such a function or an impl header.
129 // This will always be false unless the `in_band_lifetimes` or
130 // `impl_header_lifetime_elision` feature is enabled.
131 is_collecting_in_band_lifetimes: bool,
133 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
134 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
135 // against this list to see if it is already in-scope, or if a definition
136 // needs to be created for it.
137 in_scope_lifetimes: Vec<Ident>,
139 type_def_lifetime_params: DefIdMap<usize>,
141 current_hir_id_owner: Vec<(DefIndex, u32)>,
142 item_local_id_counters: NodeMap<u32>,
143 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
147 /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
148 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
150 /// Obtain the resolution for a node id
151 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
153 /// Obtain the possible resolutions for the given `use` statement.
154 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
156 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
157 /// This should only return `None` during testing.
158 fn definitions(&mut self) -> &mut Definitions;
160 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
161 /// it based on `is_value`.
165 crate_root: Option<&str>,
167 params: Option<P<hir::GenericArgs>>,
173 enum ImplTraitContext<'a> {
174 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
175 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
176 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
178 /// Newly generated parameters should be inserted into the given `Vec`
179 Universal(&'a mut Vec<hir::GenericParam>),
181 /// Treat `impl Trait` as shorthand for a new universal existential parameter.
182 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
183 /// equivalent to a fresh existential parameter like `abstract type T; fn foo() -> T`.
185 /// We store a DefId here so we can look up necessary information later
188 /// `impl Trait` is not accepted in this position.
192 impl<'a> ImplTraitContext<'a> {
193 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
194 use self::ImplTraitContext::*;
196 Universal(params) => Universal(params),
197 Existential(did) => Existential(*did),
198 Disallowed => Disallowed,
205 cstore: &dyn CrateStore,
206 dep_graph: &DepGraph,
208 resolver: &mut dyn Resolver,
210 // We're constructing the HIR here; we don't care what we will
211 // read, since we haven't even constructed the *input* to
213 dep_graph.assert_ignored();
216 crate_root: std_inject::injected_crate_name(),
220 items: BTreeMap::new(),
221 trait_items: BTreeMap::new(),
222 impl_items: BTreeMap::new(),
223 bodies: BTreeMap::new(),
224 trait_impls: BTreeMap::new(),
225 trait_auto_impl: BTreeMap::new(),
226 exported_macros: Vec::new(),
227 catch_scopes: Vec::new(),
228 loop_scopes: Vec::new(),
229 is_in_loop_condition: false,
230 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
231 type_def_lifetime_params: DefIdMap(),
232 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
233 item_local_id_counters: NodeMap(),
234 node_id_to_hir_id: IndexVec::new(),
236 is_in_trait_impl: false,
237 lifetimes_to_define: Vec::new(),
238 is_collecting_in_band_lifetimes: false,
239 in_scope_lifetimes: Vec::new(),
243 #[derive(Copy, Clone, PartialEq)]
245 /// Any path in a type context.
247 /// The `module::Type` in `module::Type::method` in an expression.
252 struct LoweredNodeId {
257 enum ParenthesizedGenericArgs {
263 /// What to do when we encounter an **anonymous** lifetime
264 /// reference. Anonymous lifetime references come in two flavors. You
265 /// have implicit, or fully elided, references to lifetimes, like the
266 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
267 /// or `Ref<'_, T>`. These often behave the same, but not always:
269 /// - certain usages of implicit references are deprecated, like
270 /// `Ref<T>`, and we sometimes just give hard errors in those cases
272 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
273 /// the same as `Box<dyn Foo + '_>`.
275 /// We describe the effects of the various modes in terms of three cases:
277 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
278 /// of a `&` (e.g., the missing lifetime in something like `&T`)
279 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
280 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
281 /// elided bounds follow special rules. Note that this only covers
282 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
283 /// '_>` is a case of "modern" elision.
284 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
285 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
286 /// non-deprecated equivalent.
288 /// Currently, the handling of lifetime elision is somewhat spread out
289 /// between HIR lowering and -- as described below -- the
290 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
291 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
292 /// everything into HIR lowering.
293 #[derive(Copy, Clone)]
294 enum AnonymousLifetimeMode {
295 /// For **Modern** cases, create a new anonymous region parameter
296 /// and reference that.
298 /// For **Dyn Bound** cases, pass responsibility to
299 /// `resolve_lifetime` code.
301 /// For **Deprecated** cases, report an error.
304 /// Pass responsibility to `resolve_lifetime` code for all cases.
308 impl<'a> LoweringContext<'a> {
309 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
310 /// Full-crate AST visitor that inserts into a fresh
311 /// `LoweringContext` any information that may be
312 /// needed from arbitrary locations in the crate.
313 /// E.g. The number of lifetime generic parameters
314 /// declared for every type and trait definition.
315 struct MiscCollector<'lcx, 'interner: 'lcx> {
316 lctx: &'lcx mut LoweringContext<'interner>,
319 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
320 fn visit_item(&mut self, item: &'lcx Item) {
321 self.lctx.allocate_hir_id_counter(item.id, item);
324 ItemKind::Struct(_, ref generics)
325 | ItemKind::Union(_, ref generics)
326 | ItemKind::Enum(_, ref generics)
327 | ItemKind::Ty(_, ref generics)
328 | ItemKind::Existential(_, ref generics)
329 | ItemKind::Trait(_, _, ref generics, ..) => {
330 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
334 .filter(|param| match param.kind {
335 ast::GenericParamKind::Lifetime { .. } => true,
339 self.lctx.type_def_lifetime_params.insert(def_id, count);
343 visit::walk_item(self, item);
346 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
347 self.lctx.allocate_hir_id_counter(item.id, item);
348 visit::walk_trait_item(self, item);
351 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
352 self.lctx.allocate_hir_id_counter(item.id, item);
353 visit::walk_impl_item(self, item);
357 struct ItemLowerer<'lcx, 'interner: 'lcx> {
358 lctx: &'lcx mut LoweringContext<'interner>,
361 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
362 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
364 F: FnOnce(&mut Self),
366 let old = self.lctx.is_in_trait_impl;
367 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
373 self.lctx.is_in_trait_impl = old;
377 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
378 fn visit_item(&mut self, item: &'lcx Item) {
379 let mut item_lowered = true;
380 self.lctx.with_hir_id_owner(item.id, |lctx| {
381 if let Some(hir_item) = lctx.lower_item(item) {
382 lctx.items.insert(item.id, hir_item);
384 item_lowered = false;
389 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
390 hir::ItemKind::Impl(_, _, _, ref generics, ..)
391 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
392 generics.params.clone()
397 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
398 let this = &mut ItemLowerer { lctx: this };
399 if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
400 this.with_trait_impl_ref(opt_trait_ref, |this| {
401 visit::walk_item(this, item)
404 visit::walk_item(this, item);
410 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
411 self.lctx.with_hir_id_owner(item.id, |lctx| {
412 let id = hir::TraitItemId { node_id: item.id };
413 let hir_item = lctx.lower_trait_item(item);
414 lctx.trait_items.insert(id, hir_item);
417 visit::walk_trait_item(self, item);
420 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
421 self.lctx.with_hir_id_owner(item.id, |lctx| {
422 let id = hir::ImplItemId { node_id: item.id };
423 let hir_item = lctx.lower_impl_item(item);
424 lctx.impl_items.insert(id, hir_item);
426 visit::walk_impl_item(self, item);
430 self.lower_node_id(CRATE_NODE_ID);
431 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
433 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
434 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
436 let module = self.lower_mod(&c.module);
437 let attrs = self.lower_attrs(&c.attrs);
438 let body_ids = body_ids(&self.bodies);
442 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
448 exported_macros: hir::HirVec::from(self.exported_macros),
450 trait_items: self.trait_items,
451 impl_items: self.impl_items,
454 trait_impls: self.trait_impls,
455 trait_auto_impl: self.trait_auto_impl,
459 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
460 if self.item_local_id_counters.insert(owner, 0).is_some() {
462 "Tried to allocate item_local_id_counter for {:?} twice",
466 // Always allocate the first HirId for the owner itself
467 self.lower_node_id_with_owner(owner, owner)
470 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
472 F: FnOnce(&mut Self) -> hir::HirId,
474 if ast_node_id == DUMMY_NODE_ID {
475 return LoweredNodeId {
476 node_id: DUMMY_NODE_ID,
477 hir_id: hir::DUMMY_HIR_ID,
481 let min_size = ast_node_id.as_usize() + 1;
483 if min_size > self.node_id_to_hir_id.len() {
484 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
487 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
489 if existing_hir_id == hir::DUMMY_HIR_ID {
490 // Generate a new HirId
491 let hir_id = alloc_hir_id(self);
492 self.node_id_to_hir_id[ast_node_id] = hir_id;
494 node_id: ast_node_id,
499 node_id: ast_node_id,
500 hir_id: existing_hir_id,
505 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
507 F: FnOnce(&mut Self) -> T,
509 let counter = self.item_local_id_counters
510 .insert(owner, HIR_ID_COUNTER_LOCKED)
511 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
512 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
513 self.current_hir_id_owner.push((def_index, counter));
515 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
517 debug_assert!(def_index == new_def_index);
518 debug_assert!(new_counter >= counter);
520 let prev = self.item_local_id_counters
521 .insert(owner, new_counter)
523 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
527 /// This method allocates a new HirId for the given NodeId and stores it in
528 /// the LoweringContext's NodeId => HirId map.
529 /// Take care not to call this method if the resulting HirId is then not
530 /// actually used in the HIR, as that would trigger an assertion in the
531 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
532 /// properly. Calling the method twice with the same NodeId is fine though.
533 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
534 self.lower_node_id_generic(ast_node_id, |this| {
535 let &mut (def_index, ref mut local_id_counter) =
536 this.current_hir_id_owner.last_mut().unwrap();
537 let local_id = *local_id_counter;
538 *local_id_counter += 1;
541 local_id: hir::ItemLocalId(local_id),
546 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
547 self.lower_node_id_generic(ast_node_id, |this| {
548 let local_id_counter = this
549 .item_local_id_counters
551 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
552 let local_id = *local_id_counter;
554 // We want to be sure not to modify the counter in the map while it
555 // is also on the stack. Otherwise we'll get lost updates when writing
556 // back from the stack to the map.
557 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
559 *local_id_counter += 1;
563 .opt_def_index(owner)
564 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
565 that do not belong to the current owner");
569 local_id: hir::ItemLocalId(local_id),
574 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
575 let body = hir::Body {
576 arguments: decl.map_or(hir_vec![], |decl| {
577 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
579 is_generator: self.is_generator,
583 self.bodies.insert(id, body);
587 fn next_id(&mut self) -> LoweredNodeId {
588 self.lower_node_id(self.sess.next_node_id())
591 fn expect_full_def(&mut self, id: NodeId) -> Def {
592 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
593 if pr.unresolved_segments() != 0 {
594 bug!("path not fully resolved: {:?}", pr);
600 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Def> {
601 self.resolver.get_import(id).present_items().map(|pr| {
602 if pr.unresolved_segments() != 0 {
603 bug!("path not fully resolved: {:?}", pr);
609 fn diagnostic(&self) -> &errors::Handler {
610 self.sess.diagnostic()
613 fn str_to_ident(&self, s: &'static str) -> Ident {
614 Ident::with_empty_ctxt(Symbol::gensym(s))
617 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
618 let mark = Mark::fresh(Mark::root());
619 mark.set_expn_info(source_map::ExpnInfo {
621 def_site: Some(span),
622 format: source_map::CompilerDesugaring(reason),
623 allow_internal_unstable: true,
624 allow_internal_unsafe: false,
625 local_inner_macros: false,
626 edition: source_map::hygiene::default_edition(),
628 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
631 fn with_anonymous_lifetime_mode<R>(
633 anonymous_lifetime_mode: AnonymousLifetimeMode,
634 op: impl FnOnce(&mut Self) -> R,
636 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
637 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
638 let result = op(self);
639 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
643 /// Creates a new hir::GenericParam for every new lifetime and
644 /// type parameter encountered while evaluating `f`. Definitions
645 /// are created with the parent provided. If no `parent_id` is
646 /// provided, no definitions will be returned.
648 /// Presuming that in-band lifetimes are enabled, then
649 /// `self.anonymous_lifetime_mode` will be updated to match the
650 /// argument while `f` is running (and restored afterwards).
651 fn collect_in_band_defs<T, F>(
654 anonymous_lifetime_mode: AnonymousLifetimeMode,
656 ) -> (Vec<hir::GenericParam>, T)
658 F: FnOnce(&mut LoweringContext) -> (Vec<hir::GenericParam>, T),
660 assert!(!self.is_collecting_in_band_lifetimes);
661 assert!(self.lifetimes_to_define.is_empty());
662 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
664 if self.sess.features_untracked().impl_header_lifetime_elision {
665 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
666 self.is_collecting_in_band_lifetimes = true;
667 } else if self.sess.features_untracked().in_band_lifetimes {
668 self.is_collecting_in_band_lifetimes = true;
671 let (in_band_ty_params, res) = f(self);
673 self.is_collecting_in_band_lifetimes = false;
674 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
676 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
678 let params = lifetimes_to_define
680 .map(|(span, hir_name)| {
681 let def_node_id = self.next_id().node_id;
683 // Get the name we'll use to make the def-path. Note
684 // that collisions are ok here and this shouldn't
685 // really show up for end-user.
686 let str_name = match hir_name {
687 ParamName::Plain(ident) => ident.as_interned_str(),
688 ParamName::Fresh(_) => keywords::UnderscoreLifetime.name().as_interned_str(),
691 // Add a definition for the in-band lifetime def
692 self.resolver.definitions().create_def_with_parent(
695 DefPathData::LifetimeParam(str_name),
696 DefIndexAddressSpace::High,
707 pure_wrt_drop: false,
708 kind: hir::GenericParamKind::Lifetime { in_band: true }
711 .chain(in_band_ty_params.into_iter())
717 /// When there is a reference to some lifetime `'a`, and in-band
718 /// lifetimes are enabled, then we want to push that lifetime into
719 /// the vector of names to define later. In that case, it will get
720 /// added to the appropriate generics.
721 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
722 if !self.is_collecting_in_band_lifetimes {
726 if !self.sess.features_untracked().in_band_lifetimes {
730 if self.in_scope_lifetimes.contains(&ident.modern()) {
734 let hir_name = ParamName::Plain(ident);
736 if self.lifetimes_to_define.iter()
737 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
741 self.lifetimes_to_define.push((ident.span, hir_name));
744 /// When we have either an elided or `'_` lifetime in an impl
745 /// header, we convert it to
746 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
747 assert!(self.is_collecting_in_band_lifetimes);
748 let index = self.lifetimes_to_define.len();
749 let hir_name = ParamName::Fresh(index);
750 self.lifetimes_to_define.push((span, hir_name));
754 // Evaluates `f` with the lifetimes in `params` in-scope.
755 // This is used to track which lifetimes have already been defined, and
756 // which are new in-band lifetimes that need to have a definition created
758 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
760 F: FnOnce(&mut LoweringContext) -> T,
762 let old_len = self.in_scope_lifetimes.len();
763 let lt_def_names = params.iter().filter_map(|param| match param.kind {
764 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
767 self.in_scope_lifetimes.extend(lt_def_names);
771 self.in_scope_lifetimes.truncate(old_len);
775 // Same as the method above, but accepts `hir::GenericParam`s
776 // instead of `ast::GenericParam`s.
777 // This should only be used with generics that have already had their
778 // in-band lifetimes added. In practice, this means that this function is
779 // only used when lowering a child item of a trait or impl.
780 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
781 params: &HirVec<hir::GenericParam>,
784 F: FnOnce(&mut LoweringContext) -> T,
786 let old_len = self.in_scope_lifetimes.len();
787 let lt_def_names = params.iter().filter_map(|param| match param.kind {
788 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
791 self.in_scope_lifetimes.extend(lt_def_names);
795 self.in_scope_lifetimes.truncate(old_len);
799 /// Appends in-band lifetime defs and argument-position `impl
800 /// Trait` defs to the existing set of generics.
802 /// Presuming that in-band lifetimes are enabled, then
803 /// `self.anonymous_lifetime_mode` will be updated to match the
804 /// argument while `f` is running (and restored afterwards).
805 fn add_in_band_defs<F, T>(
809 anonymous_lifetime_mode: AnonymousLifetimeMode,
811 ) -> (hir::Generics, T)
813 F: FnOnce(&mut LoweringContext, &mut Vec<hir::GenericParam>) -> T,
815 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
818 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
819 let mut params = Vec::new();
820 let generics = this.lower_generics(
822 ImplTraitContext::Universal(&mut params),
824 let res = f(this, &mut params);
825 (params, (generics, res))
830 lowered_generics.params = lowered_generics
837 (lowered_generics, res)
840 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
842 F: FnOnce(&mut LoweringContext) -> T,
844 let len = self.catch_scopes.len();
845 self.catch_scopes.push(catch_id);
847 let result = f(self);
850 self.catch_scopes.len(),
851 "catch scopes should be added and removed in stack order"
854 self.catch_scopes.pop().unwrap();
861 capture_clause: CaptureBy,
862 closure_node_id: NodeId,
864 body: impl FnOnce(&mut LoweringContext) -> hir::Expr,
866 let prev_is_generator = mem::replace(&mut self.is_generator, true);
867 let body_expr = body(self);
868 let span = body_expr.span;
869 let output = match ret_ty {
870 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
871 None => FunctionRetTy::Default(span),
878 let body_id = self.record_body(body_expr, Some(&decl));
879 self.is_generator = prev_is_generator;
881 let capture_clause = self.lower_capture_clause(capture_clause);
882 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
883 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
884 let generator = hir::Expr {
886 hir_id: closure_hir_id,
887 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
888 Some(hir::GeneratorMovability::Static)),
890 attrs: ThinVec::new(),
893 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
894 let gen_future = self.expr_std_path(
895 unstable_span, &["future", "from_generator"], None, ThinVec::new());
896 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
899 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
901 F: FnOnce(&mut LoweringContext) -> hir::Expr,
903 let prev = mem::replace(&mut self.is_generator, false);
904 let result = f(self);
905 let r = self.record_body(result, decl);
906 self.is_generator = prev;
910 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
912 F: FnOnce(&mut LoweringContext) -> T,
914 // We're no longer in the base loop's condition; we're in another loop.
915 let was_in_loop_condition = self.is_in_loop_condition;
916 self.is_in_loop_condition = false;
918 let len = self.loop_scopes.len();
919 self.loop_scopes.push(loop_id);
921 let result = f(self);
924 self.loop_scopes.len(),
925 "Loop scopes should be added and removed in stack order"
928 self.loop_scopes.pop().unwrap();
930 self.is_in_loop_condition = was_in_loop_condition;
935 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
937 F: FnOnce(&mut LoweringContext) -> T,
939 let was_in_loop_condition = self.is_in_loop_condition;
940 self.is_in_loop_condition = true;
942 let result = f(self);
944 self.is_in_loop_condition = was_in_loop_condition;
949 fn with_new_scopes<T, F>(&mut self, f: F) -> T
951 F: FnOnce(&mut LoweringContext) -> T,
953 let was_in_loop_condition = self.is_in_loop_condition;
954 self.is_in_loop_condition = false;
956 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
957 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
958 let result = f(self);
959 self.catch_scopes = catch_scopes;
960 self.loop_scopes = loop_scopes;
962 self.is_in_loop_condition = was_in_loop_condition;
967 fn def_key(&mut self, id: DefId) -> DefKey {
969 self.resolver.definitions().def_key(id.index)
971 self.cstore.def_key(id)
975 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
976 label.map(|label| hir::Label {
981 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
982 let target_id = match destination {
984 if let Def::Label(loop_id) = self.expect_full_def(id) {
985 Ok(self.lower_node_id(loop_id).node_id)
987 Err(hir::LoopIdError::UnresolvedLabel)
994 .map(|id| Ok(self.lower_node_id(id).node_id))
995 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1000 label: self.lower_label(destination.map(|(_, label)| label)),
1005 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1008 .map(|a| self.lower_attr(a))
1009 .collect::<Vec<_>>()
1013 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1017 path: attr.path.clone(),
1018 tokens: self.lower_token_stream(attr.tokens.clone()),
1019 is_sugared_doc: attr.is_sugared_doc,
1024 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1027 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1031 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1033 TokenTree::Token(span, token) => self.lower_token(token, span),
1034 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1037 delim: delimited.delim,
1038 tts: self.lower_token_stream(delimited.tts.into()).into(),
1044 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1046 Token::Interpolated(_) => {}
1047 other => return TokenTree::Token(span, other).into(),
1050 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1051 self.lower_token_stream(tts)
1054 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1056 attrs: self.lower_attrs(&arm.attrs),
1057 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1058 guard: match arm.guard {
1059 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1062 body: P(self.lower_expr(&arm.body)),
1066 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1068 id: self.lower_node_id(b.id).node_id,
1070 ty: self.lower_ty(&b.ty, itctx),
1075 fn lower_generic_arg(&mut self,
1076 arg: &ast::GenericArg,
1077 itctx: ImplTraitContext)
1078 -> hir::GenericArg {
1080 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1081 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1085 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1086 P(self.lower_ty_direct(t, itctx))
1089 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext) -> hir::Ty {
1090 let kind = match t.node {
1091 TyKind::Infer => hir::TyKind::Infer,
1092 TyKind::Err => hir::TyKind::Err,
1093 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1094 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1095 TyKind::Rptr(ref region, ref mt) => {
1096 let span = t.span.shrink_to_lo();
1097 let lifetime = match *region {
1098 Some(ref lt) => self.lower_lifetime(lt),
1099 None => self.elided_ref_lifetime(span),
1101 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1103 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1106 this.with_anonymous_lifetime_mode(
1107 AnonymousLifetimeMode::PassThrough,
1109 hir::TyKind::BareFn(P(hir::BareFnTy {
1110 generic_params: this.lower_generic_params(
1113 ImplTraitContext::Disallowed,
1115 unsafety: this.lower_unsafety(f.unsafety),
1117 decl: this.lower_fn_decl(&f.decl, None, false, None),
1118 arg_names: this.lower_fn_args_to_names(&f.decl),
1124 TyKind::Never => hir::TyKind::Never,
1125 TyKind::Tup(ref tys) => {
1126 hir::TyKind::Tup(tys.iter().map(|ty| {
1127 self.lower_ty_direct(ty, itctx.reborrow())
1130 TyKind::Paren(ref ty) => {
1131 return self.lower_ty_direct(ty, itctx);
1133 TyKind::Path(ref qself, ref path) => {
1134 let id = self.lower_node_id(t.id);
1135 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1136 let ty = self.ty_path(id, t.span, qpath);
1137 if let hir::TyKind::TraitObject(..) = ty.node {
1138 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1142 TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1145 def: self.expect_full_def(t.id),
1146 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1150 TyKind::Array(ref ty, ref length) => {
1151 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1153 TyKind::Typeof(ref expr) => {
1154 hir::TyKind::Typeof(self.lower_anon_const(expr))
1156 TyKind::TraitObject(ref bounds, kind) => {
1157 let mut lifetime_bound = None;
1160 .filter_map(|bound| match *bound {
1161 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1162 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1164 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1165 GenericBound::Outlives(ref lifetime) => {
1166 if lifetime_bound.is_none() {
1167 lifetime_bound = Some(self.lower_lifetime(lifetime));
1173 let lifetime_bound =
1174 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1175 if kind != TraitObjectSyntax::Dyn {
1176 self.maybe_lint_bare_trait(t.span, t.id, false);
1178 hir::TyKind::TraitObject(bounds, lifetime_bound)
1180 TyKind::ImplTrait(def_node_id, ref bounds) => {
1183 ImplTraitContext::Existential(fn_def_id) => {
1184 self.lower_existential_impl_trait(
1185 span, fn_def_id, def_node_id,
1186 |this| this.lower_param_bounds(bounds, itctx),
1189 ImplTraitContext::Universal(in_band_ty_params) => {
1190 self.lower_node_id(def_node_id);
1191 // Add a definition for the in-band Param
1192 let def_index = self
1195 .opt_def_index(def_node_id)
1198 let hir_bounds = self.lower_param_bounds(
1200 ImplTraitContext::Universal(in_band_ty_params),
1202 // Set the name to `impl Bound1 + Bound2`
1203 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1204 in_band_ty_params.push(hir::GenericParam {
1206 name: ParamName::Plain(ident),
1207 pure_wrt_drop: false,
1211 kind: hir::GenericParamKind::Type {
1213 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1217 hir::TyKind::Path(hir::QPath::Resolved(
1221 def: Def::TyParam(DefId::local(def_index)),
1222 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1226 ImplTraitContext::Disallowed => {
1231 "`impl Trait` not allowed outside of function \
1232 and inherent method return types"
1238 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1241 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1250 fn lower_existential_impl_trait(
1254 exist_ty_node_id: NodeId,
1255 lower_bounds: impl FnOnce(&mut LoweringContext) -> hir::GenericBounds,
1257 // Make sure we know that some funky desugaring has been going on here.
1258 // This is a first: there is code in other places like for loop
1259 // desugaring that explicitly states that we don't want to track that.
1260 // Not tracking it makes lints in rustc and clippy very fragile as
1261 // frequently opened issues show.
1262 let exist_ty_span = self.allow_internal_unstable(
1263 CompilerDesugaringKind::ExistentialReturnType,
1267 let exist_ty_def_index = self
1270 .opt_def_index(exist_ty_node_id)
1274 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1276 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1278 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1284 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1285 let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1286 generics: hir::Generics {
1287 params: lifetime_defs,
1288 where_clause: hir::WhereClause {
1289 id: lctx.next_id().node_id,
1290 predicates: Vec::new().into(),
1295 impl_trait_fn: Some(fn_def_id),
1297 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1298 // Generate an `existential type Foo: Trait;` declaration
1299 trace!("creating existential type with id {:#?}", exist_ty_id);
1301 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1302 let exist_ty_item = hir::Item {
1303 id: exist_ty_id.node_id,
1304 hir_id: exist_ty_id.hir_id,
1305 name: keywords::Invalid.name(),
1306 attrs: Default::default(),
1307 node: exist_ty_item_kind,
1308 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1309 span: exist_ty_span,
1312 // Insert the item into the global list. This usually happens
1313 // automatically for all AST items. But this existential type item
1314 // does not actually exist in the AST.
1315 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1317 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1318 let path = P(hir::Path {
1319 span: exist_ty_span,
1320 def: Def::Existential(DefId::local(exist_ty_def_index)),
1321 segments: hir_vec![hir::PathSegment {
1323 ident: Ident::new(keywords::Invalid.name(), exist_ty_span),
1324 args: Some(P(hir::GenericArgs {
1325 parenthesized: false,
1326 bindings: HirVec::new(),
1331 hir::TyKind::Path(hir::QPath::Resolved(None, path))
1335 fn lifetimes_from_impl_trait_bounds(
1337 exist_ty_id: NodeId,
1338 parent_index: DefIndex,
1339 bounds: &hir::GenericBounds,
1340 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1341 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1342 // appear in the bounds, excluding lifetimes that are created within the bounds.
1343 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1344 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1345 context: &'r mut LoweringContext<'a>,
1347 exist_ty_id: NodeId,
1348 collect_elided_lifetimes: bool,
1349 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1350 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1351 output_lifetimes: Vec<hir::GenericArg>,
1352 output_lifetime_params: Vec<hir::GenericParam>,
1355 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1356 fn nested_visit_map<'this>(
1358 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1359 hir::intravisit::NestedVisitorMap::None
1362 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1363 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1364 if parameters.parenthesized {
1365 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1366 self.collect_elided_lifetimes = false;
1367 hir::intravisit::walk_generic_args(self, span, parameters);
1368 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1370 hir::intravisit::walk_generic_args(self, span, parameters);
1374 fn visit_ty(&mut self, t: &'v hir::Ty) {
1375 // Don't collect elided lifetimes used inside of `fn()` syntax
1376 if let hir::TyKind::BareFn(_) = t.node {
1377 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1378 self.collect_elided_lifetimes = false;
1380 // Record the "stack height" of `for<'a>` lifetime bindings
1381 // to be able to later fully undo their introduction.
1382 let old_len = self.currently_bound_lifetimes.len();
1383 hir::intravisit::walk_ty(self, t);
1384 self.currently_bound_lifetimes.truncate(old_len);
1386 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1388 hir::intravisit::walk_ty(self, t)
1392 fn visit_poly_trait_ref(
1394 trait_ref: &'v hir::PolyTraitRef,
1395 modifier: hir::TraitBoundModifier,
1397 // Record the "stack height" of `for<'a>` lifetime bindings
1398 // to be able to later fully undo their introduction.
1399 let old_len = self.currently_bound_lifetimes.len();
1400 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1401 self.currently_bound_lifetimes.truncate(old_len);
1404 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1405 // Record the introduction of 'a in `for<'a> ...`
1406 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1407 // Introduce lifetimes one at a time so that we can handle
1408 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1409 let lt_name = hir::LifetimeName::Param(param.name);
1410 self.currently_bound_lifetimes.push(lt_name);
1413 hir::intravisit::walk_generic_param(self, param);
1416 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1417 let name = match lifetime.name {
1418 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1419 if self.collect_elided_lifetimes {
1420 // Use `'_` for both implicit and underscore lifetimes in
1421 // `abstract type Foo<'_>: SomeTrait<'_>;`
1422 hir::LifetimeName::Underscore
1427 hir::LifetimeName::Param(_) => lifetime.name,
1428 hir::LifetimeName::Static => return,
1431 if !self.currently_bound_lifetimes.contains(&name)
1432 && !self.already_defined_lifetimes.contains(&name) {
1433 self.already_defined_lifetimes.insert(name);
1435 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1436 id: self.context.next_id().node_id,
1437 span: lifetime.span,
1441 // We need to manually create the ids here, because the
1442 // definitions will go into the explicit `existential type`
1443 // declaration and thus need to have their owner set to that item
1444 let def_node_id = self.context.sess.next_node_id();
1445 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1446 self.context.resolver.definitions().create_def_with_parent(
1449 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1450 DefIndexAddressSpace::High,
1455 let name = match name {
1456 hir::LifetimeName::Underscore => {
1457 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident())
1459 hir::LifetimeName::Param(param_name) => param_name,
1460 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1463 self.output_lifetime_params.push(hir::GenericParam {
1466 span: lifetime.span,
1467 pure_wrt_drop: false,
1470 kind: hir::GenericParamKind::Lifetime {
1478 let mut lifetime_collector = ImplTraitLifetimeCollector {
1480 parent: parent_index,
1482 collect_elided_lifetimes: true,
1483 currently_bound_lifetimes: Vec::new(),
1484 already_defined_lifetimes: FxHashSet::default(),
1485 output_lifetimes: Vec::new(),
1486 output_lifetime_params: Vec::new(),
1489 for bound in bounds {
1490 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1494 lifetime_collector.output_lifetimes.into(),
1495 lifetime_collector.output_lifetime_params.into(),
1499 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1504 .map(|x| self.lower_foreign_item(x))
1509 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1516 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1518 node: hir::VariantKind {
1519 name: v.node.ident.name,
1520 attrs: self.lower_attrs(&v.node.attrs),
1521 data: self.lower_variant_data(&v.node.data),
1522 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1531 qself: &Option<QSelf>,
1533 param_mode: ParamMode,
1534 mut itctx: ImplTraitContext,
1536 let qself_position = qself.as_ref().map(|q| q.position);
1537 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1539 let resolution = self.resolver
1541 .unwrap_or(PathResolution::new(Def::Err));
1543 let proj_start = p.segments.len() - resolution.unresolved_segments();
1544 let path = P(hir::Path {
1545 def: resolution.base_def(),
1546 segments: p.segments[..proj_start]
1549 .map(|(i, segment)| {
1550 let param_mode = match (qself_position, param_mode) {
1551 (Some(j), ParamMode::Optional) if i < j => {
1552 // This segment is part of the trait path in a
1553 // qualified path - one of `a`, `b` or `Trait`
1554 // in `<X as a::b::Trait>::T::U::method`.
1560 // Figure out if this is a type/trait segment,
1561 // which may need lifetime elision performed.
1562 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1563 krate: def_id.krate,
1564 index: this.def_key(def_id).parent.expect("missing parent"),
1566 let type_def_id = match resolution.base_def() {
1567 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1568 Some(parent_def_id(self, def_id))
1570 Def::Variant(def_id) if i + 1 == proj_start => {
1571 Some(parent_def_id(self, def_id))
1574 | Def::Union(def_id)
1576 | Def::TyAlias(def_id)
1577 | Def::Trait(def_id) if i + 1 == proj_start =>
1583 let parenthesized_generic_args = match resolution.base_def() {
1584 // `a::b::Trait(Args)`
1585 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1586 // `a::b::Trait(Args)::TraitItem`
1587 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1588 if i + 2 == proj_start =>
1590 ParenthesizedGenericArgs::Ok
1592 // Avoid duplicated errors
1593 Def::Err => ParenthesizedGenericArgs::Ok,
1599 | Def::Variant(..) if i + 1 == proj_start =>
1601 ParenthesizedGenericArgs::Err
1603 // A warning for now, for compatibility reasons
1604 _ => ParenthesizedGenericArgs::Warn,
1607 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1608 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1611 assert!(!def_id.is_local());
1613 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1614 let n = item_generics.own_counts().lifetimes;
1615 self.type_def_lifetime_params.insert(def_id, n);
1618 self.lower_path_segment(
1623 parenthesized_generic_args,
1631 // Simple case, either no projections, or only fully-qualified.
1632 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1633 if resolution.unresolved_segments() == 0 {
1634 return hir::QPath::Resolved(qself, path);
1637 // Create the innermost type that we're projecting from.
1638 let mut ty = if path.segments.is_empty() {
1639 // If the base path is empty that means there exists a
1640 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1641 qself.expect("missing QSelf for <T>::...")
1643 // Otherwise, the base path is an implicit `Self` type path,
1644 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1645 // `<I as Iterator>::Item::default`.
1646 let new_id = self.next_id();
1647 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1650 // Anything after the base path are associated "extensions",
1651 // out of which all but the last one are associated types,
1652 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1653 // * base path is `std::vec::Vec<T>`
1654 // * "extensions" are `IntoIter`, `Item` and `clone`
1655 // * type nodes are:
1656 // 1. `std::vec::Vec<T>` (created above)
1657 // 2. `<std::vec::Vec<T>>::IntoIter`
1658 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1659 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1660 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1661 let segment = P(self.lower_path_segment(
1666 ParenthesizedGenericArgs::Warn,
1669 let qpath = hir::QPath::TypeRelative(ty, segment);
1671 // It's finished, return the extension of the right node type.
1672 if i == p.segments.len() - 1 {
1676 // Wrap the associated extension in another type node.
1677 let new_id = self.next_id();
1678 ty = P(self.ty_path(new_id, p.span, qpath));
1681 // Should've returned in the for loop above.
1684 "lower_qpath: no final extension segment in {}..{}",
1690 fn lower_path_extra(
1694 ident: Option<Ident>,
1695 param_mode: ParamMode,
1699 segments: p.segments
1702 self.lower_path_segment(
1707 ParenthesizedGenericArgs::Err,
1708 ImplTraitContext::Disallowed,
1711 .chain(ident.map(|ident| hir::PathSegment::from_ident(ident)))
1717 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1718 let def = self.expect_full_def(id);
1719 self.lower_path_extra(def, p, None, param_mode)
1722 fn lower_path_segment(
1725 segment: &PathSegment,
1726 param_mode: ParamMode,
1727 expected_lifetimes: usize,
1728 parenthesized_generic_args: ParenthesizedGenericArgs,
1729 itctx: ImplTraitContext,
1730 ) -> hir::PathSegment {
1731 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1732 let msg = "parenthesized parameters may only be used with a trait";
1733 match **generic_args {
1734 GenericArgs::AngleBracketed(ref data) => {
1735 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1737 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1738 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1739 ParenthesizedGenericArgs::Warn => {
1740 self.sess.buffer_lint(
1741 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1746 (hir::GenericArgs::none(), true)
1748 ParenthesizedGenericArgs::Err => {
1749 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1750 .span_label(data.span, "only traits may use parentheses")
1752 (hir::GenericArgs::none(), true)
1757 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1760 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1761 GenericArg::Lifetime(_) => true,
1764 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1765 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1766 if !generic_args.parenthesized && !has_lifetimes {
1768 self.elided_path_lifetimes(path_span, expected_lifetimes)
1770 .map(|lt| GenericArg::Lifetime(lt))
1771 .chain(generic_args.args.into_iter())
1773 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1774 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1775 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1776 let no_bindings = generic_args.bindings.is_empty();
1777 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1778 // If there are no (non-implicit) generic args or associated-type
1779 // bindings, our suggestion includes the angle brackets
1780 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1782 // Otherwise—sorry, this is kind of gross—we need to infer the
1783 // place to splice in the `'_, ` from the generics that do exist
1784 let first_generic_span = first_generic_span
1785 .expect("already checked that type args or bindings exist");
1786 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1788 self.sess.buffer_lint_with_diagnostic(
1789 ELIDED_LIFETIMES_IN_PATHS,
1792 "hidden lifetime parameters in types are deprecated",
1793 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1794 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1800 hir::PathSegment::new(
1807 fn lower_angle_bracketed_parameter_data(
1809 data: &AngleBracketedArgs,
1810 param_mode: ParamMode,
1811 mut itctx: ImplTraitContext,
1812 ) -> (hir::GenericArgs, bool) {
1813 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1814 let has_types = args.iter().any(|arg| match arg {
1815 ast::GenericArg::Type(_) => true,
1819 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1820 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1821 parenthesized: false,
1823 !has_types && param_mode == ParamMode::Optional)
1826 fn lower_parenthesized_parameter_data(
1828 data: &ParenthesisedArgs,
1829 ) -> (hir::GenericArgs, bool) {
1830 // Switch to `PassThrough` mode for anonymous lifetimes: this
1831 // means that we permit things like `&Ref<T>`, where `Ref` has
1832 // a hidden lifetime parameter. This is needed for backwards
1833 // compatibility, even in contexts like an impl header where
1834 // we generally don't permit such things (see #51008).
1835 self.with_anonymous_lifetime_mode(
1836 AnonymousLifetimeMode::PassThrough,
1838 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1839 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1840 let inputs = inputs.iter().map(|ty| this.lower_ty_direct(ty, DISALLOWED)).collect();
1841 let mk_tup = |this: &mut Self, tys, span| {
1842 let LoweredNodeId { node_id, hir_id } = this.next_id();
1843 hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1848 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1851 id: this.next_id().node_id,
1852 ident: Ident::from_str(FN_OUTPUT_NAME),
1855 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1856 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1857 span: output.as_ref().map_or(span, |ty| ty.span),
1860 parenthesized: true,
1868 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1869 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1875 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1876 pat: self.lower_pat(&l.pat),
1877 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1879 attrs: l.attrs.clone(),
1880 source: hir::LocalSource::Normal,
1884 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1886 Mutability::Mutable => hir::MutMutable,
1887 Mutability::Immutable => hir::MutImmutable,
1891 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1892 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1896 pat: self.lower_pat(&arg.pat),
1900 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1903 .map(|arg| match arg.pat.node {
1904 PatKind::Ident(_, ident, _) => ident,
1905 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
1910 // Lowers a function declaration.
1912 // decl: the unlowered (ast) function declaration.
1913 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1914 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1915 // make_ret_async is also `Some`.
1916 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1917 // This guards against trait declarations and implementations where impl Trait is
1919 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1920 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
1921 // return type impl Trait item.
1925 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
1926 impl_trait_return_allow: bool,
1927 make_ret_async: Option<NodeId>,
1928 ) -> P<hir::FnDecl> {
1929 let inputs = decl.inputs
1932 if let Some((_, ref mut ibty)) = in_band_ty_params {
1933 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
1935 self.lower_ty_direct(&arg.ty, ImplTraitContext::Disallowed)
1938 .collect::<HirVec<_>>();
1940 let output = if let Some(ret_id) = make_ret_async {
1941 self.lower_async_fn_ret_ty(
1944 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
1949 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
1950 Some((def_id, _)) if impl_trait_return_allow => {
1951 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1953 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1955 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1962 variadic: decl.variadic,
1963 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1964 TyKind::ImplicitSelf => true,
1965 TyKind::Rptr(_, ref mt) => mt.ty.node.is_implicit_self(),
1971 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
1973 // fn_span: the span of the async function declaration. Used for error reporting.
1974 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
1975 // output: unlowered output type (`T` in `-> T`)
1976 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
1977 fn lower_async_fn_ret_ty(
1980 output: &FunctionRetTy,
1982 return_impl_trait_id: NodeId,
1983 ) -> hir::FunctionRetTy {
1984 // Get lifetimes used in the input arguments to the function. Our output type must also
1985 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
1986 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
1987 // is a subset of the other. We really want some new lifetime that is a subset of all input
1988 // lifetimes, but that doesn't exist at the moment.
1990 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
1991 context: &'r mut LoweringContext<'a>,
1992 // Lifetimes bound by HRTB
1993 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1994 // Whether to count elided lifetimes.
1995 // Disabled inside of `Fn` or `fn` syntax.
1996 collect_elided_lifetimes: bool,
1997 // The lifetime found.
1998 // Multiple different or elided lifetimes cannot appear in async fn for now.
1999 output_lifetime: Option<(hir::LifetimeName, Span)>,
2002 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
2003 fn nested_visit_map<'this>(
2005 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
2006 hir::intravisit::NestedVisitorMap::None
2009 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
2010 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2011 if parameters.parenthesized {
2012 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2013 self.collect_elided_lifetimes = false;
2014 hir::intravisit::walk_generic_args(self, span, parameters);
2015 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2017 hir::intravisit::walk_generic_args(self, span, parameters);
2021 fn visit_ty(&mut self, t: &'v hir::Ty) {
2022 // Don't collect elided lifetimes used inside of `fn()` syntax
2023 if let &hir::TyKind::BareFn(_) = &t.node {
2024 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2025 self.collect_elided_lifetimes = false;
2027 // Record the "stack height" of `for<'a>` lifetime bindings
2028 // to be able to later fully undo their introduction.
2029 let old_len = self.currently_bound_lifetimes.len();
2030 hir::intravisit::walk_ty(self, t);
2031 self.currently_bound_lifetimes.truncate(old_len);
2033 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2035 hir::intravisit::walk_ty(self, t);
2039 fn visit_poly_trait_ref(
2041 trait_ref: &'v hir::PolyTraitRef,
2042 modifier: hir::TraitBoundModifier,
2044 // Record the "stack height" of `for<'a>` lifetime bindings
2045 // to be able to later fully undo their introduction.
2046 let old_len = self.currently_bound_lifetimes.len();
2047 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2048 self.currently_bound_lifetimes.truncate(old_len);
2051 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2052 // Record the introduction of 'a in `for<'a> ...`
2053 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2054 // Introduce lifetimes one at a time so that we can handle
2055 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2056 let lt_name = hir::LifetimeName::Param(param.name);
2057 self.currently_bound_lifetimes.push(lt_name);
2060 hir::intravisit::walk_generic_param(self, param);
2063 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2064 let name = match lifetime.name {
2065 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2066 if self.collect_elided_lifetimes {
2067 // Use `'_` for both implicit and underscore lifetimes in
2068 // `abstract type Foo<'_>: SomeTrait<'_>;`
2069 hir::LifetimeName::Underscore
2074 hir::LifetimeName::Param(_) => lifetime.name,
2075 hir::LifetimeName::Static => return,
2078 if !self.currently_bound_lifetimes.contains(&name) {
2079 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2080 // We don't currently have a reliable way to desugar `async fn` with
2081 // multiple potentially unrelated input lifetimes into
2082 // `-> impl Trait + 'lt`, so we report an error in this case.
2083 if current_lt_name != name {
2086 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2088 "multiple different lifetimes used in arguments of `async fn`",
2090 .span_label(current_lt_span, "first lifetime here")
2091 .span_label(lifetime.span, "different lifetime here")
2092 .help("`async fn` can only accept borrowed values \
2093 with identical lifetimes")
2095 } else if current_lt_name.is_elided() && name.is_elided() {
2098 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2100 "multiple elided lifetimes used in arguments of `async fn`",
2102 .span_label(current_lt_span, "first lifetime here")
2103 .span_label(lifetime.span, "different lifetime here")
2104 .help("consider giving these arguments named lifetimes")
2108 self.output_lifetime = Some((name, lifetime.span));
2114 let bound_lifetime = {
2115 let mut lifetime_collector = AsyncFnLifetimeCollector {
2117 currently_bound_lifetimes: Vec::new(),
2118 collect_elided_lifetimes: true,
2119 output_lifetime: None,
2123 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2125 lifetime_collector.output_lifetime
2128 let span = match output {
2129 FunctionRetTy::Ty(ty) => ty.span,
2130 FunctionRetTy::Default(span) => *span,
2133 let impl_trait_ty = self.lower_existential_impl_trait(
2134 span, fn_def_id, return_impl_trait_id, |this| {
2135 let output_ty = match output {
2136 FunctionRetTy::Ty(ty) =>
2137 this.lower_ty(ty, ImplTraitContext::Existential(fn_def_id)),
2138 FunctionRetTy::Default(span) => {
2139 let LoweredNodeId { node_id, hir_id } = this.next_id();
2143 node: hir::TyKind::Tup(hir_vec![]),
2150 let future_params = P(hir::GenericArgs {
2152 bindings: hir_vec![hir::TypeBinding {
2153 ident: Ident::from_str(FN_OUTPUT_NAME),
2155 id: this.next_id().node_id,
2158 parenthesized: false,
2162 this.std_path(span, &["future", "Future"], Some(future_params), false);
2164 let LoweredNodeId { node_id, hir_id } = this.next_id();
2165 let mut bounds = vec![
2166 hir::GenericBound::Trait(
2168 trait_ref: hir::TraitRef {
2173 bound_generic_params: hir_vec![],
2176 hir::TraitBoundModifier::None
2180 if let Some((name, span)) = bound_lifetime {
2181 bounds.push(hir::GenericBound::Outlives(
2182 hir::Lifetime { id: this.next_id().node_id, name, span }));
2185 hir::HirVec::from(bounds)
2188 let LoweredNodeId { node_id, hir_id } = self.next_id();
2189 let impl_trait_ty = P(hir::Ty {
2191 node: impl_trait_ty,
2196 hir::FunctionRetTy::Return(impl_trait_ty)
2199 fn lower_param_bound(
2202 itctx: ImplTraitContext,
2203 ) -> hir::GenericBound {
2205 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2206 self.lower_poly_trait_ref(ty, itctx),
2207 self.lower_trait_bound_modifier(modifier),
2209 GenericBound::Outlives(ref lifetime) => {
2210 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2215 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2216 let span = l.ident.span;
2218 ident if ident.name == keywords::StaticLifetime.name() =>
2219 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2220 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2221 match self.anonymous_lifetime_mode {
2222 AnonymousLifetimeMode::CreateParameter => {
2223 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2224 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2227 AnonymousLifetimeMode::PassThrough => {
2228 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2232 self.maybe_collect_in_band_lifetime(ident);
2233 let param_name = ParamName::Plain(ident);
2234 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2239 fn new_named_lifetime(
2243 name: hir::LifetimeName,
2244 ) -> hir::Lifetime {
2246 id: self.lower_node_id(id).node_id,
2252 fn lower_generic_params(
2254 params: &[GenericParam],
2255 add_bounds: &NodeMap<Vec<GenericBound>>,
2256 mut itctx: ImplTraitContext,
2257 ) -> hir::HirVec<hir::GenericParam> {
2258 params.iter().map(|param| {
2259 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2263 fn lower_generic_param(&mut self,
2264 param: &GenericParam,
2265 add_bounds: &NodeMap<Vec<GenericBound>>,
2266 mut itctx: ImplTraitContext)
2267 -> hir::GenericParam {
2268 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx.reborrow());
2270 GenericParamKind::Lifetime => {
2271 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2272 self.is_collecting_in_band_lifetimes = false;
2274 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
2275 let param_name = match lt.name {
2276 hir::LifetimeName::Param(param_name) => param_name,
2277 _ => hir::ParamName::Plain(lt.name.ident()),
2279 let param = hir::GenericParam {
2283 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2284 attrs: self.lower_attrs(¶m.attrs),
2286 kind: hir::GenericParamKind::Lifetime { in_band: false }
2289 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2293 GenericParamKind::Type { ref default, .. } => {
2294 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2295 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2296 // Instead, use gensym("Self") to create a distinct name that looks the same.
2297 let ident = if param.ident.name == keywords::SelfType.name() {
2298 param.ident.gensym()
2303 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2304 if !add_bounds.is_empty() {
2305 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2306 bounds = bounds.into_iter()
2312 id: self.lower_node_id(param.id).node_id,
2313 name: hir::ParamName::Plain(ident),
2314 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2315 attrs: self.lower_attrs(¶m.attrs),
2318 kind: hir::GenericParamKind::Type {
2319 default: default.as_ref().map(|x| {
2320 self.lower_ty(x, ImplTraitContext::Disallowed)
2322 synthetic: param.attrs.iter()
2323 .filter(|attr| attr.check_name("rustc_synthetic"))
2324 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2334 generics: &Generics,
2335 itctx: ImplTraitContext)
2338 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2339 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2340 // paths where report_error is called are also the only paths that advance to after
2341 // the match statement, so the error reporting could probably just be moved there.
2342 let mut add_bounds: NodeMap<Vec<_>> = NodeMap();
2343 for pred in &generics.where_clause.predicates {
2344 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2345 'next_bound: for bound in &bound_pred.bounds {
2346 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2347 let report_error = |this: &mut Self| {
2348 this.diagnostic().span_err(
2349 bound_pred.bounded_ty.span,
2350 "`?Trait` bounds are only permitted at the \
2351 point where a type parameter is declared",
2354 // Check if the where clause type is a plain type parameter.
2355 match bound_pred.bounded_ty.node {
2356 TyKind::Path(None, ref path)
2357 if path.segments.len() == 1
2358 && bound_pred.bound_generic_params.is_empty() =>
2360 if let Some(Def::TyParam(def_id)) = self.resolver
2361 .get_resolution(bound_pred.bounded_ty.id)
2362 .map(|d| d.base_def())
2364 if let Some(node_id) =
2365 self.resolver.definitions().as_local_node_id(def_id)
2367 for param in &generics.params {
2369 GenericParamKind::Type { .. } => {
2370 if node_id == param.id {
2371 add_bounds.entry(param.id)
2373 .push(bound.clone());
2374 continue 'next_bound;
2384 _ => report_error(self),
2392 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2393 where_clause: self.lower_where_clause(&generics.where_clause),
2394 span: generics.span,
2398 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2400 id: self.lower_node_id(wc.id).node_id,
2401 predicates: wc.predicates
2403 .map(|predicate| self.lower_where_predicate(predicate))
2408 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2410 WherePredicate::BoundPredicate(WhereBoundPredicate {
2411 ref bound_generic_params,
2416 self.with_in_scope_lifetime_defs(
2417 &bound_generic_params,
2419 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2420 bound_generic_params: this.lower_generic_params(
2421 bound_generic_params,
2423 ImplTraitContext::Disallowed,
2425 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2428 .filter_map(|bound| match *bound {
2429 // Ignore `?Trait` bounds.
2430 // Tthey were copied into type parameters already.
2431 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2432 _ => Some(this.lower_param_bound(
2434 ImplTraitContext::Disallowed,
2443 WherePredicate::RegionPredicate(WhereRegionPredicate {
2447 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2449 lifetime: self.lower_lifetime(lifetime),
2450 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2452 WherePredicate::EqPredicate(WhereEqPredicate {
2457 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2458 id: self.lower_node_id(id).node_id,
2459 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2460 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2466 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2468 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2472 .map(|f| self.lower_struct_field(f))
2474 self.lower_node_id(id).node_id,
2476 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2480 .map(|f| self.lower_struct_field(f))
2482 self.lower_node_id(id).node_id,
2484 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2488 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2489 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2490 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2491 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2493 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.ref_id);
2501 fn lower_poly_trait_ref(
2504 mut itctx: ImplTraitContext,
2505 ) -> hir::PolyTraitRef {
2506 let bound_generic_params =
2507 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx.reborrow());
2508 let trait_ref = self.with_parent_impl_lifetime_defs(
2509 &bound_generic_params,
2510 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2514 bound_generic_params,
2520 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2523 id: self.lower_node_id(f.id).node_id,
2524 ident: match f.ident {
2525 Some(ident) => ident,
2526 // FIXME(jseyfried) positional field hygiene
2527 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2529 vis: self.lower_visibility(&f.vis, None),
2530 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2531 attrs: self.lower_attrs(&f.attrs),
2535 fn lower_field(&mut self, f: &Field) -> hir::Field {
2537 id: self.next_id().node_id,
2539 expr: P(self.lower_expr(&f.expr)),
2541 is_shorthand: f.is_shorthand,
2545 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2547 ty: self.lower_ty(&mt.ty, itctx),
2548 mutbl: self.lower_mutability(mt.mutbl),
2552 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext)
2553 -> hir::GenericBounds {
2554 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2557 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2558 let mut expr = None;
2560 let mut stmts = vec![];
2562 for (index, stmt) in b.stmts.iter().enumerate() {
2563 if index == b.stmts.len() - 1 {
2564 if let StmtKind::Expr(ref e) = stmt.node {
2565 expr = Some(P(self.lower_expr(e)));
2567 stmts.extend(self.lower_stmt(stmt));
2570 stmts.extend(self.lower_stmt(stmt));
2574 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2579 stmts: stmts.into(),
2581 rules: self.lower_block_check_mode(&b.rules),
2584 recovered: b.recovered,
2588 fn lower_async_body(
2594 self.lower_body(Some(decl), |this| {
2595 if let IsAsync::Async { closure_id, .. } = asyncness {
2596 let async_expr = this.make_async_expr(
2597 CaptureBy::Value, closure_id, None,
2599 let body = this.lower_block(body, false);
2600 this.expr_block(body, ThinVec::new())
2602 this.expr(body.span, async_expr, ThinVec::new())
2604 let body = this.lower_block(body, false);
2605 this.expr_block(body, ThinVec::new())
2614 attrs: &hir::HirVec<Attribute>,
2615 vis: &mut hir::Visibility,
2617 ) -> hir::ItemKind {
2619 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2620 ItemKind::Use(ref use_tree) => {
2621 // Start with an empty prefix
2624 span: use_tree.span,
2627 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2629 ItemKind::Static(ref t, m, ref e) => {
2630 let value = self.lower_body(None, |this| this.lower_expr(e));
2631 hir::ItemKind::Static(
2632 self.lower_ty(t, ImplTraitContext::Disallowed),
2633 self.lower_mutability(m),
2637 ItemKind::Const(ref t, ref e) => {
2638 let value = self.lower_body(None, |this| this.lower_expr(e));
2639 hir::ItemKind::Const(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2641 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2642 let fn_def_id = self.resolver.definitions().local_def_id(id);
2644 self.with_new_scopes(|this| {
2645 // Note: we don't need to change the return type from `T` to
2646 // `impl Future<Output = T>` here because lower_body
2647 // only cares about the input argument patterns in the function
2648 // declaration (decl), not the return types.
2649 let body_id = this.lower_async_body(decl, header.asyncness, body);
2651 let (generics, fn_decl) = this.add_in_band_defs(
2654 AnonymousLifetimeMode::PassThrough,
2655 |this, idty| this.lower_fn_decl(
2656 decl, Some((fn_def_id, idty)), true, header.asyncness.opt_return_id()),
2661 this.lower_fn_header(header),
2667 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2668 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2669 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2670 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2671 self.lower_ty(t, ImplTraitContext::Disallowed),
2672 self.lower_generics(generics, ImplTraitContext::Disallowed),
2674 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2675 generics: self.lower_generics(generics, ImplTraitContext::Disallowed),
2676 bounds: self.lower_param_bounds(b, ImplTraitContext::Disallowed),
2677 impl_trait_fn: None,
2679 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2681 variants: enum_definition
2684 .map(|x| self.lower_variant(x))
2687 self.lower_generics(generics, ImplTraitContext::Disallowed),
2689 ItemKind::Struct(ref struct_def, ref generics) => {
2690 let struct_def = self.lower_variant_data(struct_def);
2691 hir::ItemKind::Struct(
2693 self.lower_generics(generics, ImplTraitContext::Disallowed),
2696 ItemKind::Union(ref vdata, ref generics) => {
2697 let vdata = self.lower_variant_data(vdata);
2698 hir::ItemKind::Union(
2700 self.lower_generics(generics, ImplTraitContext::Disallowed),
2712 let def_id = self.resolver.definitions().local_def_id(id);
2714 // Lower the "impl header" first. This ordering is important
2715 // for in-band lifetimes! Consider `'a` here:
2717 // impl Foo<'a> for u32 {
2718 // fn method(&'a self) { .. }
2721 // Because we start by lowering the `Foo<'a> for u32`
2722 // part, we will add `'a` to the list of generics on
2723 // the impl. When we then encounter it later in the
2724 // method, it will not be considered an in-band
2725 // lifetime to be added, but rather a reference to a
2727 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2730 AnonymousLifetimeMode::CreateParameter,
2732 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2733 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2736 if let Some(ref trait_ref) = trait_ref {
2737 if let Def::Trait(def_id) = trait_ref.path.def {
2738 this.trait_impls.entry(def_id).or_default().push(id);
2742 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2744 (trait_ref, lowered_ty)
2748 let new_impl_items = self.with_in_scope_lifetime_defs(
2749 &ast_generics.params,
2753 .map(|item| this.lower_impl_item_ref(item))
2758 hir::ItemKind::Impl(
2759 self.lower_unsafety(unsafety),
2760 self.lower_impl_polarity(polarity),
2761 self.lower_defaultness(defaultness, true /* [1] */),
2768 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2769 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2772 .map(|item| self.lower_trait_item_ref(item))
2774 hir::ItemKind::Trait(
2775 self.lower_is_auto(is_auto),
2776 self.lower_unsafety(unsafety),
2777 self.lower_generics(generics, ImplTraitContext::Disallowed),
2782 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
2783 self.lower_generics(generics, ImplTraitContext::Disallowed),
2784 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2786 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2789 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2790 // not cause an assertion failure inside the `lower_defaultness` function
2798 vis: &mut hir::Visibility,
2800 attrs: &hir::HirVec<Attribute>,
2801 ) -> hir::ItemKind {
2802 let path = &tree.prefix;
2805 UseTreeKind::Simple(rename, id1, id2) => {
2806 *name = tree.ident().name;
2808 // First apply the prefix to the path
2809 let mut path = Path {
2813 .chain(path.segments.iter())
2819 // Correctly resolve `self` imports
2820 if path.segments.len() > 1
2821 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2823 let _ = path.segments.pop();
2824 if rename.is_none() {
2825 *name = path.segments.last().unwrap().ident.name;
2829 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2830 let mut defs = self.expect_full_def_from_use(id);
2831 // we want to return *something* from this function, so hang onto the first item
2833 let ret_def = defs.next().unwrap_or(Def::Err);
2835 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2836 let vis = vis.clone();
2837 let name = name.clone();
2838 let span = path.span;
2839 self.resolver.definitions().create_def_with_parent(
2843 DefIndexAddressSpace::High,
2846 self.allocate_hir_id_counter(new_node_id, &path);
2848 self.with_hir_id_owner(new_node_id, |this| {
2849 let new_id = this.lower_node_id(new_node_id);
2850 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2851 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
2852 let vis_kind = match vis.node {
2853 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2854 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2855 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2856 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
2857 let id = this.next_id();
2858 hir::VisibilityKind::Restricted {
2860 // We are allocating a new NodeId here
2866 let vis = respan(vis.span, vis_kind);
2872 hir_id: new_id.hir_id,
2874 attrs: attrs.clone(),
2883 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2884 hir::ItemKind::Use(path, hir::UseKind::Single)
2886 UseTreeKind::Glob => {
2887 let path = P(self.lower_path(
2893 .chain(path.segments.iter())
2898 ParamMode::Explicit,
2900 hir::ItemKind::Use(path, hir::UseKind::Glob)
2902 UseTreeKind::Nested(ref trees) => {
2907 .chain(path.segments.iter())
2910 span: prefix.span.to(path.span),
2913 // Add all the nested PathListItems in the HIR
2914 for &(ref use_tree, id) in trees {
2915 self.allocate_hir_id_counter(id, &use_tree);
2919 } = self.lower_node_id(id);
2921 let mut vis = vis.clone();
2922 let mut name = name.clone();
2924 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2926 self.with_hir_id_owner(new_id, |this| {
2927 let vis_kind = match vis.node {
2928 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2929 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2930 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2931 hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
2932 let id = this.next_id();
2933 hir::VisibilityKind::Restricted {
2935 // We are allocating a new NodeId here
2941 let vis = respan(vis.span, vis_kind);
2949 attrs: attrs.clone(),
2952 span: use_tree.span,
2958 // Privatize the degenerate import base, used only to check
2959 // the stability of `use a::{};`, to avoid it showing up as
2960 // a re-export by accident when `pub`, e.g. in documentation.
2961 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2962 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
2963 hir::ItemKind::Use(path, hir::UseKind::ListStem)
2968 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2969 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2970 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2972 let (generics, node) = match i.node {
2973 TraitItemKind::Const(ref ty, ref default) => (
2974 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2975 hir::TraitItemKind::Const(
2976 self.lower_ty(ty, ImplTraitContext::Disallowed),
2979 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2982 TraitItemKind::Method(ref sig, None) => {
2983 let names = self.lower_fn_args_to_names(&sig.decl);
2984 let (generics, sig) = self.lower_method_sig(
2991 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
2993 TraitItemKind::Method(ref sig, Some(ref body)) => {
2994 let body_id = self.lower_body(Some(&sig.decl), |this| {
2995 let body = this.lower_block(body, false);
2996 this.expr_block(body, ThinVec::new())
2999 let (generics, sig) = self.lower_method_sig(
3007 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3009 TraitItemKind::Type(ref bounds, ref default) => (
3010 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3011 hir::TraitItemKind::Type(
3012 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3015 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
3018 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3025 attrs: self.lower_attrs(&i.attrs),
3032 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3033 let (kind, has_default) = match i.node {
3034 TraitItemKind::Const(_, ref default) => {
3035 (hir::AssociatedItemKind::Const, default.is_some())
3037 TraitItemKind::Type(_, ref default) => {
3038 (hir::AssociatedItemKind::Type, default.is_some())
3040 TraitItemKind::Method(ref sig, ref default) => (
3041 hir::AssociatedItemKind::Method {
3042 has_self: sig.decl.has_self(),
3046 TraitItemKind::Macro(..) => unimplemented!(),
3049 id: hir::TraitItemId { node_id: i.id },
3052 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3057 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3058 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3059 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3061 let (generics, node) = match i.node {
3062 ImplItemKind::Const(ref ty, ref expr) => {
3063 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3065 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3066 hir::ImplItemKind::Const(
3067 self.lower_ty(ty, ImplTraitContext::Disallowed),
3072 ImplItemKind::Method(ref sig, ref body) => {
3073 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3074 let impl_trait_return_allow = !self.is_in_trait_impl;
3075 let (generics, sig) = self.lower_method_sig(
3079 impl_trait_return_allow,
3080 sig.header.asyncness.opt_return_id(),
3082 (generics, hir::ImplItemKind::Method(sig, body_id))
3084 ImplItemKind::Type(ref ty) => (
3085 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3086 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
3088 ImplItemKind::Existential(ref bounds) => (
3089 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3090 hir::ImplItemKind::Existential(
3091 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3094 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3101 attrs: self.lower_attrs(&i.attrs),
3103 vis: self.lower_visibility(&i.vis, None),
3104 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3109 // [1] since `default impl` is not yet implemented, this is always true in impls
3112 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3114 id: hir::ImplItemId { node_id: i.id },
3117 vis: self.lower_visibility(&i.vis, Some(i.id)),
3118 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3119 kind: match i.node {
3120 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3121 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3122 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3123 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3124 has_self: sig.decl.has_self(),
3126 ImplItemKind::Macro(..) => unimplemented!(),
3130 // [1] since `default impl` is not yet implemented, this is always true in impls
3133 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3136 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3140 /// Lowers `impl Trait` items and appends them to the list
3141 fn lower_impl_trait_ids(
3145 ids: &mut OneVector<hir::ItemId>,
3147 if let Some(id) = header.asyncness.opt_return_id() {
3148 ids.push(hir::ItemId { id });
3150 struct IdVisitor<'a> { ids: &'a mut OneVector<hir::ItemId> }
3151 impl<'a, 'b> Visitor<'a> for IdVisitor<'b> {
3152 fn visit_ty(&mut self, ty: &'a Ty) {
3158 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
3161 visit::walk_ty(self, ty);
3163 fn visit_path_segment(
3166 path_segment: &'v PathSegment,
3168 if let Some(ref p) = path_segment.args {
3169 if let GenericArgs::Parenthesized(_) = **p {
3173 visit::walk_path_segment(self, path_span, path_segment)
3176 let mut visitor = IdVisitor { ids };
3178 FunctionRetTy::Default(_) => {},
3179 FunctionRetTy::Ty(ref ty) => visitor.visit_ty(ty),
3183 fn lower_item_id(&mut self, i: &Item) -> OneVector<hir::ItemId> {
3185 ItemKind::Use(ref use_tree) => {
3186 let mut vec = smallvec![hir::ItemId { id: i.id }];
3187 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3190 ItemKind::MacroDef(..) => OneVector::new(),
3191 ItemKind::Fn(ref decl, ref header, ..) => {
3192 let mut ids = smallvec![hir::ItemId { id: i.id }];
3193 self.lower_impl_trait_ids(decl, header, &mut ids);
3196 ItemKind::Impl(.., None, _, ref items) => {
3197 let mut ids = smallvec![hir::ItemId { id: i.id }];
3199 if let ImplItemKind::Method(ref sig, _) = item.node {
3200 self.lower_impl_trait_ids(&sig.decl, &sig.header, &mut ids);
3205 _ => smallvec![hir::ItemId { id: i.id }],
3209 fn lower_item_id_use_tree(&mut self,
3212 vec: &mut OneVector<hir::ItemId>)
3215 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3216 vec.push(hir::ItemId { id });
3217 self.lower_item_id_use_tree(nested, id, vec);
3219 UseTreeKind::Glob => {}
3220 UseTreeKind::Simple(_, id1, id2) => {
3221 for (_, &id) in self.expect_full_def_from_use(base_id)
3223 .zip([id1, id2].iter())
3225 vec.push(hir::ItemId { id });
3231 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3232 let mut name = i.ident.name;
3233 let mut vis = self.lower_visibility(&i.vis, None);
3234 let attrs = self.lower_attrs(&i.attrs);
3235 if let ItemKind::MacroDef(ref def) = i.node {
3236 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3237 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3238 let body = self.lower_token_stream(def.stream());
3239 self.exported_macros.push(hir::MacroDef {
3252 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3254 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3267 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3268 let node_id = self.lower_node_id(i.id).node_id;
3269 let def_id = self.resolver.definitions().local_def_id(node_id);
3273 attrs: self.lower_attrs(&i.attrs),
3274 node: match i.node {
3275 ForeignItemKind::Fn(ref fdec, ref generics) => {
3276 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3279 AnonymousLifetimeMode::PassThrough,
3282 // Disallow impl Trait in foreign items
3283 this.lower_fn_decl(fdec, None, false, None),
3284 this.lower_fn_args_to_names(fdec),
3289 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3291 ForeignItemKind::Static(ref t, m) => {
3292 hir::ForeignItemKind::Static(self.lower_ty(t, ImplTraitContext::Disallowed), m)
3294 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3295 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3297 vis: self.lower_visibility(&i.vis, None),
3302 fn lower_method_sig(
3304 generics: &Generics,
3307 impl_trait_return_allow: bool,
3308 is_async: Option<NodeId>,
3309 ) -> (hir::Generics, hir::MethodSig) {
3310 let header = self.lower_fn_header(sig.header);
3311 let (generics, decl) = self.add_in_band_defs(
3314 AnonymousLifetimeMode::PassThrough,
3315 |this, idty| this.lower_fn_decl(
3317 Some((fn_def_id, idty)),
3318 impl_trait_return_allow,
3322 (generics, hir::MethodSig { header, decl })
3325 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3327 IsAuto::Yes => hir::IsAuto::Yes,
3328 IsAuto::No => hir::IsAuto::No,
3332 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3334 unsafety: self.lower_unsafety(h.unsafety),
3335 asyncness: self.lower_asyncness(h.asyncness),
3336 constness: self.lower_constness(h.constness),
3341 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3343 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3344 Unsafety::Normal => hir::Unsafety::Normal,
3348 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3350 Constness::Const => hir::Constness::Const,
3351 Constness::NotConst => hir::Constness::NotConst,
3355 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3357 IsAsync::Async { .. } => hir::IsAsync::Async,
3358 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3362 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3364 UnOp::Deref => hir::UnDeref,
3365 UnOp::Not => hir::UnNot,
3366 UnOp::Neg => hir::UnNeg,
3370 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3372 node: match b.node {
3373 BinOpKind::Add => hir::BinOpKind::Add,
3374 BinOpKind::Sub => hir::BinOpKind::Sub,
3375 BinOpKind::Mul => hir::BinOpKind::Mul,
3376 BinOpKind::Div => hir::BinOpKind::Div,
3377 BinOpKind::Rem => hir::BinOpKind::Rem,
3378 BinOpKind::And => hir::BinOpKind::And,
3379 BinOpKind::Or => hir::BinOpKind::Or,
3380 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3381 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3382 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3383 BinOpKind::Shl => hir::BinOpKind::Shl,
3384 BinOpKind::Shr => hir::BinOpKind::Shr,
3385 BinOpKind::Eq => hir::BinOpKind::Eq,
3386 BinOpKind::Lt => hir::BinOpKind::Lt,
3387 BinOpKind::Le => hir::BinOpKind::Le,
3388 BinOpKind::Ne => hir::BinOpKind::Ne,
3389 BinOpKind::Ge => hir::BinOpKind::Ge,
3390 BinOpKind::Gt => hir::BinOpKind::Gt,
3396 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3397 let node = match p.node {
3398 PatKind::Wild => hir::PatKind::Wild,
3399 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3400 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3401 // `None` can occur in body-less function signatures
3402 def @ None | def @ Some(Def::Local(_)) => {
3403 let canonical_id = match def {
3404 Some(Def::Local(id)) => id,
3407 hir::PatKind::Binding(
3408 self.lower_binding_mode(binding_mode),
3411 sub.as_ref().map(|x| self.lower_pat(x)),
3414 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3419 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3424 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3425 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3426 let qpath = self.lower_qpath(
3430 ParamMode::Optional,
3431 ImplTraitContext::Disallowed,
3433 self.check_self_struct_ctor_feature(&qpath);
3434 hir::PatKind::TupleStruct(
3436 pats.iter().map(|x| self.lower_pat(x)).collect(),
3440 PatKind::Path(ref qself, ref path) => {
3441 let qpath = self.lower_qpath(
3445 ParamMode::Optional,
3446 ImplTraitContext::Disallowed,
3448 self.check_self_struct_ctor_feature(&qpath);
3449 hir::PatKind::Path(qpath)
3451 PatKind::Struct(ref path, ref fields, etc) => {
3452 let qpath = self.lower_qpath(
3456 ParamMode::Optional,
3457 ImplTraitContext::Disallowed,
3464 node: hir::FieldPat {
3465 id: self.next_id().node_id,
3466 ident: f.node.ident,
3467 pat: self.lower_pat(&f.node.pat),
3468 is_shorthand: f.node.is_shorthand,
3472 hir::PatKind::Struct(qpath, fs, etc)
3474 PatKind::Tuple(ref elts, ddpos) => {
3475 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3477 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3478 PatKind::Ref(ref inner, mutbl) => {
3479 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3481 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3482 P(self.lower_expr(e1)),
3483 P(self.lower_expr(e2)),
3484 self.lower_range_end(end),
3486 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3487 before.iter().map(|x| self.lower_pat(x)).collect(),
3488 slice.as_ref().map(|x| self.lower_pat(x)),
3489 after.iter().map(|x| self.lower_pat(x)).collect(),
3491 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3492 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3495 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3504 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3506 RangeEnd::Included(_) => hir::RangeEnd::Included,
3507 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3511 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3512 self.with_new_scopes(|this| {
3513 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3517 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3522 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3523 let kind = match e.node {
3524 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3525 ExprKind::ObsoleteInPlace(..) => {
3526 self.sess.abort_if_errors();
3527 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3529 ExprKind::Array(ref exprs) => {
3530 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3532 ExprKind::Repeat(ref expr, ref count) => {
3533 let expr = P(self.lower_expr(expr));
3534 let count = self.lower_anon_const(count);
3535 hir::ExprKind::Repeat(expr, count)
3537 ExprKind::Tup(ref elts) => {
3538 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3540 ExprKind::Call(ref f, ref args) => {
3541 let f = P(self.lower_expr(f));
3542 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3544 ExprKind::MethodCall(ref seg, ref args) => {
3545 let hir_seg = self.lower_path_segment(
3548 ParamMode::Optional,
3550 ParenthesizedGenericArgs::Err,
3551 ImplTraitContext::Disallowed,
3553 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3554 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3556 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3557 let binop = self.lower_binop(binop);
3558 let lhs = P(self.lower_expr(lhs));
3559 let rhs = P(self.lower_expr(rhs));
3560 hir::ExprKind::Binary(binop, lhs, rhs)
3562 ExprKind::Unary(op, ref ohs) => {
3563 let op = self.lower_unop(op);
3564 let ohs = P(self.lower_expr(ohs));
3565 hir::ExprKind::Unary(op, ohs)
3567 ExprKind::Lit(ref l) => hir::ExprKind::Lit(P((**l).clone())),
3568 ExprKind::Cast(ref expr, ref ty) => {
3569 let expr = P(self.lower_expr(expr));
3570 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3572 ExprKind::Type(ref expr, ref ty) => {
3573 let expr = P(self.lower_expr(expr));
3574 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3576 ExprKind::AddrOf(m, ref ohs) => {
3577 let m = self.lower_mutability(m);
3578 let ohs = P(self.lower_expr(ohs));
3579 hir::ExprKind::AddrOf(m, ohs)
3581 // More complicated than you might expect because the else branch
3582 // might be `if let`.
3583 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3584 let else_opt = else_opt.as_ref().map(|els| {
3586 ExprKind::IfLet(..) => {
3587 // wrap the if-let expr in a block
3588 let span = els.span;
3589 let els = P(self.lower_expr(els));
3590 let LoweredNodeId { node_id, hir_id } = self.next_id();
3591 let blk = P(hir::Block {
3596 rules: hir::DefaultBlock,
3598 targeted_by_break: false,
3599 recovered: blk.recovered,
3601 P(self.expr_block(blk, ThinVec::new()))
3603 _ => P(self.lower_expr(els)),
3607 let then_blk = self.lower_block(blk, false);
3608 let then_expr = self.expr_block(then_blk, ThinVec::new());
3610 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3612 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3613 hir::ExprKind::While(
3614 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3615 this.lower_block(body, false),
3616 this.lower_label(opt_label),
3619 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3620 hir::ExprKind::Loop(
3621 this.lower_block(body, false),
3622 this.lower_label(opt_label),
3623 hir::LoopSource::Loop,
3626 ExprKind::TryBlock(ref body) => {
3627 self.with_catch_scope(body.id, |this| {
3629 this.allow_internal_unstable(CompilerDesugaringKind::TryBlock, body.span);
3630 let mut block = this.lower_block(body, true).into_inner();
3631 let tail = block.expr.take().map_or_else(
3633 let LoweredNodeId { node_id, hir_id } = this.next_id();
3634 let span = this.sess.source_map().end_point(unstable_span);
3638 node: hir::ExprKind::Tup(hir_vec![]),
3639 attrs: ThinVec::new(),
3643 |x: P<hir::Expr>| x.into_inner(),
3645 block.expr = Some(this.wrap_in_try_constructor(
3646 "from_ok", tail, unstable_span));
3647 hir::ExprKind::Block(P(block), None)
3650 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3651 P(self.lower_expr(expr)),
3652 arms.iter().map(|x| self.lower_arm(x)).collect(),
3653 hir::MatchSource::Normal,
3655 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3656 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3657 this.with_new_scopes(|this| {
3658 let block = this.lower_block(block, false);
3659 this.expr_block(block, ThinVec::new())
3664 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3666 if let IsAsync::Async { closure_id, .. } = asyncness {
3667 let outer_decl = FnDecl {
3668 inputs: decl.inputs.clone(),
3669 output: FunctionRetTy::Default(fn_decl_span),
3672 // We need to lower the declaration outside the new scope, because we
3673 // have to conserve the state of being inside a loop condition for the
3674 // closure argument types.
3675 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3677 self.with_new_scopes(|this| {
3678 // FIXME(cramertj) allow `async` non-`move` closures with
3679 if capture_clause == CaptureBy::Ref &&
3680 !decl.inputs.is_empty()
3686 "`async` non-`move` closures with arguments \
3687 are not currently supported",
3689 .help("consider using `let` statements to manually capture \
3690 variables by reference before entering an \
3691 `async move` closure")
3695 // Transform `async |x: u8| -> X { ... }` into
3696 // `|x: u8| future_from_generator(|| -> X { ... })`
3697 let body_id = this.lower_body(Some(&outer_decl), |this| {
3698 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3701 let async_body = this.make_async_expr(
3702 capture_clause, closure_id, async_ret_ty,
3704 this.with_new_scopes(|this| this.lower_expr(body))
3706 this.expr(fn_decl_span, async_body, ThinVec::new())
3708 hir::ExprKind::Closure(
3709 this.lower_capture_clause(capture_clause),
3717 // Lower outside new scope to preserve `is_in_loop_condition`.
3718 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3720 self.with_new_scopes(|this| {
3721 let mut is_generator = false;
3722 let body_id = this.lower_body(Some(decl), |this| {
3723 let e = this.lower_expr(body);
3724 is_generator = this.is_generator;
3727 let generator_option = if is_generator {
3728 if !decl.inputs.is_empty() {
3733 "generators cannot have explicit arguments"
3735 this.sess.abort_if_errors();
3737 Some(match movability {
3738 Movability::Movable => hir::GeneratorMovability::Movable,
3739 Movability::Static => hir::GeneratorMovability::Static,
3742 if movability == Movability::Static {
3747 "closures cannot be static"
3752 hir::ExprKind::Closure(
3753 this.lower_capture_clause(capture_clause),
3762 ExprKind::Block(ref blk, opt_label) => {
3763 hir::ExprKind::Block(self.lower_block(blk,
3764 opt_label.is_some()),
3765 self.lower_label(opt_label))
3767 ExprKind::Assign(ref el, ref er) => {
3768 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3770 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
3771 self.lower_binop(op),
3772 P(self.lower_expr(el)),
3773 P(self.lower_expr(er)),
3775 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
3776 ExprKind::Index(ref el, ref er) => {
3777 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
3779 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3780 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3781 let id = self.next_id();
3782 let e1 = self.lower_expr(e1);
3783 let e2 = self.lower_expr(e2);
3784 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
3785 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
3786 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3787 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3788 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
3789 hir::ExprKind::Call(new, hir_vec![e1, e2])
3791 ExprKind::Range(ref e1, ref e2, lims) => {
3792 use syntax::ast::RangeLimits::*;
3794 let path = match (e1, e2, lims) {
3795 (&None, &None, HalfOpen) => "RangeFull",
3796 (&Some(..), &None, HalfOpen) => "RangeFrom",
3797 (&None, &Some(..), HalfOpen) => "RangeTo",
3798 (&Some(..), &Some(..), HalfOpen) => "Range",
3799 (&None, &Some(..), Closed) => "RangeToInclusive",
3800 (&Some(..), &Some(..), Closed) => unreachable!(),
3801 (_, &None, Closed) => self.diagnostic()
3802 .span_fatal(e.span, "inclusive range with no end")
3806 let fields = e1.iter()
3807 .map(|e| ("start", e))
3808 .chain(e2.iter().map(|e| ("end", e)))
3810 let expr = P(self.lower_expr(&e));
3811 let ident = Ident::new(Symbol::intern(s), e.span);
3812 self.field(ident, expr, e.span)
3814 .collect::<P<[hir::Field]>>();
3816 let is_unit = fields.is_empty();
3817 let struct_path = iter::once("ops")
3818 .chain(iter::once(path))
3819 .collect::<Vec<_>>();
3820 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
3821 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3823 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3829 hir::ExprKind::Path(struct_path)
3831 hir::ExprKind::Struct(struct_path, fields, None)
3834 attrs: e.attrs.clone(),
3837 ExprKind::Path(ref qself, ref path) => {
3838 let qpath = self.lower_qpath(
3842 ParamMode::Optional,
3843 ImplTraitContext::Disallowed,
3845 self.check_self_struct_ctor_feature(&qpath);
3846 hir::ExprKind::Path(qpath)
3848 ExprKind::Break(opt_label, ref opt_expr) => {
3849 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3852 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3855 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3857 hir::ExprKind::Break(
3859 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3862 ExprKind::Continue(opt_label) => {
3863 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
3866 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3869 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3872 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
3873 ExprKind::InlineAsm(ref asm) => {
3874 let hir_asm = hir::InlineAsm {
3875 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3876 outputs: asm.outputs
3878 .map(|out| hir::InlineAsmOutput {
3879 constraint: out.constraint.clone(),
3881 is_indirect: out.is_indirect,
3884 asm: asm.asm.clone(),
3885 asm_str_style: asm.asm_str_style,
3886 clobbers: asm.clobbers.clone().into(),
3887 volatile: asm.volatile,
3888 alignstack: asm.alignstack,
3889 dialect: asm.dialect,
3892 let outputs = asm.outputs
3894 .map(|out| self.lower_expr(&out.expr))
3896 let inputs = asm.inputs
3898 .map(|&(_, ref input)| self.lower_expr(input))
3900 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
3902 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
3907 ParamMode::Optional,
3908 ImplTraitContext::Disallowed,
3910 fields.iter().map(|x| self.lower_field(x)).collect(),
3911 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3913 ExprKind::Paren(ref ex) => {
3914 let mut ex = self.lower_expr(ex);
3915 // include parens in span, but only if it is a super-span.
3916 if e.span.contains(ex.span) {
3919 // merge attributes into the inner expression.
3920 let mut attrs = e.attrs.clone();
3921 attrs.extend::<Vec<_>>(ex.attrs.into());
3926 ExprKind::Yield(ref opt_expr) => {
3927 self.is_generator = true;
3930 .map(|x| self.lower_expr(x))
3932 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
3934 hir::ExprKind::Yield(P(expr))
3937 // Desugar ExprIfLet
3938 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3939 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3942 // match <sub_expr> {
3944 // _ => [<else_opt> | ()]
3947 let mut arms = vec![];
3949 // `<pat> => <body>`
3951 let body = self.lower_block(body, false);
3952 let body_expr = P(self.expr_block(body, ThinVec::new()));
3953 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3954 arms.push(self.arm(pats, body_expr));
3957 // _ => [<else_opt>|()]
3959 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3960 let wildcard_pattern = self.pat_wild(e.span);
3961 let body = if let Some(else_expr) = wildcard_arm {
3962 P(self.lower_expr(else_expr))
3964 self.expr_tuple(e.span, hir_vec![])
3966 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3969 let contains_else_clause = else_opt.is_some();
3971 let sub_expr = P(self.lower_expr(sub_expr));
3973 hir::ExprKind::Match(
3976 hir::MatchSource::IfLetDesugar {
3977 contains_else_clause,
3982 // Desugar ExprWhileLet
3983 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3984 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3987 // [opt_ident]: loop {
3988 // match <sub_expr> {
3994 // Note that the block AND the condition are evaluated in the loop scope.
3995 // This is done to allow `break` from inside the condition of the loop.
3996 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3998 this.lower_block(body, false),
3999 this.expr_break(e.span, ThinVec::new()),
4000 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4004 // `<pat> => <body>`
4006 let body_expr = P(self.expr_block(body, ThinVec::new()));
4007 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4008 self.arm(pats, body_expr)
4013 let pat_under = self.pat_wild(e.span);
4014 self.arm(hir_vec![pat_under], break_expr)
4017 // `match <sub_expr> { ... }`
4018 let arms = hir_vec![pat_arm, break_arm];
4019 let match_expr = self.expr(
4021 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4025 // `[opt_ident]: loop { ... }`
4026 let loop_block = P(self.block_expr(P(match_expr)));
4027 let loop_expr = hir::ExprKind::Loop(
4029 self.lower_label(opt_label),
4030 hir::LoopSource::WhileLet,
4032 // add attributes to the outer returned expr node
4036 // Desugar ExprForLoop
4037 // From: `[opt_ident]: for <pat> in <head> <body>`
4038 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4042 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4044 // [opt_ident]: loop {
4046 // match ::std::iter::Iterator::next(&mut iter) {
4047 // ::std::option::Option::Some(val) => __next = val,
4048 // ::std::option::Option::None => break
4050 // let <pat> = __next;
4051 // StmtKind::Expr(<body>);
4059 let head = self.lower_expr(head);
4060 let head_sp = head.span;
4062 let iter = self.str_to_ident("iter");
4064 let next_ident = self.str_to_ident("__next");
4065 let next_sp = self.allow_internal_unstable(
4066 CompilerDesugaringKind::ForLoop,
4069 let next_pat = self.pat_ident_binding_mode(
4072 hir::BindingAnnotation::Mutable,
4075 // `::std::option::Option::Some(val) => next = val`
4077 let val_ident = self.str_to_ident("val");
4078 let val_pat = self.pat_ident(pat.span, val_ident);
4079 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4080 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4081 let assign = P(self.expr(
4083 hir::ExprKind::Assign(next_expr, val_expr),
4086 let some_pat = self.pat_some(pat.span, val_pat);
4087 self.arm(hir_vec![some_pat], assign)
4090 // `::std::option::Option::None => break`
4093 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4094 let pat = self.pat_none(e.span);
4095 self.arm(hir_vec![pat], break_expr)
4100 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
4102 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4104 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4105 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4106 let next_path = &["iter", "Iterator", "next"];
4107 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4108 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4109 let arms = hir_vec![pat_arm, break_arm];
4113 hir::ExprKind::Match(
4116 hir::MatchSource::ForLoopDesugar
4121 let match_stmt = respan(
4123 hir::StmtKind::Expr(match_expr, self.next_id().node_id)
4126 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4130 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
4132 // `let <pat> = __next`
4133 let pat = self.lower_pat(pat);
4134 let pat_let = self.stmt_let_pat(
4138 hir::LocalSource::ForLoopDesugar,
4141 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4142 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4143 let body_stmt = respan(
4145 hir::StmtKind::Expr(body_expr, self.next_id().node_id)
4148 let loop_block = P(self.block_all(
4150 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4154 // `[opt_ident]: loop { ... }`
4155 let loop_expr = hir::ExprKind::Loop(
4157 self.lower_label(opt_label),
4158 hir::LoopSource::ForLoop,
4160 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4161 let loop_expr = P(hir::Expr {
4166 attrs: ThinVec::new(),
4169 // `mut iter => { ... }`
4170 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4172 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4173 let into_iter_expr = {
4174 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4175 let into_iter = P(self.expr_std_path(
4176 head_sp, into_iter_path, None, ThinVec::new()));
4177 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4180 let match_expr = P(self.expr_match(
4184 hir::MatchSource::ForLoopDesugar,
4187 // `{ let _result = ...; _result }`
4188 // underscore prevents an unused_variables lint if the head diverges
4189 let result_ident = self.str_to_ident("_result");
4190 let (let_stmt, let_stmt_binding) =
4191 self.stmt_let(e.span, false, result_ident, match_expr);
4193 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4194 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4195 // add the attributes to the outer returned expr node
4196 return self.expr_block(block, e.attrs.clone());
4199 // Desugar ExprKind::Try
4201 ExprKind::Try(ref sub_expr) => {
4204 // match Try::into_result(<expr>) {
4205 // Ok(val) => #[allow(unreachable_code)] val,
4206 // Err(err) => #[allow(unreachable_code)]
4207 // // If there is an enclosing `catch {...}`
4208 // break 'catch_target Try::from_error(From::from(err)),
4210 // return Try::from_error(From::from(err)),
4214 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4216 // Try::into_result(<expr>)
4219 let sub_expr = self.lower_expr(sub_expr);
4221 let path = &["ops", "Try", "into_result"];
4222 let path = P(self.expr_std_path(
4223 unstable_span, path, None, ThinVec::new()));
4224 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4227 // #[allow(unreachable_code)]
4229 // allow(unreachable_code)
4231 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4232 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4233 let uc_nested = attr::mk_nested_word_item(uc_ident);
4234 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4236 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4238 let attrs = vec![attr];
4240 // Ok(val) => #[allow(unreachable_code)] val,
4242 let val_ident = self.str_to_ident("val");
4243 let val_pat = self.pat_ident(e.span, val_ident);
4244 let val_expr = P(self.expr_ident_with_attrs(
4248 ThinVec::from(attrs.clone()),
4250 let ok_pat = self.pat_ok(e.span, val_pat);
4252 self.arm(hir_vec![ok_pat], val_expr)
4255 // Err(err) => #[allow(unreachable_code)]
4256 // return Try::from_error(From::from(err)),
4258 let err_ident = self.str_to_ident("err");
4259 let err_local = self.pat_ident(e.span, err_ident);
4261 let path = &["convert", "From", "from"];
4262 let from = P(self.expr_std_path(
4263 e.span, path, None, ThinVec::new()));
4264 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4266 self.expr_call(e.span, from, hir_vec![err_expr])
4269 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4270 let thin_attrs = ThinVec::from(attrs);
4271 let catch_scope = self.catch_scopes.last().map(|x| *x);
4272 let ret_expr = if let Some(catch_node) = catch_scope {
4275 hir::ExprKind::Break(
4278 target_id: Ok(catch_node),
4280 Some(from_err_expr),
4285 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4288 let err_pat = self.pat_err(e.span, err_local);
4289 self.arm(hir_vec![err_pat], ret_expr)
4292 hir::ExprKind::Match(
4294 hir_vec![err_arm, ok_arm],
4295 hir::MatchSource::TryDesugar,
4299 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4302 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4309 attrs: e.attrs.clone(),
4313 fn lower_stmt(&mut self, s: &Stmt) -> OneVector<hir::Stmt> {
4314 smallvec![match s.node {
4315 StmtKind::Local(ref l) => Spanned {
4316 node: hir::StmtKind::Decl(
4318 node: hir::DeclKind::Local(self.lower_local(l)),
4321 self.lower_node_id(s.id).node_id,
4325 StmtKind::Item(ref it) => {
4326 // Can only use the ID once.
4327 let mut id = Some(s.id);
4328 return self.lower_item_id(it)
4330 .map(|item_id| Spanned {
4331 node: hir::StmtKind::Decl(
4333 node: hir::DeclKind::Item(item_id),
4337 .map(|id| self.lower_node_id(id).node_id)
4338 .unwrap_or_else(|| self.next_id().node_id),
4344 StmtKind::Expr(ref e) => Spanned {
4345 node: hir::StmtKind::Expr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4348 StmtKind::Semi(ref e) => Spanned {
4349 node: hir::StmtKind::Semi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4352 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4356 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4358 CaptureBy::Value => hir::CaptureByValue,
4359 CaptureBy::Ref => hir::CaptureByRef,
4363 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4364 /// the address space of that item instead of the item currently being
4365 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4366 /// lower a `Visibility` value although we haven't lowered the owning
4367 /// `ImplItem` in question yet.
4368 fn lower_visibility(
4371 explicit_owner: Option<NodeId>,
4372 ) -> hir::Visibility {
4373 let node = match v.node {
4374 VisibilityKind::Public => hir::VisibilityKind::Public,
4375 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4376 VisibilityKind::Restricted { ref path, id } => {
4377 let lowered_id = if let Some(owner) = explicit_owner {
4378 self.lower_node_id_with_owner(id, owner)
4380 self.lower_node_id(id)
4382 hir::VisibilityKind::Restricted {
4383 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4384 id: lowered_id.node_id,
4385 hir_id: lowered_id.hir_id,
4388 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4390 respan(v.span, node)
4393 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4395 Defaultness::Default => hir::Defaultness::Default {
4396 has_value: has_value,
4398 Defaultness::Final => {
4400 hir::Defaultness::Final
4405 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4407 BlockCheckMode::Default => hir::DefaultBlock,
4408 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4412 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4414 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4415 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4416 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4417 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4421 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4423 CompilerGenerated => hir::CompilerGenerated,
4424 UserProvided => hir::UserProvided,
4428 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4430 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4431 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4435 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4437 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4438 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4442 // Helper methods for building HIR.
4444 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4453 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4455 id: self.next_id().node_id,
4459 is_shorthand: false,
4463 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4464 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4465 P(self.expr(span, expr_break, attrs))
4472 args: hir::HirVec<hir::Expr>,
4474 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4477 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4478 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4481 fn expr_ident_with_attrs(
4486 attrs: ThinVec<Attribute>,
4488 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4492 def: Def::Local(binding),
4493 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4497 self.expr(span, expr_path, attrs)
4500 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4501 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4507 components: &[&str],
4508 params: Option<P<hir::GenericArgs>>,
4509 attrs: ThinVec<Attribute>,
4511 let path = self.std_path(span, components, params, true);
4514 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4523 arms: hir::HirVec<hir::Arm>,
4524 source: hir::MatchSource,
4526 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4529 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4530 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4533 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4534 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4537 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4538 let LoweredNodeId { node_id, hir_id } = self.next_id();
4551 ex: Option<P<hir::Expr>>,
4553 source: hir::LocalSource,
4555 let LoweredNodeId { node_id, hir_id } = self.next_id();
4557 let local = P(hir::Local {
4564 attrs: ThinVec::new(),
4567 let decl = respan(sp, hir::DeclKind::Local(local));
4568 respan(sp, hir::StmtKind::Decl(P(decl), self.next_id().node_id))
4577 ) -> (hir::Stmt, NodeId) {
4578 let pat = if mutbl {
4579 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4581 self.pat_ident(sp, ident)
4583 let pat_id = pat.id;
4585 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4590 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4591 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4597 stmts: hir::HirVec<hir::Stmt>,
4598 expr: Option<P<hir::Expr>>,
4600 let LoweredNodeId { node_id, hir_id } = self.next_id();
4607 rules: hir::DefaultBlock,
4609 targeted_by_break: false,
4614 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4615 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4618 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4619 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4622 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4623 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4626 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4627 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4633 components: &[&str],
4634 subpats: hir::HirVec<P<hir::Pat>>,
4636 let path = self.std_path(span, components, None, true);
4637 let qpath = hir::QPath::Resolved(None, P(path));
4638 let pt = if subpats.is_empty() {
4639 hir::PatKind::Path(qpath)
4641 hir::PatKind::TupleStruct(qpath, subpats, None)
4646 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4647 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4650 fn pat_ident_binding_mode(
4654 bm: hir::BindingAnnotation,
4656 let LoweredNodeId { node_id, hir_id } = self.next_id();
4661 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4666 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4667 self.pat(span, hir::PatKind::Wild)
4670 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4671 let LoweredNodeId { node_id, hir_id } = self.next_id();
4680 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4681 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4682 /// The path is also resolved according to `is_value`.
4686 components: &[&str],
4687 params: Option<P<hir::GenericArgs>>,
4691 .resolve_str_path(span, self.crate_root, components, params, is_value)
4694 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4696 let node = match qpath {
4697 hir::QPath::Resolved(None, path) => {
4698 // Turn trait object paths into `TyKind::TraitObject` instead.
4699 if let Def::Trait(_) = path.def {
4700 let principal = hir::PolyTraitRef {
4701 bound_generic_params: hir::HirVec::new(),
4702 trait_ref: hir::TraitRef {
4703 path: path.and_then(|path| path),
4705 hir_ref_id: id.hir_id,
4710 // The original ID is taken by the `PolyTraitRef`,
4711 // so the `Ty` itself needs a different one.
4712 id = self.next_id();
4713 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4715 hir::TyKind::Path(hir::QPath::Resolved(None, path))
4718 _ => hir::TyKind::Path(qpath),
4728 /// Invoked to create the lifetime argument for a type `&T`
4729 /// with no explicit lifetime.
4730 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4731 match self.anonymous_lifetime_mode {
4732 // Intercept when we are in an impl header and introduce an in-band lifetime.
4733 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4735 AnonymousLifetimeMode::CreateParameter => {
4736 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4738 id: self.next_id().node_id,
4740 name: hir::LifetimeName::Param(fresh_name),
4744 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4748 /// Invoked to create the lifetime argument(s) for a path like
4749 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4750 /// sorts of cases are deprecated. This may therefore report a warning or an
4751 /// error, depending on the mode.
4752 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4753 match self.anonymous_lifetime_mode {
4754 // NB. We intentionally ignore the create-parameter mode here
4755 // and instead "pass through" to resolve-lifetimes, which will then
4756 // report an error. This is because we don't want to support
4757 // impl elision for deprecated forms like
4759 // impl Foo for std::cell::Ref<u32> // note lack of '_
4760 AnonymousLifetimeMode::CreateParameter => {}
4762 // This is the normal case.
4763 AnonymousLifetimeMode::PassThrough => {}
4767 .map(|_| self.new_implicit_lifetime(span))
4771 /// Invoked to create the lifetime argument(s) for an elided trait object
4772 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4773 /// when the bound is written, even if it is written with `'_` like in
4774 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4775 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4776 match self.anonymous_lifetime_mode {
4777 // NB. We intentionally ignore the create-parameter mode here.
4778 // and instead "pass through" to resolve-lifetimes, which will apply
4779 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4780 // do not act like other elided lifetimes. In other words, given this:
4782 // impl Foo for Box<dyn Debug>
4784 // we do not introduce a fresh `'_` to serve as the bound, but instead
4785 // ultimately translate to the equivalent of:
4787 // impl Foo for Box<dyn Debug + 'static>
4789 // `resolve_lifetime` has the code to make that happen.
4790 AnonymousLifetimeMode::CreateParameter => {}
4792 // This is the normal case.
4793 AnonymousLifetimeMode::PassThrough => {}
4796 self.new_implicit_lifetime(span)
4799 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4801 id: self.next_id().node_id,
4803 name: hir::LifetimeName::Implicit,
4807 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4808 self.sess.buffer_lint_with_diagnostic(
4809 builtin::BARE_TRAIT_OBJECTS,
4812 "trait objects without an explicit `dyn` are deprecated",
4813 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4817 fn wrap_in_try_constructor(
4819 method: &'static str,
4821 unstable_span: Span,
4823 let path = &["ops", "Try", method];
4824 let from_err = P(self.expr_std_path(unstable_span, path, None,
4826 P(self.expr_call(e.span, from_err, hir_vec![e]))
4829 fn check_self_struct_ctor_feature(&self, qp: &hir::QPath) {
4830 if let hir::QPath::Resolved(_, ref p) = qp {
4831 if p.segments.len() == 1 &&
4832 p.segments[0].ident.name == keywords::SelfType.name() &&
4833 !self.sess.features_untracked().self_struct_ctor {
4834 emit_feature_err(&self.sess.parse_sess, "self_struct_ctor",
4835 p.span, GateIssue::Language,
4836 "`Self` struct constructors are unstable");
4842 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4843 // Sorting by span ensures that we get things in order within a
4844 // file, and also puts the files in a sensible order.
4845 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4846 body_ids.sort_by_key(|b| bodies[b].value.span);