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::indexed_vec::IndexVec;
55 use util::common::FN_OUTPUT_NAME;
56 use util::nodemap::{DefIdMap, NodeMap};
58 use std::collections::{BTreeMap, HashSet};
66 use syntax::ext::hygiene::{Mark, SyntaxContext};
67 use syntax::print::pprust;
69 use syntax::codemap::{self, respan, CompilerDesugaringKind, Spanned};
70 use syntax::std_inject;
71 use syntax::symbol::{keywords, Symbol};
72 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
73 use syntax::parse::token::Token;
74 use syntax::util::small_vector::SmallVector;
75 use syntax::visit::{self, Visitor};
76 use syntax_pos::{Span, MultiSpan};
78 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
80 pub struct LoweringContext<'a> {
81 crate_root: Option<&'static str>,
83 // Use to assign ids to hir nodes that do not directly correspond to an ast node
86 cstore: &'a dyn CrateStore,
88 resolver: &'a mut dyn Resolver,
90 /// The items being lowered are collected here.
91 items: BTreeMap<NodeId, hir::Item>,
93 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
94 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
95 bodies: BTreeMap<hir::BodyId, hir::Body>,
96 exported_macros: Vec<hir::MacroDef>,
98 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
99 trait_auto_impl: BTreeMap<DefId, NodeId>,
103 catch_scopes: Vec<NodeId>,
104 loop_scopes: Vec<NodeId>,
105 is_in_loop_condition: bool,
106 is_in_trait_impl: bool,
108 /// What to do when we encounter either an "anonymous lifetime
109 /// reference". The term "anonymous" is meant to encompass both
110 /// `'_` lifetimes as well as fully elided cases where nothing is
111 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
112 anonymous_lifetime_mode: AnonymousLifetimeMode,
114 // Used to create lifetime definitions from in-band lifetime usages.
115 // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
116 // When a named lifetime is encountered in a function or impl header and
117 // has not been defined
118 // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
119 // to this list. The results of this list are then added to the list of
120 // lifetime definitions in the corresponding impl or function generics.
121 lifetimes_to_define: Vec<(Span, ParamName)>,
123 // Whether or not in-band lifetimes are being collected. This is used to
124 // indicate whether or not we're in a place where new lifetimes will result
125 // in in-band lifetime definitions, such a function or an impl header.
126 // This will always be false unless the `in_band_lifetimes` feature is
128 is_collecting_in_band_lifetimes: bool,
130 // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
131 // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
132 // against this list to see if it is already in-scope, or if a definition
133 // needs to be created for it.
134 in_scope_lifetimes: Vec<Ident>,
136 type_def_lifetime_params: DefIdMap<usize>,
138 current_hir_id_owner: Vec<(DefIndex, u32)>,
139 item_local_id_counters: NodeMap<u32>,
140 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
144 /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
145 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
147 /// Obtain the resolution for a node id
148 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
150 /// Obtain the possible resolutions for the given `use` statement.
151 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
153 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
154 /// This should only return `None` during testing.
155 fn definitions(&mut self) -> &mut Definitions;
157 /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
158 /// it based on `is_value`.
162 crate_root: Option<&str>,
164 params: Option<P<hir::GenericArgs>>,
170 enum ImplTraitContext<'a> {
171 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
172 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
173 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
175 /// Newly generated parameters should be inserted into the given `Vec`
176 Universal(&'a mut Vec<hir::GenericParam>),
178 /// Treat `impl Trait` as shorthand for a new universal existential parameter.
179 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
180 /// equivalent to a fresh existential parameter like `abstract type T; fn foo() -> T`.
182 /// We store a DefId here so we can look up necessary information later
185 /// `impl Trait` is not accepted in this position.
189 impl<'a> ImplTraitContext<'a> {
190 fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
191 use self::ImplTraitContext::*;
193 Universal(params) => Universal(params),
194 Existential(did) => Existential(*did),
195 Disallowed => Disallowed,
202 cstore: &dyn CrateStore,
203 dep_graph: &DepGraph,
205 resolver: &mut dyn Resolver,
207 // We're constructing the HIR here; we don't care what we will
208 // read, since we haven't even constructed the *input* to
210 dep_graph.assert_ignored();
213 crate_root: std_inject::injected_crate_name(),
217 items: BTreeMap::new(),
218 trait_items: BTreeMap::new(),
219 impl_items: BTreeMap::new(),
220 bodies: BTreeMap::new(),
221 trait_impls: BTreeMap::new(),
222 trait_auto_impl: BTreeMap::new(),
223 exported_macros: Vec::new(),
224 catch_scopes: Vec::new(),
225 loop_scopes: Vec::new(),
226 is_in_loop_condition: false,
227 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
228 type_def_lifetime_params: DefIdMap(),
229 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
230 item_local_id_counters: NodeMap(),
231 node_id_to_hir_id: IndexVec::new(),
233 is_in_trait_impl: false,
234 lifetimes_to_define: Vec::new(),
235 is_collecting_in_band_lifetimes: false,
236 in_scope_lifetimes: Vec::new(),
240 #[derive(Copy, Clone, PartialEq)]
242 /// Any path in a type context.
244 /// The `module::Type` in `module::Type::method` in an expression.
249 struct LoweredNodeId {
254 enum ParenthesizedGenericArgs {
260 /// What to do when we encounter an **anonymous** lifetime
261 /// reference. Anonymous lifetime references come in two flavors. You
262 /// have implicit, or fully elided, references to lifetimes, like the
263 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
264 /// or `Ref<'_, T>`. These often behave the same, but not always:
266 /// - certain usages of implicit references are deprecated, like
267 /// `Ref<T>`, and we sometimes just give hard errors in those cases
269 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
270 /// the same as `Box<dyn Foo + '_>`.
272 /// We describe the effects of the various modes in terms of three cases:
274 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
275 /// of a `&` (e.g., the missing lifetime in something like `&T`)
276 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
277 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
278 /// elided bounds follow special rules. Note that this only covers
279 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
280 /// '_>` is a case of "modern" elision.
281 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
282 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
283 /// non-deprecated equivalent.
285 /// Currently, the handling of lifetime elision is somewhat spread out
286 /// between HIR lowering and -- as described below -- the
287 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
288 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
289 /// everything into HIR lowering.
290 #[derive(Copy, Clone)]
291 enum AnonymousLifetimeMode {
292 /// For **Modern** cases, create a new anonymous region parameter
293 /// and reference that.
295 /// For **Dyn Bound** cases, pass responsibility to
296 /// `resolve_lifetime` code.
298 /// For **Deprecated** cases, report an error.
301 /// Pass responsibility to `resolve_lifetime` code for all cases.
305 impl<'a> LoweringContext<'a> {
306 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
307 /// Full-crate AST visitor that inserts into a fresh
308 /// `LoweringContext` any information that may be
309 /// needed from arbitrary locations in the crate.
310 /// E.g. The number of lifetime generic parameters
311 /// declared for every type and trait definition.
312 struct MiscCollector<'lcx, 'interner: 'lcx> {
313 lctx: &'lcx mut LoweringContext<'interner>,
316 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
317 fn visit_item(&mut self, item: &'lcx Item) {
318 self.lctx.allocate_hir_id_counter(item.id, item);
321 ItemKind::Struct(_, ref generics)
322 | ItemKind::Union(_, ref generics)
323 | ItemKind::Enum(_, ref generics)
324 | ItemKind::Ty(_, ref generics)
325 | ItemKind::Existential(_, ref generics)
326 | ItemKind::Trait(_, _, ref generics, ..) => {
327 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
331 .filter(|param| match param.kind {
332 ast::GenericParamKind::Lifetime { .. } => true,
336 self.lctx.type_def_lifetime_params.insert(def_id, count);
340 visit::walk_item(self, item);
343 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
344 self.lctx.allocate_hir_id_counter(item.id, item);
345 visit::walk_trait_item(self, item);
348 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
349 self.lctx.allocate_hir_id_counter(item.id, item);
350 visit::walk_impl_item(self, item);
354 struct ItemLowerer<'lcx, 'interner: 'lcx> {
355 lctx: &'lcx mut LoweringContext<'interner>,
358 impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
359 fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
361 F: FnOnce(&mut Self),
363 let old = self.lctx.is_in_trait_impl;
364 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
370 self.lctx.is_in_trait_impl = old;
374 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
375 fn visit_item(&mut self, item: &'lcx Item) {
376 let mut item_lowered = true;
377 self.lctx.with_hir_id_owner(item.id, |lctx| {
378 if let Some(hir_item) = lctx.lower_item(item) {
379 lctx.items.insert(item.id, hir_item);
381 item_lowered = false;
386 let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
387 hir::ItemKind::Impl(_, _, _, ref generics, ..)
388 | hir::ItemKind::Trait(_, _, ref generics, ..) => {
389 generics.params.clone()
394 self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
395 let this = &mut ItemLowerer { lctx: this };
396 if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
397 this.with_trait_impl_ref(opt_trait_ref, |this| {
398 visit::walk_item(this, item)
401 visit::walk_item(this, item);
407 fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
408 self.lctx.with_hir_id_owner(item.id, |lctx| {
409 let id = hir::TraitItemId { node_id: item.id };
410 let hir_item = lctx.lower_trait_item(item);
411 lctx.trait_items.insert(id, hir_item);
414 visit::walk_trait_item(self, item);
417 fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
418 self.lctx.with_hir_id_owner(item.id, |lctx| {
419 let id = hir::ImplItemId { node_id: item.id };
420 let hir_item = lctx.lower_impl_item(item);
421 lctx.impl_items.insert(id, hir_item);
423 visit::walk_impl_item(self, item);
427 self.lower_node_id(CRATE_NODE_ID);
428 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
430 visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
431 visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
433 let module = self.lower_mod(&c.module);
434 let attrs = self.lower_attrs(&c.attrs);
435 let body_ids = body_ids(&self.bodies);
439 .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
445 exported_macros: hir::HirVec::from(self.exported_macros),
447 trait_items: self.trait_items,
448 impl_items: self.impl_items,
451 trait_impls: self.trait_impls,
452 trait_auto_impl: self.trait_auto_impl,
456 fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
457 if self.item_local_id_counters.insert(owner, 0).is_some() {
459 "Tried to allocate item_local_id_counter for {:?} twice",
463 // Always allocate the first HirId for the owner itself
464 self.lower_node_id_with_owner(owner, owner)
467 fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
469 F: FnOnce(&mut Self) -> hir::HirId,
471 if ast_node_id == DUMMY_NODE_ID {
472 return LoweredNodeId {
473 node_id: DUMMY_NODE_ID,
474 hir_id: hir::DUMMY_HIR_ID,
478 let min_size = ast_node_id.as_usize() + 1;
480 if min_size > self.node_id_to_hir_id.len() {
481 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
484 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
486 if existing_hir_id == hir::DUMMY_HIR_ID {
487 // Generate a new HirId
488 let hir_id = alloc_hir_id(self);
489 self.node_id_to_hir_id[ast_node_id] = hir_id;
491 node_id: ast_node_id,
496 node_id: ast_node_id,
497 hir_id: existing_hir_id,
502 fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
504 F: FnOnce(&mut Self) -> T,
506 let counter = self.item_local_id_counters
507 .insert(owner, HIR_ID_COUNTER_LOCKED)
508 .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
509 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
510 self.current_hir_id_owner.push((def_index, counter));
512 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
514 debug_assert!(def_index == new_def_index);
515 debug_assert!(new_counter >= counter);
517 let prev = self.item_local_id_counters
518 .insert(owner, new_counter)
520 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
524 /// This method allocates a new HirId for the given NodeId and stores it in
525 /// the LoweringContext's NodeId => HirId map.
526 /// Take care not to call this method if the resulting HirId is then not
527 /// actually used in the HIR, as that would trigger an assertion in the
528 /// HirIdValidator later on, which makes sure that all NodeIds got mapped
529 /// properly. Calling the method twice with the same NodeId is fine though.
530 fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
531 self.lower_node_id_generic(ast_node_id, |this| {
532 let &mut (def_index, ref mut local_id_counter) =
533 this.current_hir_id_owner.last_mut().unwrap();
534 let local_id = *local_id_counter;
535 *local_id_counter += 1;
538 local_id: hir::ItemLocalId(local_id),
543 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
544 self.lower_node_id_generic(ast_node_id, |this| {
545 let local_id_counter = this
546 .item_local_id_counters
548 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
549 let local_id = *local_id_counter;
551 // We want to be sure not to modify the counter in the map while it
552 // is also on the stack. Otherwise we'll get lost updates when writing
553 // back from the stack to the map.
554 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
556 *local_id_counter += 1;
560 .opt_def_index(owner)
561 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
562 that do not belong to the current owner");
566 local_id: hir::ItemLocalId(local_id),
571 fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
572 let body = hir::Body {
573 arguments: decl.map_or(hir_vec![], |decl| {
574 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
576 is_generator: self.is_generator,
580 self.bodies.insert(id, body);
584 fn next_id(&mut self) -> LoweredNodeId {
585 self.lower_node_id(self.sess.next_node_id())
588 fn expect_full_def(&mut self, id: NodeId) -> Def {
589 self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
590 if pr.unresolved_segments() != 0 {
591 bug!("path not fully resolved: {:?}", pr);
597 fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item=Def> {
598 self.resolver.get_import(id).present_items().map(|pr| {
599 if pr.unresolved_segments() != 0 {
600 bug!("path not fully resolved: {:?}", pr);
606 fn diagnostic(&self) -> &errors::Handler {
607 self.sess.diagnostic()
610 fn str_to_ident(&self, s: &'static str) -> Ident {
611 Ident::with_empty_ctxt(Symbol::gensym(s))
614 fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
615 let mark = Mark::fresh(Mark::root());
616 mark.set_expn_info(codemap::ExpnInfo {
618 def_site: Some(span),
619 format: codemap::CompilerDesugaring(reason),
620 allow_internal_unstable: true,
621 allow_internal_unsafe: false,
622 local_inner_macros: false,
623 edition: codemap::hygiene::default_edition(),
625 span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
628 fn with_anonymous_lifetime_mode<R>(
630 anonymous_lifetime_mode: AnonymousLifetimeMode,
631 op: impl FnOnce(&mut Self) -> R,
633 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
634 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
635 let result = op(self);
636 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
640 /// Creates a new hir::GenericParam for every new lifetime and
641 /// type parameter encountered while evaluating `f`. Definitions
642 /// are created with the parent provided. If no `parent_id` is
643 /// provided, no definitions will be returned.
645 /// Presuming that in-band lifetimes are enabled, then
646 /// `self.anonymous_lifetime_mode` will be updated to match the
647 /// argument while `f` is running (and restored afterwards).
648 fn collect_in_band_defs<T, F>(
651 anonymous_lifetime_mode: AnonymousLifetimeMode,
653 ) -> (Vec<hir::GenericParam>, T)
655 F: FnOnce(&mut LoweringContext) -> (Vec<hir::GenericParam>, T),
657 assert!(!self.is_collecting_in_band_lifetimes);
658 assert!(self.lifetimes_to_define.is_empty());
659 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
661 self.is_collecting_in_band_lifetimes = self.sess.features_untracked().in_band_lifetimes;
662 if self.is_collecting_in_band_lifetimes {
663 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
666 let (in_band_ty_params, res) = f(self);
668 self.is_collecting_in_band_lifetimes = false;
669 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
671 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
673 let params = lifetimes_to_define
675 .map(|(span, hir_name)| {
676 let def_node_id = self.next_id().node_id;
678 // Get the name we'll use to make the def-path. Note
679 // that collisions are ok here and this shouldn't
680 // really show up for end-user.
681 let str_name = match hir_name {
682 ParamName::Plain(ident) => ident.as_interned_str(),
683 ParamName::Fresh(_) => keywords::UnderscoreLifetime.name().as_interned_str(),
686 // Add a definition for the in-band lifetime def
687 self.resolver.definitions().create_def_with_parent(
690 DefPathData::LifetimeParam(str_name),
691 DefIndexAddressSpace::High,
702 pure_wrt_drop: false,
703 kind: hir::GenericParamKind::Lifetime { in_band: true }
706 .chain(in_band_ty_params.into_iter())
712 /// When there is a reference to some lifetime `'a`, and in-band
713 /// lifetimes are enabled, then we want to push that lifetime into
714 /// the vector of names to define later. In that case, it will get
715 /// added to the appropriate generics.
716 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
717 if !self.is_collecting_in_band_lifetimes {
721 if self.in_scope_lifetimes.contains(&ident.modern()) {
725 let hir_name = ParamName::Plain(ident);
727 if self.lifetimes_to_define.iter()
728 .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
732 self.lifetimes_to_define.push((ident.span, hir_name));
735 /// When we have either an elided or `'_` lifetime in an impl
736 /// header, we convert it to
737 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
738 assert!(self.is_collecting_in_band_lifetimes);
739 let index = self.lifetimes_to_define.len();
740 let hir_name = ParamName::Fresh(index);
741 self.lifetimes_to_define.push((span, hir_name));
745 // Evaluates `f` with the lifetimes in `params` in-scope.
746 // This is used to track which lifetimes have already been defined, and
747 // which are new in-band lifetimes that need to have a definition created
749 fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
751 F: FnOnce(&mut LoweringContext) -> T,
753 let old_len = self.in_scope_lifetimes.len();
754 let lt_def_names = params.iter().filter_map(|param| match param.kind {
755 GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
758 self.in_scope_lifetimes.extend(lt_def_names);
762 self.in_scope_lifetimes.truncate(old_len);
766 // Same as the method above, but accepts `hir::GenericParam`s
767 // instead of `ast::GenericParam`s.
768 // This should only be used with generics that have already had their
769 // in-band lifetimes added. In practice, this means that this function is
770 // only used when lowering a child item of a trait or impl.
771 fn with_parent_impl_lifetime_defs<T, F>(&mut self,
772 params: &HirVec<hir::GenericParam>,
775 F: FnOnce(&mut LoweringContext) -> T,
777 let old_len = self.in_scope_lifetimes.len();
778 let lt_def_names = params.iter().filter_map(|param| match param.kind {
779 hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
782 self.in_scope_lifetimes.extend(lt_def_names);
786 self.in_scope_lifetimes.truncate(old_len);
790 /// Appends in-band lifetime defs and argument-position `impl
791 /// Trait` defs to the existing set of generics.
793 /// Presuming that in-band lifetimes are enabled, then
794 /// `self.anonymous_lifetime_mode` will be updated to match the
795 /// argument while `f` is running (and restored afterwards).
796 fn add_in_band_defs<F, T>(
800 anonymous_lifetime_mode: AnonymousLifetimeMode,
802 ) -> (hir::Generics, T)
804 F: FnOnce(&mut LoweringContext, &mut Vec<hir::GenericParam>) -> T,
806 let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
809 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
810 let mut params = Vec::new();
811 let generics = this.lower_generics(
813 ImplTraitContext::Universal(&mut params),
815 let res = f(this, &mut params);
816 (params, (generics, res))
821 lowered_generics.params = lowered_generics
828 (lowered_generics, res)
831 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
833 F: FnOnce(&mut LoweringContext) -> T,
835 let len = self.catch_scopes.len();
836 self.catch_scopes.push(catch_id);
838 let result = f(self);
841 self.catch_scopes.len(),
842 "catch scopes should be added and removed in stack order"
845 self.catch_scopes.pop().unwrap();
852 capture_clause: CaptureBy,
853 closure_node_id: NodeId,
855 body: impl FnOnce(&mut LoweringContext) -> hir::Expr,
857 let prev_is_generator = mem::replace(&mut self.is_generator, true);
858 let body_expr = body(self);
859 let span = body_expr.span;
860 let output = match ret_ty {
861 Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
862 None => FunctionRetTy::Default(span),
869 let body_id = self.record_body(body_expr, Some(&decl));
870 self.is_generator = prev_is_generator;
872 let capture_clause = self.lower_capture_clause(capture_clause);
873 let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
874 let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
875 let generator = hir::Expr {
877 hir_id: closure_hir_id,
878 node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
879 Some(hir::GeneratorMovability::Static)),
881 attrs: ThinVec::new(),
884 let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
885 let gen_future = self.expr_std_path(
886 unstable_span, &["future", "from_generator"], None, ThinVec::new());
887 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
890 fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
892 F: FnOnce(&mut LoweringContext) -> hir::Expr,
894 let prev = mem::replace(&mut self.is_generator, false);
895 let result = f(self);
896 let r = self.record_body(result, decl);
897 self.is_generator = prev;
901 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
903 F: FnOnce(&mut LoweringContext) -> T,
905 // We're no longer in the base loop's condition; we're in another loop.
906 let was_in_loop_condition = self.is_in_loop_condition;
907 self.is_in_loop_condition = false;
909 let len = self.loop_scopes.len();
910 self.loop_scopes.push(loop_id);
912 let result = f(self);
915 self.loop_scopes.len(),
916 "Loop scopes should be added and removed in stack order"
919 self.loop_scopes.pop().unwrap();
921 self.is_in_loop_condition = was_in_loop_condition;
926 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
928 F: FnOnce(&mut LoweringContext) -> T,
930 let was_in_loop_condition = self.is_in_loop_condition;
931 self.is_in_loop_condition = true;
933 let result = f(self);
935 self.is_in_loop_condition = was_in_loop_condition;
940 fn with_new_scopes<T, F>(&mut self, f: F) -> T
942 F: FnOnce(&mut LoweringContext) -> T,
944 let was_in_loop_condition = self.is_in_loop_condition;
945 self.is_in_loop_condition = false;
947 let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
948 let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
949 let result = f(self);
950 self.catch_scopes = catch_scopes;
951 self.loop_scopes = loop_scopes;
953 self.is_in_loop_condition = was_in_loop_condition;
958 fn def_key(&mut self, id: DefId) -> DefKey {
960 self.resolver.definitions().def_key(id.index)
962 self.cstore.def_key(id)
966 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
967 label.map(|label| hir::Label {
972 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
973 let target_id = match destination {
975 if let Def::Label(loop_id) = self.expect_full_def(id) {
976 Ok(self.lower_node_id(loop_id).node_id)
978 Err(hir::LoopIdError::UnresolvedLabel)
984 .map(|innermost_loop_id| *innermost_loop_id)
985 .map(|id| Ok(self.lower_node_id(id).node_id))
986 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
991 label: self.lower_label(destination.map(|(_, label)| label)),
996 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
999 .map(|a| self.lower_attr(a))
1000 .collect::<Vec<_>>()
1004 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1008 path: attr.path.clone(),
1009 tokens: self.lower_token_stream(attr.tokens.clone()),
1010 is_sugared_doc: attr.is_sugared_doc,
1015 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1018 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1022 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1024 TokenTree::Token(span, token) => self.lower_token(token, span),
1025 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1028 delim: delimited.delim,
1029 tts: self.lower_token_stream(delimited.tts.into()).into(),
1035 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1037 Token::Interpolated(_) => {}
1038 other => return TokenTree::Token(span, other).into(),
1041 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1042 self.lower_token_stream(tts)
1045 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1047 attrs: self.lower_attrs(&arm.attrs),
1048 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1049 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1050 body: P(self.lower_expr(&arm.body)),
1054 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1056 id: self.lower_node_id(b.id).node_id,
1058 ty: self.lower_ty(&b.ty, itctx),
1063 fn lower_generic_arg(&mut self,
1064 arg: &ast::GenericArg,
1065 itctx: ImplTraitContext)
1066 -> hir::GenericArg {
1068 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1069 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1073 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1074 P(self.lower_ty_direct(t, itctx))
1077 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext) -> hir::Ty {
1078 let kind = match t.node {
1079 TyKind::Infer => hir::TyKind::Infer,
1080 TyKind::Err => hir::TyKind::Err,
1081 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1082 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1083 TyKind::Rptr(ref region, ref mt) => {
1084 let span = t.span.shrink_to_lo();
1085 let lifetime = match *region {
1086 Some(ref lt) => self.lower_lifetime(lt),
1087 None => self.elided_ref_lifetime(span),
1089 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1091 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1094 this.with_anonymous_lifetime_mode(
1095 AnonymousLifetimeMode::PassThrough,
1097 hir::TyKind::BareFn(P(hir::BareFnTy {
1098 generic_params: this.lower_generic_params(
1101 ImplTraitContext::Disallowed,
1103 unsafety: this.lower_unsafety(f.unsafety),
1105 decl: this.lower_fn_decl(&f.decl, None, false, None),
1106 arg_names: this.lower_fn_args_to_names(&f.decl),
1112 TyKind::Never => hir::TyKind::Never,
1113 TyKind::Tup(ref tys) => {
1114 hir::TyKind::Tup(tys.iter().map(|ty| {
1115 self.lower_ty_direct(ty, itctx.reborrow())
1118 TyKind::Paren(ref ty) => {
1119 return self.lower_ty_direct(ty, itctx);
1121 TyKind::Path(ref qself, ref path) => {
1122 let id = self.lower_node_id(t.id);
1123 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1124 let ty = self.ty_path(id, t.span, qpath);
1125 if let hir::TyKind::TraitObject(..) = ty.node {
1126 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1130 TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1133 def: self.expect_full_def(t.id),
1134 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1138 TyKind::Array(ref ty, ref length) => {
1139 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1141 TyKind::Typeof(ref expr) => {
1142 hir::TyKind::Typeof(self.lower_anon_const(expr))
1144 TyKind::TraitObject(ref bounds, kind) => {
1145 let mut lifetime_bound = None;
1148 .filter_map(|bound| match *bound {
1149 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1150 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1152 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1153 GenericBound::Outlives(ref lifetime) => {
1154 if lifetime_bound.is_none() {
1155 lifetime_bound = Some(self.lower_lifetime(lifetime));
1161 let lifetime_bound =
1162 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1163 if kind != TraitObjectSyntax::Dyn {
1164 self.maybe_lint_bare_trait(t.span, t.id, false);
1166 hir::TyKind::TraitObject(bounds, lifetime_bound)
1168 TyKind::ImplTrait(def_node_id, ref bounds) => {
1171 ImplTraitContext::Existential(fn_def_id) => {
1172 self.lower_existential_impl_trait(
1173 span, fn_def_id, def_node_id,
1174 |this| this.lower_param_bounds(bounds, itctx),
1177 ImplTraitContext::Universal(in_band_ty_params) => {
1178 self.lower_node_id(def_node_id);
1179 // Add a definition for the in-band TyParam
1180 let def_index = self
1183 .opt_def_index(def_node_id)
1186 let hir_bounds = self.lower_param_bounds(
1188 ImplTraitContext::Universal(in_band_ty_params),
1190 // Set the name to `impl Bound1 + Bound2`
1191 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1192 in_band_ty_params.push(hir::GenericParam {
1194 name: ParamName::Plain(ident),
1195 pure_wrt_drop: false,
1199 kind: hir::GenericParamKind::Type {
1201 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1205 hir::TyKind::Path(hir::QPath::Resolved(
1209 def: Def::TyParam(DefId::local(def_index)),
1210 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1214 ImplTraitContext::Disallowed => {
1219 "`impl Trait` not allowed outside of function \
1220 and inherent method return types"
1226 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1229 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1238 fn lower_existential_impl_trait(
1242 exist_ty_node_id: NodeId,
1243 lower_bounds: impl FnOnce(&mut LoweringContext) -> hir::GenericBounds,
1245 // Make sure we know that some funky desugaring has been going on here.
1246 // This is a first: there is code in other places like for loop
1247 // desugaring that explicitly states that we don't want to track that.
1248 // Not tracking it makes lints in rustc and clippy very fragile as
1249 // frequently opened issues show.
1250 let exist_ty_span = self.allow_internal_unstable(
1251 CompilerDesugaringKind::ExistentialReturnType,
1255 let exist_ty_def_index = self
1258 .opt_def_index(exist_ty_node_id)
1262 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1264 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1266 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1272 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1273 let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1274 generics: hir::Generics {
1275 params: lifetime_defs,
1276 where_clause: hir::WhereClause {
1277 id: lctx.next_id().node_id,
1278 predicates: Vec::new().into(),
1283 impl_trait_fn: Some(fn_def_id),
1285 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1286 // Generate an `existential type Foo: Trait;` declaration
1287 trace!("creating existential type with id {:#?}", exist_ty_id);
1289 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1290 let exist_ty_item = hir::Item {
1291 id: exist_ty_id.node_id,
1292 hir_id: exist_ty_id.hir_id,
1293 name: keywords::Invalid.name(),
1294 attrs: Default::default(),
1295 node: exist_ty_item_kind,
1296 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1297 span: exist_ty_span,
1300 // Insert the item into the global list. This usually happens
1301 // automatically for all AST items. But this existential type item
1302 // does not actually exist in the AST.
1303 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1305 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1306 let path = P(hir::Path {
1307 span: exist_ty_span,
1308 def: Def::Existential(DefId::local(exist_ty_def_index)),
1309 segments: hir_vec![hir::PathSegment {
1311 ident: Ident::new(keywords::Invalid.name(), exist_ty_span),
1312 args: Some(P(hir::GenericArgs {
1313 parenthesized: false,
1314 bindings: HirVec::new(),
1319 hir::TyKind::Path(hir::QPath::Resolved(None, path))
1323 fn lifetimes_from_impl_trait_bounds(
1325 exist_ty_id: NodeId,
1326 parent_index: DefIndex,
1327 bounds: &hir::GenericBounds,
1328 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1329 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1330 // appear in the bounds, excluding lifetimes that are created within the bounds.
1331 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1332 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1333 context: &'r mut LoweringContext<'a>,
1335 exist_ty_id: NodeId,
1336 collect_elided_lifetimes: bool,
1337 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1338 already_defined_lifetimes: HashSet<hir::LifetimeName>,
1339 output_lifetimes: Vec<hir::GenericArg>,
1340 output_lifetime_params: Vec<hir::GenericParam>,
1343 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1344 fn nested_visit_map<'this>(
1346 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1347 hir::intravisit::NestedVisitorMap::None
1350 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1351 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1352 if parameters.parenthesized {
1353 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1354 self.collect_elided_lifetimes = false;
1355 hir::intravisit::walk_generic_args(self, span, parameters);
1356 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1358 hir::intravisit::walk_generic_args(self, span, parameters);
1362 fn visit_ty(&mut self, t: &'v hir::Ty) {
1363 // Don't collect elided lifetimes used inside of `fn()` syntax
1364 if let hir::TyKind::BareFn(_) = t.node {
1365 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1366 self.collect_elided_lifetimes = false;
1368 // Record the "stack height" of `for<'a>` lifetime bindings
1369 // to be able to later fully undo their introduction.
1370 let old_len = self.currently_bound_lifetimes.len();
1371 hir::intravisit::walk_ty(self, t);
1372 self.currently_bound_lifetimes.truncate(old_len);
1374 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1376 hir::intravisit::walk_ty(self, t)
1380 fn visit_poly_trait_ref(
1382 trait_ref: &'v hir::PolyTraitRef,
1383 modifier: hir::TraitBoundModifier,
1385 // Record the "stack height" of `for<'a>` lifetime bindings
1386 // to be able to later fully undo their introduction.
1387 let old_len = self.currently_bound_lifetimes.len();
1388 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1389 self.currently_bound_lifetimes.truncate(old_len);
1392 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1393 // Record the introduction of 'a in `for<'a> ...`
1394 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1395 // Introduce lifetimes one at a time so that we can handle
1396 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1397 let lt_name = hir::LifetimeName::Param(param.name);
1398 self.currently_bound_lifetimes.push(lt_name);
1401 hir::intravisit::walk_generic_param(self, param);
1404 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1405 let name = match lifetime.name {
1406 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1407 if self.collect_elided_lifetimes {
1408 // Use `'_` for both implicit and underscore lifetimes in
1409 // `abstract type Foo<'_>: SomeTrait<'_>;`
1410 hir::LifetimeName::Underscore
1415 hir::LifetimeName::Param(_) => lifetime.name,
1416 hir::LifetimeName::Static => return,
1419 if !self.currently_bound_lifetimes.contains(&name)
1420 && !self.already_defined_lifetimes.contains(&name) {
1421 self.already_defined_lifetimes.insert(name);
1423 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1424 id: self.context.next_id().node_id,
1425 span: lifetime.span,
1429 // We need to manually create the ids here, because the
1430 // definitions will go into the explicit `existential type`
1431 // declaration and thus need to have their owner set to that item
1432 let def_node_id = self.context.sess.next_node_id();
1433 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1434 self.context.resolver.definitions().create_def_with_parent(
1437 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1438 DefIndexAddressSpace::High,
1443 let name = match name {
1444 hir::LifetimeName::Underscore => {
1445 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident())
1447 hir::LifetimeName::Param(param_name) => param_name,
1448 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1451 self.output_lifetime_params.push(hir::GenericParam {
1454 span: lifetime.span,
1455 pure_wrt_drop: false,
1458 kind: hir::GenericParamKind::Lifetime {
1466 let mut lifetime_collector = ImplTraitLifetimeCollector {
1468 parent: parent_index,
1470 collect_elided_lifetimes: true,
1471 currently_bound_lifetimes: Vec::new(),
1472 already_defined_lifetimes: HashSet::new(),
1473 output_lifetimes: Vec::new(),
1474 output_lifetime_params: Vec::new(),
1477 for bound in bounds {
1478 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1482 lifetime_collector.output_lifetimes.into(),
1483 lifetime_collector.output_lifetime_params.into(),
1487 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1492 .map(|x| self.lower_foreign_item(x))
1497 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1504 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1506 node: hir::VariantKind {
1507 name: v.node.ident.name,
1508 attrs: self.lower_attrs(&v.node.attrs),
1509 data: self.lower_variant_data(&v.node.data),
1510 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1519 qself: &Option<QSelf>,
1521 param_mode: ParamMode,
1522 mut itctx: ImplTraitContext,
1524 let qself_position = qself.as_ref().map(|q| q.position);
1525 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1527 let resolution = self.resolver
1529 .unwrap_or(PathResolution::new(Def::Err));
1531 let proj_start = p.segments.len() - resolution.unresolved_segments();
1532 let path = P(hir::Path {
1533 def: resolution.base_def(),
1534 segments: p.segments[..proj_start]
1537 .map(|(i, segment)| {
1538 let param_mode = match (qself_position, param_mode) {
1539 (Some(j), ParamMode::Optional) if i < j => {
1540 // This segment is part of the trait path in a
1541 // qualified path - one of `a`, `b` or `Trait`
1542 // in `<X as a::b::Trait>::T::U::method`.
1548 // Figure out if this is a type/trait segment,
1549 // which may need lifetime elision performed.
1550 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1551 krate: def_id.krate,
1552 index: this.def_key(def_id).parent.expect("missing parent"),
1554 let type_def_id = match resolution.base_def() {
1555 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1556 Some(parent_def_id(self, def_id))
1558 Def::Variant(def_id) if i + 1 == proj_start => {
1559 Some(parent_def_id(self, def_id))
1562 | Def::Union(def_id)
1564 | Def::TyAlias(def_id)
1565 | Def::Trait(def_id) if i + 1 == proj_start =>
1571 let parenthesized_generic_args = match resolution.base_def() {
1572 // `a::b::Trait(Args)`
1573 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1574 // `a::b::Trait(Args)::TraitItem`
1575 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1576 if i + 2 == proj_start =>
1578 ParenthesizedGenericArgs::Ok
1580 // Avoid duplicated errors
1581 Def::Err => ParenthesizedGenericArgs::Ok,
1587 | Def::Variant(..) if i + 1 == proj_start =>
1589 ParenthesizedGenericArgs::Err
1591 // A warning for now, for compatibility reasons
1592 _ => ParenthesizedGenericArgs::Warn,
1595 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1596 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1599 assert!(!def_id.is_local());
1601 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1602 let n = item_generics.own_counts().lifetimes;
1603 self.type_def_lifetime_params.insert(def_id, n);
1606 self.lower_path_segment(
1611 parenthesized_generic_args,
1619 // Simple case, either no projections, or only fully-qualified.
1620 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1621 if resolution.unresolved_segments() == 0 {
1622 return hir::QPath::Resolved(qself, path);
1625 // Create the innermost type that we're projecting from.
1626 let mut ty = if path.segments.is_empty() {
1627 // If the base path is empty that means there exists a
1628 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1629 qself.expect("missing QSelf for <T>::...")
1631 // Otherwise, the base path is an implicit `Self` type path,
1632 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1633 // `<I as Iterator>::Item::default`.
1634 let new_id = self.next_id();
1635 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1638 // Anything after the base path are associated "extensions",
1639 // out of which all but the last one are associated types,
1640 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1641 // * base path is `std::vec::Vec<T>`
1642 // * "extensions" are `IntoIter`, `Item` and `clone`
1643 // * type nodes are:
1644 // 1. `std::vec::Vec<T>` (created above)
1645 // 2. `<std::vec::Vec<T>>::IntoIter`
1646 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1647 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1648 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1649 let segment = P(self.lower_path_segment(
1654 ParenthesizedGenericArgs::Warn,
1657 let qpath = hir::QPath::TypeRelative(ty, segment);
1659 // It's finished, return the extension of the right node type.
1660 if i == p.segments.len() - 1 {
1664 // Wrap the associated extension in another type node.
1665 let new_id = self.next_id();
1666 ty = P(self.ty_path(new_id, p.span, qpath));
1669 // Should've returned in the for loop above.
1672 "lower_qpath: no final extension segment in {}..{}",
1678 fn lower_path_extra(
1682 ident: Option<Ident>,
1683 param_mode: ParamMode,
1687 segments: p.segments
1690 self.lower_path_segment(
1695 ParenthesizedGenericArgs::Err,
1696 ImplTraitContext::Disallowed,
1699 .chain(ident.map(|ident| hir::PathSegment::from_ident(ident)))
1705 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1706 let def = self.expect_full_def(id);
1707 self.lower_path_extra(def, p, None, param_mode)
1710 fn lower_path_segment(
1713 segment: &PathSegment,
1714 param_mode: ParamMode,
1715 expected_lifetimes: usize,
1716 parenthesized_generic_args: ParenthesizedGenericArgs,
1717 itctx: ImplTraitContext,
1718 ) -> hir::PathSegment {
1719 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1720 let msg = "parenthesized parameters may only be used with a trait";
1721 match **generic_args {
1722 GenericArgs::AngleBracketed(ref data) => {
1723 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1725 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1726 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1727 ParenthesizedGenericArgs::Warn => {
1728 self.sess.buffer_lint(
1729 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1734 (hir::GenericArgs::none(), true)
1736 ParenthesizedGenericArgs::Err => {
1737 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1738 .span_label(data.span, "only traits may use parentheses")
1740 (hir::GenericArgs::none(), true)
1745 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1748 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1749 GenericArg::Lifetime(_) => true,
1752 let first_generic_span = generic_args.args.iter().map(|a| a.span())
1753 .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1754 if !generic_args.parenthesized && !has_lifetimes {
1756 self.elided_path_lifetimes(path_span, expected_lifetimes)
1758 .map(|lt| GenericArg::Lifetime(lt))
1759 .chain(generic_args.args.into_iter())
1761 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1762 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1763 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1764 let no_bindings = generic_args.bindings.is_empty();
1765 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1766 // If there are no (non-implicit) generic args or associated-type
1767 // bindings, our suggestion includes the angle brackets
1768 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1770 // Otherwise—sorry, this is kind of gross—we need to infer the
1771 // place to splice in the `'_, ` from the generics that do exist
1772 let first_generic_span = first_generic_span
1773 .expect("already checked that type args or bindings exist");
1774 (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1776 self.sess.buffer_lint_with_diagnostic(
1777 ELIDED_LIFETIMES_IN_PATHS,
1780 "hidden lifetime parameters in types are deprecated",
1781 builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1782 expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1788 hir::PathSegment::new(
1795 fn lower_angle_bracketed_parameter_data(
1797 data: &AngleBracketedArgs,
1798 param_mode: ParamMode,
1799 mut itctx: ImplTraitContext,
1800 ) -> (hir::GenericArgs, bool) {
1801 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1802 let has_types = args.iter().any(|arg| match arg {
1803 ast::GenericArg::Type(_) => true,
1807 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1808 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1809 parenthesized: false,
1811 !has_types && param_mode == ParamMode::Optional)
1814 fn lower_parenthesized_parameter_data(
1816 data: &ParenthesisedArgs,
1817 ) -> (hir::GenericArgs, bool) {
1818 // Switch to `PassThrough` mode for anonymous lifetimes: this
1819 // means that we permit things like `&Ref<T>`, where `Ref` has
1820 // a hidden lifetime parameter. This is needed for backwards
1821 // compatibility, even in contexts like an impl header where
1822 // we generally don't permit such things (see #51008).
1823 self.with_anonymous_lifetime_mode(
1824 AnonymousLifetimeMode::PassThrough,
1826 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1827 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1828 let inputs = inputs.iter().map(|ty| this.lower_ty_direct(ty, DISALLOWED)).collect();
1829 let mk_tup = |this: &mut Self, tys, span| {
1830 let LoweredNodeId { node_id, hir_id } = this.next_id();
1831 hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1836 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1839 id: this.next_id().node_id,
1840 ident: Ident::from_str(FN_OUTPUT_NAME),
1843 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1844 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1845 span: output.as_ref().map_or(span, |ty| ty.span),
1848 parenthesized: true,
1856 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1857 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1863 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1864 pat: self.lower_pat(&l.pat),
1865 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1867 attrs: l.attrs.clone(),
1868 source: hir::LocalSource::Normal,
1872 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1874 Mutability::Mutable => hir::MutMutable,
1875 Mutability::Immutable => hir::MutImmutable,
1879 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1880 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1884 pat: self.lower_pat(&arg.pat),
1888 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1891 .map(|arg| match arg.pat.node {
1892 PatKind::Ident(_, ident, _) => ident,
1893 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
1898 // Lowers a function declaration.
1900 // decl: the unlowered (ast) function declaration.
1901 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1902 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1903 // make_ret_async is also `Some`.
1904 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1905 // This guards against trait declarations and implementations where impl Trait is
1907 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1908 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
1909 // return type impl Trait item.
1913 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
1914 impl_trait_return_allow: bool,
1915 make_ret_async: Option<NodeId>,
1916 ) -> P<hir::FnDecl> {
1917 let inputs = decl.inputs
1920 if let Some((_, ref mut ibty)) = in_band_ty_params {
1921 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
1923 self.lower_ty_direct(&arg.ty, ImplTraitContext::Disallowed)
1926 .collect::<HirVec<_>>();
1928 let output = if let Some(ret_id) = make_ret_async {
1929 self.lower_async_fn_ret_ty(
1932 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
1937 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
1938 Some((def_id, _)) if impl_trait_return_allow => {
1939 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1941 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1943 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1950 variadic: decl.variadic,
1951 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1952 TyKind::ImplicitSelf => true,
1953 TyKind::Rptr(_, ref mt) => mt.ty.node.is_implicit_self(),
1959 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
1961 // fn_span: the span of the async function declaration. Used for error reporting.
1962 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
1963 // output: unlowered output type (`T` in `-> T`)
1964 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
1965 fn lower_async_fn_ret_ty(
1968 output: &FunctionRetTy,
1970 return_impl_trait_id: NodeId,
1971 ) -> hir::FunctionRetTy {
1972 // Get lifetimes used in the input arguments to the function. Our output type must also
1973 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
1974 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
1975 // is a subset of the other. We really want some new lifetime that is a subset of all input
1976 // lifetimes, but that doesn't exist at the moment.
1978 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
1979 context: &'r mut LoweringContext<'a>,
1980 // Lifetimes bound by HRTB
1981 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1982 // Whether to count elided lifetimes.
1983 // Disabled inside of `Fn` or `fn` syntax.
1984 collect_elided_lifetimes: bool,
1985 // The lifetime found.
1986 // Multiple different or elided lifetimes cannot appear in async fn for now.
1987 output_lifetime: Option<(hir::LifetimeName, Span)>,
1990 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
1991 fn nested_visit_map<'this>(
1993 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1994 hir::intravisit::NestedVisitorMap::None
1997 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1998 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1999 if parameters.parenthesized {
2000 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2001 self.collect_elided_lifetimes = false;
2002 hir::intravisit::walk_generic_args(self, span, parameters);
2003 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2005 hir::intravisit::walk_generic_args(self, span, parameters);
2009 fn visit_ty(&mut self, t: &'v hir::Ty) {
2010 // Don't collect elided lifetimes used inside of `fn()` syntax
2011 if let &hir::TyKind::BareFn(_) = &t.node {
2012 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2013 self.collect_elided_lifetimes = false;
2015 // Record the "stack height" of `for<'a>` lifetime bindings
2016 // to be able to later fully undo their introduction.
2017 let old_len = self.currently_bound_lifetimes.len();
2018 hir::intravisit::walk_ty(self, t);
2019 self.currently_bound_lifetimes.truncate(old_len);
2021 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2023 hir::intravisit::walk_ty(self, t);
2027 fn visit_poly_trait_ref(
2029 trait_ref: &'v hir::PolyTraitRef,
2030 modifier: hir::TraitBoundModifier,
2032 // Record the "stack height" of `for<'a>` lifetime bindings
2033 // to be able to later fully undo their introduction.
2034 let old_len = self.currently_bound_lifetimes.len();
2035 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2036 self.currently_bound_lifetimes.truncate(old_len);
2039 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2040 // Record the introduction of 'a in `for<'a> ...`
2041 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2042 // Introduce lifetimes one at a time so that we can handle
2043 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2044 let lt_name = hir::LifetimeName::Param(param.name);
2045 self.currently_bound_lifetimes.push(lt_name);
2048 hir::intravisit::walk_generic_param(self, param);
2051 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2052 let name = match lifetime.name {
2053 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2054 if self.collect_elided_lifetimes {
2055 // Use `'_` for both implicit and underscore lifetimes in
2056 // `abstract type Foo<'_>: SomeTrait<'_>;`
2057 hir::LifetimeName::Underscore
2062 hir::LifetimeName::Param(_) => lifetime.name,
2063 hir::LifetimeName::Static => return,
2066 if !self.currently_bound_lifetimes.contains(&name) {
2067 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2068 // We don't currently have a reliable way to desugar `async fn` with
2069 // multiple potentially unrelated input lifetimes into
2070 // `-> impl Trait + 'lt`, so we report an error in this case.
2071 if current_lt_name != name {
2074 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2076 "multiple different lifetimes used in arguments of `async fn`",
2078 .span_label(current_lt_span, "first lifetime here")
2079 .span_label(lifetime.span, "different lifetime here")
2080 .help("`async fn` can only accept borrowed values \
2081 with identical lifetimes")
2083 } else if current_lt_name.is_elided() && name.is_elided() {
2086 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2088 "multiple elided 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("consider giving these arguments named lifetimes")
2096 self.output_lifetime = Some((name, lifetime.span));
2102 let bound_lifetime = {
2103 let mut lifetime_collector = AsyncFnLifetimeCollector {
2105 currently_bound_lifetimes: Vec::new(),
2106 collect_elided_lifetimes: true,
2107 output_lifetime: None,
2111 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2113 lifetime_collector.output_lifetime
2116 let span = match output {
2117 FunctionRetTy::Ty(ty) => ty.span,
2118 FunctionRetTy::Default(span) => *span,
2121 let impl_trait_ty = self.lower_existential_impl_trait(
2122 span, fn_def_id, return_impl_trait_id, |this| {
2123 let output_ty = match output {
2124 FunctionRetTy::Ty(ty) =>
2125 this.lower_ty(ty, ImplTraitContext::Existential(fn_def_id)),
2126 FunctionRetTy::Default(span) => {
2127 let LoweredNodeId { node_id, hir_id } = this.next_id();
2131 node: hir::TyKind::Tup(hir_vec![]),
2138 let future_params = P(hir::GenericArgs {
2140 bindings: hir_vec![hir::TypeBinding {
2141 ident: Ident::from_str(FN_OUTPUT_NAME),
2143 id: this.next_id().node_id,
2146 parenthesized: false,
2150 this.std_path(span, &["future", "Future"], Some(future_params), false);
2152 let mut bounds = vec![
2153 hir::GenericBound::Trait(
2155 trait_ref: hir::TraitRef {
2157 ref_id: this.next_id().node_id,
2159 bound_generic_params: hir_vec![],
2162 hir::TraitBoundModifier::None
2166 if let Some((name, span)) = bound_lifetime {
2167 bounds.push(hir::GenericBound::Outlives(
2168 hir::Lifetime { id: this.next_id().node_id, name, span }));
2171 hir::HirVec::from(bounds)
2174 let LoweredNodeId { node_id, hir_id } = self.next_id();
2175 let impl_trait_ty = P(hir::Ty {
2177 node: impl_trait_ty,
2182 hir::FunctionRetTy::Return(impl_trait_ty)
2185 fn lower_param_bound(
2188 itctx: ImplTraitContext,
2189 ) -> hir::GenericBound {
2191 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2192 self.lower_poly_trait_ref(ty, itctx),
2193 self.lower_trait_bound_modifier(modifier),
2195 GenericBound::Outlives(ref lifetime) => {
2196 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2201 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2202 let span = l.ident.span;
2204 ident if ident.name == keywords::StaticLifetime.name() =>
2205 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2206 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2207 match self.anonymous_lifetime_mode {
2208 AnonymousLifetimeMode::CreateParameter => {
2209 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2210 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2213 AnonymousLifetimeMode::PassThrough => {
2214 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2218 self.maybe_collect_in_band_lifetime(ident);
2219 let param_name = ParamName::Plain(ident);
2220 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2225 fn new_named_lifetime(
2229 name: hir::LifetimeName,
2230 ) -> hir::Lifetime {
2232 id: self.lower_node_id(id).node_id,
2238 fn lower_generic_params(
2240 params: &[GenericParam],
2241 add_bounds: &NodeMap<Vec<GenericBound>>,
2242 mut itctx: ImplTraitContext,
2243 ) -> hir::HirVec<hir::GenericParam> {
2244 params.iter().map(|param| {
2245 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2249 fn lower_generic_param(&mut self,
2250 param: &GenericParam,
2251 add_bounds: &NodeMap<Vec<GenericBound>>,
2252 mut itctx: ImplTraitContext)
2253 -> hir::GenericParam {
2254 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx.reborrow());
2256 GenericParamKind::Lifetime => {
2257 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2258 self.is_collecting_in_band_lifetimes = false;
2260 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
2261 let param_name = match lt.name {
2262 hir::LifetimeName::Param(param_name) => param_name,
2263 _ => hir::ParamName::Plain(lt.name.ident()),
2265 let param = hir::GenericParam {
2269 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2270 attrs: self.lower_attrs(¶m.attrs),
2272 kind: hir::GenericParamKind::Lifetime { in_band: false }
2275 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2279 GenericParamKind::Type { ref default, .. } => {
2280 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2281 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2282 // Instead, use gensym("Self") to create a distinct name that looks the same.
2283 let ident = if param.ident.name == keywords::SelfType.name() {
2284 param.ident.gensym()
2289 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2290 if !add_bounds.is_empty() {
2291 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2292 bounds = bounds.into_iter()
2298 id: self.lower_node_id(param.id).node_id,
2299 name: hir::ParamName::Plain(ident),
2300 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2301 attrs: self.lower_attrs(¶m.attrs),
2304 kind: hir::GenericParamKind::Type {
2305 default: default.as_ref().map(|x| {
2306 self.lower_ty(x, ImplTraitContext::Disallowed)
2308 synthetic: param.attrs.iter()
2309 .filter(|attr| attr.check_name("rustc_synthetic"))
2310 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2320 generics: &Generics,
2321 itctx: ImplTraitContext)
2324 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2325 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2326 // paths where report_error is called are also the only paths that advance to after
2327 // the match statement, so the error reporting could probably just be moved there.
2328 let mut add_bounds = NodeMap();
2329 for pred in &generics.where_clause.predicates {
2330 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2331 'next_bound: for bound in &bound_pred.bounds {
2332 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2333 let report_error = |this: &mut Self| {
2334 this.diagnostic().span_err(
2335 bound_pred.bounded_ty.span,
2336 "`?Trait` bounds are only permitted at the \
2337 point where a type parameter is declared",
2340 // Check if the where clause type is a plain type parameter.
2341 match bound_pred.bounded_ty.node {
2342 TyKind::Path(None, ref path)
2343 if path.segments.len() == 1
2344 && bound_pred.bound_generic_params.is_empty() =>
2346 if let Some(Def::TyParam(def_id)) = self.resolver
2347 .get_resolution(bound_pred.bounded_ty.id)
2348 .map(|d| d.base_def())
2350 if let Some(node_id) =
2351 self.resolver.definitions().as_local_node_id(def_id)
2353 for param in &generics.params {
2355 GenericParamKind::Type { .. } => {
2356 if node_id == param.id {
2357 add_bounds.entry(param.id)
2358 .or_insert(Vec::new())
2359 .push(bound.clone());
2360 continue 'next_bound;
2370 _ => report_error(self),
2378 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2379 where_clause: self.lower_where_clause(&generics.where_clause),
2380 span: generics.span,
2384 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2386 id: self.lower_node_id(wc.id).node_id,
2387 predicates: wc.predicates
2389 .map(|predicate| self.lower_where_predicate(predicate))
2394 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2396 WherePredicate::BoundPredicate(WhereBoundPredicate {
2397 ref bound_generic_params,
2402 self.with_in_scope_lifetime_defs(
2403 &bound_generic_params,
2405 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2406 bound_generic_params: this.lower_generic_params(
2407 bound_generic_params,
2409 ImplTraitContext::Disallowed,
2411 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2414 .filter_map(|bound| match *bound {
2415 // Ignore `?Trait` bounds.
2416 // Tthey were copied into type parameters already.
2417 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2418 _ => Some(this.lower_param_bound(
2420 ImplTraitContext::Disallowed,
2429 WherePredicate::RegionPredicate(WhereRegionPredicate {
2433 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2435 lifetime: self.lower_lifetime(lifetime),
2436 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2438 WherePredicate::EqPredicate(WhereEqPredicate {
2443 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2444 id: self.lower_node_id(id).node_id,
2445 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2446 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2452 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2454 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2458 .map(|f| self.lower_struct_field(f))
2460 self.lower_node_id(id).node_id,
2462 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2466 .map(|f| self.lower_struct_field(f))
2468 self.lower_node_id(id).node_id,
2470 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2474 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2475 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2476 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2477 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2481 ref_id: self.lower_node_id(p.ref_id).node_id,
2485 fn lower_poly_trait_ref(
2488 mut itctx: ImplTraitContext,
2489 ) -> hir::PolyTraitRef {
2490 let bound_generic_params =
2491 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx.reborrow());
2492 let trait_ref = self.with_parent_impl_lifetime_defs(
2493 &bound_generic_params,
2494 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2498 bound_generic_params,
2504 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2507 id: self.lower_node_id(f.id).node_id,
2508 ident: match f.ident {
2509 Some(ident) => ident,
2510 // FIXME(jseyfried) positional field hygiene
2511 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2513 vis: self.lower_visibility(&f.vis, None),
2514 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2515 attrs: self.lower_attrs(&f.attrs),
2519 fn lower_field(&mut self, f: &Field) -> hir::Field {
2521 id: self.next_id().node_id,
2523 expr: P(self.lower_expr(&f.expr)),
2525 is_shorthand: f.is_shorthand,
2529 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2531 ty: self.lower_ty(&mt.ty, itctx),
2532 mutbl: self.lower_mutability(mt.mutbl),
2536 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext)
2537 -> hir::GenericBounds {
2538 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2541 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2542 let mut expr = None;
2544 let mut stmts = vec![];
2546 for (index, stmt) in b.stmts.iter().enumerate() {
2547 if index == b.stmts.len() - 1 {
2548 if let StmtKind::Expr(ref e) = stmt.node {
2549 expr = Some(P(self.lower_expr(e)));
2551 stmts.extend(self.lower_stmt(stmt));
2554 stmts.extend(self.lower_stmt(stmt));
2558 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2563 stmts: stmts.into(),
2565 rules: self.lower_block_check_mode(&b.rules),
2568 recovered: b.recovered,
2572 fn lower_async_body(
2578 self.lower_body(Some(decl), |this| {
2579 if let IsAsync::Async { closure_id, .. } = asyncness {
2580 let async_expr = this.make_async_expr(
2581 CaptureBy::Value, closure_id, None,
2583 let body = this.lower_block(body, false);
2584 this.expr_block(body, ThinVec::new())
2586 this.expr(body.span, async_expr, ThinVec::new())
2588 let body = this.lower_block(body, false);
2589 this.expr_block(body, ThinVec::new())
2598 attrs: &hir::HirVec<Attribute>,
2599 vis: &mut hir::Visibility,
2601 ) -> hir::ItemKind {
2603 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2604 ItemKind::Use(ref use_tree) => {
2605 // Start with an empty prefix
2608 span: use_tree.span,
2611 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2613 ItemKind::Static(ref t, m, ref e) => {
2614 let value = self.lower_body(None, |this| this.lower_expr(e));
2615 hir::ItemKind::Static(
2616 self.lower_ty(t, ImplTraitContext::Disallowed),
2617 self.lower_mutability(m),
2621 ItemKind::Const(ref t, ref e) => {
2622 let value = self.lower_body(None, |this| this.lower_expr(e));
2623 hir::ItemKind::Const(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2625 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2626 let fn_def_id = self.resolver.definitions().local_def_id(id);
2628 self.with_new_scopes(|this| {
2629 // Note: we don't need to change the return type from `T` to
2630 // `impl Future<Output = T>` here because lower_body
2631 // only cares about the input argument patterns in the function
2632 // declaration (decl), not the return types.
2633 let body_id = this.lower_async_body(decl, header.asyncness, body);
2635 let (generics, fn_decl) = this.add_in_band_defs(
2638 AnonymousLifetimeMode::PassThrough,
2639 |this, idty| this.lower_fn_decl(
2640 decl, Some((fn_def_id, idty)), true, header.asyncness.opt_return_id()),
2645 this.lower_fn_header(header),
2651 ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2652 ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2653 ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2654 ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2655 self.lower_ty(t, ImplTraitContext::Disallowed),
2656 self.lower_generics(generics, ImplTraitContext::Disallowed),
2658 ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2659 generics: self.lower_generics(generics, ImplTraitContext::Disallowed),
2660 bounds: self.lower_param_bounds(b, ImplTraitContext::Disallowed),
2661 impl_trait_fn: None,
2663 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2665 variants: enum_definition
2668 .map(|x| self.lower_variant(x))
2671 self.lower_generics(generics, ImplTraitContext::Disallowed),
2673 ItemKind::Struct(ref struct_def, ref generics) => {
2674 let struct_def = self.lower_variant_data(struct_def);
2675 hir::ItemKind::Struct(
2677 self.lower_generics(generics, ImplTraitContext::Disallowed),
2680 ItemKind::Union(ref vdata, ref generics) => {
2681 let vdata = self.lower_variant_data(vdata);
2682 hir::ItemKind::Union(
2684 self.lower_generics(generics, ImplTraitContext::Disallowed),
2696 let def_id = self.resolver.definitions().local_def_id(id);
2698 // Lower the "impl header" first. This ordering is important
2699 // for in-band lifetimes! Consider `'a` here:
2701 // impl Foo<'a> for u32 {
2702 // fn method(&'a self) { .. }
2705 // Because we start by lowering the `Foo<'a> for u32`
2706 // part, we will add `'a` to the list of generics on
2707 // the impl. When we then encounter it later in the
2708 // method, it will not be considered an in-band
2709 // lifetime to be added, but rather a reference to a
2711 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2714 AnonymousLifetimeMode::CreateParameter,
2716 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2717 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2720 if let Some(ref trait_ref) = trait_ref {
2721 if let Def::Trait(def_id) = trait_ref.path.def {
2722 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2726 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2728 (trait_ref, lowered_ty)
2732 let new_impl_items = self.with_in_scope_lifetime_defs(
2733 &ast_generics.params,
2737 .map(|item| this.lower_impl_item_ref(item))
2742 hir::ItemKind::Impl(
2743 self.lower_unsafety(unsafety),
2744 self.lower_impl_polarity(polarity),
2745 self.lower_defaultness(defaultness, true /* [1] */),
2752 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2753 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2756 .map(|item| self.lower_trait_item_ref(item))
2758 hir::ItemKind::Trait(
2759 self.lower_is_auto(is_auto),
2760 self.lower_unsafety(unsafety),
2761 self.lower_generics(generics, ImplTraitContext::Disallowed),
2766 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
2767 self.lower_generics(generics, ImplTraitContext::Disallowed),
2768 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2770 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2773 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2774 // not cause an assertion failure inside the `lower_defaultness` function
2782 vis: &mut hir::Visibility,
2784 attrs: &hir::HirVec<Attribute>,
2785 ) -> hir::ItemKind {
2786 let path = &tree.prefix;
2789 UseTreeKind::Simple(rename, id1, id2) => {
2790 *name = tree.ident().name;
2792 // First apply the prefix to the path
2793 let mut path = Path {
2797 .chain(path.segments.iter())
2803 // Correctly resolve `self` imports
2804 if path.segments.len() > 1
2805 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2807 let _ = path.segments.pop();
2808 if rename.is_none() {
2809 *name = path.segments.last().unwrap().ident.name;
2813 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2814 let mut defs = self.expect_full_def_from_use(id);
2815 // we want to return *something* from this function, so hang onto the first item
2817 let ret_def = defs.next().unwrap_or(Def::Err);
2819 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2820 let vis = vis.clone();
2821 let name = name.clone();
2822 let span = path.span;
2823 self.resolver.definitions().create_def_with_parent(
2827 DefIndexAddressSpace::High,
2830 self.allocate_hir_id_counter(new_node_id, &path);
2832 self.with_hir_id_owner(new_node_id, |this| {
2833 let new_id = this.lower_node_id(new_node_id);
2834 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2835 let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
2836 let vis_kind = match vis.node {
2837 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2838 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2839 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2840 hir::VisibilityKind::Restricted { ref path, id: _ } => {
2841 hir::VisibilityKind::Restricted {
2843 // We are allocating a new NodeId here
2844 id: this.next_id().node_id,
2848 let vis = respan(vis.span, vis_kind);
2854 hir_id: new_id.hir_id,
2856 attrs: attrs.clone(),
2865 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2866 hir::ItemKind::Use(path, hir::UseKind::Single)
2868 UseTreeKind::Glob => {
2869 let path = P(self.lower_path(
2875 .chain(path.segments.iter())
2880 ParamMode::Explicit,
2882 hir::ItemKind::Use(path, hir::UseKind::Glob)
2884 UseTreeKind::Nested(ref trees) => {
2889 .chain(path.segments.iter())
2892 span: prefix.span.to(path.span),
2895 // Add all the nested PathListItems in the HIR
2896 for &(ref use_tree, id) in trees {
2897 self.allocate_hir_id_counter(id, &use_tree);
2901 } = self.lower_node_id(id);
2903 let mut vis = vis.clone();
2904 let mut name = name.clone();
2906 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2908 self.with_hir_id_owner(new_id, |this| {
2909 let vis_kind = match vis.node {
2910 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2911 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2912 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2913 hir::VisibilityKind::Restricted { ref path, id: _ } => {
2914 hir::VisibilityKind::Restricted {
2916 // We are allocating a new NodeId here
2917 id: this.next_id().node_id,
2921 let vis = respan(vis.span, vis_kind);
2929 attrs: attrs.clone(),
2932 span: use_tree.span,
2938 // Privatize the degenerate import base, used only to check
2939 // the stability of `use a::{};`, to avoid it showing up as
2940 // a re-export by accident when `pub`, e.g. in documentation.
2941 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2942 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
2943 hir::ItemKind::Use(path, hir::UseKind::ListStem)
2948 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2949 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2950 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2952 let (generics, node) = match i.node {
2953 TraitItemKind::Const(ref ty, ref default) => (
2954 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2955 hir::TraitItemKind::Const(
2956 self.lower_ty(ty, ImplTraitContext::Disallowed),
2959 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2962 TraitItemKind::Method(ref sig, None) => {
2963 let names = self.lower_fn_args_to_names(&sig.decl);
2964 let (generics, sig) = self.lower_method_sig(
2971 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
2973 TraitItemKind::Method(ref sig, Some(ref body)) => {
2974 let body_id = self.lower_body(Some(&sig.decl), |this| {
2975 let body = this.lower_block(body, false);
2976 this.expr_block(body, ThinVec::new())
2979 let (generics, sig) = self.lower_method_sig(
2987 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
2989 TraitItemKind::Type(ref bounds, ref default) => (
2990 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2991 hir::TraitItemKind::Type(
2992 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2995 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2998 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3005 attrs: self.lower_attrs(&i.attrs),
3012 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3013 let (kind, has_default) = match i.node {
3014 TraitItemKind::Const(_, ref default) => {
3015 (hir::AssociatedItemKind::Const, default.is_some())
3017 TraitItemKind::Type(_, ref default) => {
3018 (hir::AssociatedItemKind::Type, default.is_some())
3020 TraitItemKind::Method(ref sig, ref default) => (
3021 hir::AssociatedItemKind::Method {
3022 has_self: sig.decl.has_self(),
3026 TraitItemKind::Macro(..) => unimplemented!(),
3029 id: hir::TraitItemId { node_id: i.id },
3032 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3037 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3038 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3039 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3041 let (generics, node) = match i.node {
3042 ImplItemKind::Const(ref ty, ref expr) => {
3043 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3045 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3046 hir::ImplItemKind::Const(
3047 self.lower_ty(ty, ImplTraitContext::Disallowed),
3052 ImplItemKind::Method(ref sig, ref body) => {
3053 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3054 let impl_trait_return_allow = !self.is_in_trait_impl;
3055 let (generics, sig) = self.lower_method_sig(
3059 impl_trait_return_allow,
3060 sig.header.asyncness.opt_return_id(),
3062 (generics, hir::ImplItemKind::Method(sig, body_id))
3064 ImplItemKind::Type(ref ty) => (
3065 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3066 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
3068 ImplItemKind::Existential(ref bounds) => (
3069 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3070 hir::ImplItemKind::Existential(
3071 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
3074 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3081 attrs: self.lower_attrs(&i.attrs),
3083 vis: self.lower_visibility(&i.vis, None),
3084 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3089 // [1] since `default impl` is not yet implemented, this is always true in impls
3092 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3094 id: hir::ImplItemId { node_id: i.id },
3097 vis: self.lower_visibility(&i.vis, Some(i.id)),
3098 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3099 kind: match i.node {
3100 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3101 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3102 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3103 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3104 has_self: sig.decl.has_self(),
3106 ImplItemKind::Macro(..) => unimplemented!(),
3110 // [1] since `default impl` is not yet implemented, this is always true in impls
3113 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3116 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3120 /// Lowers `impl Trait` items and appends them to the list
3121 fn lower_impl_trait_ids(
3125 ids: &mut SmallVector<hir::ItemId>,
3127 if let Some(id) = header.asyncness.opt_return_id() {
3128 ids.push(hir::ItemId { id });
3130 struct IdVisitor<'a> { ids: &'a mut SmallVector<hir::ItemId> }
3131 impl<'a, 'b> Visitor<'a> for IdVisitor<'b> {
3132 fn visit_ty(&mut self, ty: &'a Ty) {
3138 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
3141 visit::walk_ty(self, ty);
3143 fn visit_path_segment(
3146 path_segment: &'v PathSegment,
3148 if let Some(ref p) = path_segment.args {
3149 if let GenericArgs::Parenthesized(_) = **p {
3153 visit::walk_path_segment(self, path_span, path_segment)
3156 let mut visitor = IdVisitor { ids };
3158 FunctionRetTy::Default(_) => {},
3159 FunctionRetTy::Ty(ref ty) => visitor.visit_ty(ty),
3163 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
3165 ItemKind::Use(ref use_tree) => {
3166 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
3167 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3170 ItemKind::MacroDef(..) => SmallVector::new(),
3171 ItemKind::Fn(ref decl, ref header, ..) => {
3172 let mut ids = SmallVector::one(hir::ItemId { id: i.id });
3173 self.lower_impl_trait_ids(decl, header, &mut ids);
3176 ItemKind::Impl(.., None, _, ref items) => {
3177 let mut ids = SmallVector::one(hir::ItemId { id: i.id });
3179 if let ImplItemKind::Method(ref sig, _) = item.node {
3180 self.lower_impl_trait_ids(&sig.decl, &sig.header, &mut ids);
3185 _ => SmallVector::one(hir::ItemId { id: i.id }),
3189 fn lower_item_id_use_tree(&mut self,
3192 vec: &mut SmallVector<hir::ItemId>)
3195 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3196 vec.push(hir::ItemId { id });
3197 self.lower_item_id_use_tree(nested, id, vec);
3199 UseTreeKind::Glob => {}
3200 UseTreeKind::Simple(_, id1, id2) => {
3201 for (_, &id) in self.expect_full_def_from_use(base_id)
3203 .zip([id1, id2].iter())
3205 vec.push(hir::ItemId { id });
3211 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3212 let mut name = i.ident.name;
3213 let mut vis = self.lower_visibility(&i.vis, None);
3214 let attrs = self.lower_attrs(&i.attrs);
3215 if let ItemKind::MacroDef(ref def) = i.node {
3216 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3217 attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3218 let body = self.lower_token_stream(def.stream());
3219 self.exported_macros.push(hir::MacroDef {
3232 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3234 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3247 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3248 let node_id = self.lower_node_id(i.id).node_id;
3249 let def_id = self.resolver.definitions().local_def_id(node_id);
3253 attrs: self.lower_attrs(&i.attrs),
3254 node: match i.node {
3255 ForeignItemKind::Fn(ref fdec, ref generics) => {
3256 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3259 AnonymousLifetimeMode::PassThrough,
3262 // Disallow impl Trait in foreign items
3263 this.lower_fn_decl(fdec, None, false, None),
3264 this.lower_fn_args_to_names(fdec),
3269 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3271 ForeignItemKind::Static(ref t, m) => {
3272 hir::ForeignItemKind::Static(self.lower_ty(t, ImplTraitContext::Disallowed), m)
3274 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3275 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3277 vis: self.lower_visibility(&i.vis, None),
3282 fn lower_method_sig(
3284 generics: &Generics,
3287 impl_trait_return_allow: bool,
3288 is_async: Option<NodeId>,
3289 ) -> (hir::Generics, hir::MethodSig) {
3290 let header = self.lower_fn_header(sig.header);
3291 let (generics, decl) = self.add_in_band_defs(
3294 AnonymousLifetimeMode::PassThrough,
3295 |this, idty| this.lower_fn_decl(
3297 Some((fn_def_id, idty)),
3298 impl_trait_return_allow,
3302 (generics, hir::MethodSig { header, decl })
3305 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3307 IsAuto::Yes => hir::IsAuto::Yes,
3308 IsAuto::No => hir::IsAuto::No,
3312 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3314 unsafety: self.lower_unsafety(h.unsafety),
3315 asyncness: self.lower_asyncness(h.asyncness),
3316 constness: self.lower_constness(h.constness),
3321 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3323 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3324 Unsafety::Normal => hir::Unsafety::Normal,
3328 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3330 Constness::Const => hir::Constness::Const,
3331 Constness::NotConst => hir::Constness::NotConst,
3335 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3337 IsAsync::Async { .. } => hir::IsAsync::Async,
3338 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3342 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3344 UnOp::Deref => hir::UnDeref,
3345 UnOp::Not => hir::UnNot,
3346 UnOp::Neg => hir::UnNeg,
3350 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3352 node: match b.node {
3353 BinOpKind::Add => hir::BinOpKind::Add,
3354 BinOpKind::Sub => hir::BinOpKind::Sub,
3355 BinOpKind::Mul => hir::BinOpKind::Mul,
3356 BinOpKind::Div => hir::BinOpKind::Div,
3357 BinOpKind::Rem => hir::BinOpKind::Rem,
3358 BinOpKind::And => hir::BinOpKind::And,
3359 BinOpKind::Or => hir::BinOpKind::Or,
3360 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3361 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3362 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3363 BinOpKind::Shl => hir::BinOpKind::Shl,
3364 BinOpKind::Shr => hir::BinOpKind::Shr,
3365 BinOpKind::Eq => hir::BinOpKind::Eq,
3366 BinOpKind::Lt => hir::BinOpKind::Lt,
3367 BinOpKind::Le => hir::BinOpKind::Le,
3368 BinOpKind::Ne => hir::BinOpKind::Ne,
3369 BinOpKind::Ge => hir::BinOpKind::Ge,
3370 BinOpKind::Gt => hir::BinOpKind::Gt,
3376 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3377 let node = match p.node {
3378 PatKind::Wild => hir::PatKind::Wild,
3379 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3380 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3381 // `None` can occur in body-less function signatures
3382 def @ None | def @ Some(Def::Local(_)) => {
3383 let canonical_id = match def {
3384 Some(Def::Local(id)) => id,
3387 hir::PatKind::Binding(
3388 self.lower_binding_mode(binding_mode),
3391 sub.as_ref().map(|x| self.lower_pat(x)),
3394 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3399 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3404 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3405 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3406 let qpath = self.lower_qpath(
3410 ParamMode::Optional,
3411 ImplTraitContext::Disallowed,
3413 hir::PatKind::TupleStruct(
3415 pats.iter().map(|x| self.lower_pat(x)).collect(),
3419 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3423 ParamMode::Optional,
3424 ImplTraitContext::Disallowed,
3426 PatKind::Struct(ref path, ref fields, etc) => {
3427 let qpath = self.lower_qpath(
3431 ParamMode::Optional,
3432 ImplTraitContext::Disallowed,
3439 node: hir::FieldPat {
3440 id: self.next_id().node_id,
3441 ident: f.node.ident,
3442 pat: self.lower_pat(&f.node.pat),
3443 is_shorthand: f.node.is_shorthand,
3447 hir::PatKind::Struct(qpath, fs, etc)
3449 PatKind::Tuple(ref elts, ddpos) => {
3450 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3452 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3453 PatKind::Ref(ref inner, mutbl) => {
3454 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3456 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3457 P(self.lower_expr(e1)),
3458 P(self.lower_expr(e2)),
3459 self.lower_range_end(end),
3461 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3462 before.iter().map(|x| self.lower_pat(x)).collect(),
3463 slice.as_ref().map(|x| self.lower_pat(x)),
3464 after.iter().map(|x| self.lower_pat(x)).collect(),
3466 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3467 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3470 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3479 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3481 RangeEnd::Included(_) => hir::RangeEnd::Included,
3482 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3486 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3487 self.with_new_scopes(|this| {
3488 let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3492 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3497 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3498 let kind = match e.node {
3499 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3500 ExprKind::ObsoleteInPlace(..) => {
3501 self.sess.abort_if_errors();
3502 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3504 ExprKind::Array(ref exprs) => {
3505 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3507 ExprKind::Repeat(ref expr, ref count) => {
3508 let expr = P(self.lower_expr(expr));
3509 let count = self.lower_anon_const(count);
3510 hir::ExprKind::Repeat(expr, count)
3512 ExprKind::Tup(ref elts) => {
3513 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3515 ExprKind::Call(ref f, ref args) => {
3516 let f = P(self.lower_expr(f));
3517 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3519 ExprKind::MethodCall(ref seg, ref args) => {
3520 let hir_seg = self.lower_path_segment(
3523 ParamMode::Optional,
3525 ParenthesizedGenericArgs::Err,
3526 ImplTraitContext::Disallowed,
3528 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3529 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3531 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3532 let binop = self.lower_binop(binop);
3533 let lhs = P(self.lower_expr(lhs));
3534 let rhs = P(self.lower_expr(rhs));
3535 hir::ExprKind::Binary(binop, lhs, rhs)
3537 ExprKind::Unary(op, ref ohs) => {
3538 let op = self.lower_unop(op);
3539 let ohs = P(self.lower_expr(ohs));
3540 hir::ExprKind::Unary(op, ohs)
3542 ExprKind::Lit(ref l) => hir::ExprKind::Lit(P((**l).clone())),
3543 ExprKind::Cast(ref expr, ref ty) => {
3544 let expr = P(self.lower_expr(expr));
3545 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3547 ExprKind::Type(ref expr, ref ty) => {
3548 let expr = P(self.lower_expr(expr));
3549 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3551 ExprKind::AddrOf(m, ref ohs) => {
3552 let m = self.lower_mutability(m);
3553 let ohs = P(self.lower_expr(ohs));
3554 hir::ExprKind::AddrOf(m, ohs)
3556 // More complicated than you might expect because the else branch
3557 // might be `if let`.
3558 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3559 let else_opt = else_opt.as_ref().map(|els| {
3561 ExprKind::IfLet(..) => {
3562 // wrap the if-let expr in a block
3563 let span = els.span;
3564 let els = P(self.lower_expr(els));
3565 let LoweredNodeId { node_id, hir_id } = self.next_id();
3566 let blk = P(hir::Block {
3571 rules: hir::DefaultBlock,
3573 targeted_by_break: false,
3574 recovered: blk.recovered,
3576 P(self.expr_block(blk, ThinVec::new()))
3578 _ => P(self.lower_expr(els)),
3582 let then_blk = self.lower_block(blk, false);
3583 let then_expr = self.expr_block(then_blk, ThinVec::new());
3585 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3587 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3588 hir::ExprKind::While(
3589 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3590 this.lower_block(body, false),
3591 this.lower_label(opt_label),
3594 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3595 hir::ExprKind::Loop(
3596 this.lower_block(body, false),
3597 this.lower_label(opt_label),
3598 hir::LoopSource::Loop,
3601 ExprKind::Catch(ref body) => {
3602 self.with_catch_scope(body.id, |this| {
3604 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3605 let mut block = this.lower_block(body, true).into_inner();
3606 let tail = block.expr.take().map_or_else(
3608 let LoweredNodeId { node_id, hir_id } = this.next_id();
3609 let span = this.sess.codemap().end_point(unstable_span);
3613 node: hir::ExprKind::Tup(hir_vec![]),
3614 attrs: ThinVec::new(),
3618 |x: P<hir::Expr>| x.into_inner(),
3620 block.expr = Some(this.wrap_in_try_constructor(
3621 "from_ok", tail, unstable_span));
3622 hir::ExprKind::Block(P(block), None)
3625 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3626 P(self.lower_expr(expr)),
3627 arms.iter().map(|x| self.lower_arm(x)).collect(),
3628 hir::MatchSource::Normal,
3630 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3631 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3632 this.with_new_scopes(|this| {
3633 let block = this.lower_block(block, false);
3634 this.expr_block(block, ThinVec::new())
3639 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3641 if let IsAsync::Async { closure_id, .. } = asyncness {
3642 let outer_decl = FnDecl {
3643 inputs: decl.inputs.clone(),
3644 output: FunctionRetTy::Default(fn_decl_span),
3647 // We need to lower the declaration outside the new scope, because we
3648 // have to conserve the state of being inside a loop condition for the
3649 // closure argument types.
3650 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3652 self.with_new_scopes(|this| {
3653 // FIXME(cramertj) allow `async` non-`move` closures with
3654 if capture_clause == CaptureBy::Ref &&
3655 !decl.inputs.is_empty()
3661 "`async` non-`move` closures with arguments \
3662 are not currently supported",
3664 .help("consider using `let` statements to manually capture \
3665 variables by reference before entering an \
3666 `async move` closure")
3670 // Transform `async |x: u8| -> X { ... }` into
3671 // `|x: u8| future_from_generator(|| -> X { ... })`
3672 let body_id = this.lower_body(Some(&outer_decl), |this| {
3673 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3676 let async_body = this.make_async_expr(
3677 capture_clause, closure_id, async_ret_ty,
3679 this.with_new_scopes(|this| this.lower_expr(body))
3681 this.expr(fn_decl_span, async_body, ThinVec::new())
3683 hir::ExprKind::Closure(
3684 this.lower_capture_clause(capture_clause),
3692 // Lower outside new scope to preserve `is_in_loop_condition`.
3693 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3695 self.with_new_scopes(|this| {
3696 let mut is_generator = false;
3697 let body_id = this.lower_body(Some(decl), |this| {
3698 let e = this.lower_expr(body);
3699 is_generator = this.is_generator;
3702 let generator_option = if is_generator {
3703 if !decl.inputs.is_empty() {
3708 "generators cannot have explicit arguments"
3710 this.sess.abort_if_errors();
3712 Some(match movability {
3713 Movability::Movable => hir::GeneratorMovability::Movable,
3714 Movability::Static => hir::GeneratorMovability::Static,
3717 if movability == Movability::Static {
3722 "closures cannot be static"
3727 hir::ExprKind::Closure(
3728 this.lower_capture_clause(capture_clause),
3737 ExprKind::Block(ref blk, opt_label) => {
3738 hir::ExprKind::Block(self.lower_block(blk,
3739 opt_label.is_some()),
3740 self.lower_label(opt_label))
3742 ExprKind::Assign(ref el, ref er) => {
3743 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3745 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
3746 self.lower_binop(op),
3747 P(self.lower_expr(el)),
3748 P(self.lower_expr(er)),
3750 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
3751 ExprKind::Index(ref el, ref er) => {
3752 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
3754 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3755 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3756 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3757 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3758 let id = self.next_id();
3759 let e1 = self.lower_expr(e1);
3760 let e2 = self.lower_expr(e2);
3761 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], None, false));
3762 let ty = P(self.ty_path(id, span, hir::QPath::Resolved(None, ty_path)));
3763 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3764 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3765 let new = P(self.expr(span, hir::ExprKind::Path(new_path), ThinVec::new()));
3766 hir::ExprKind::Call(new, hir_vec![e1, e2])
3768 ExprKind::Range(ref e1, ref e2, lims) => {
3769 use syntax::ast::RangeLimits::*;
3771 let path = match (e1, e2, lims) {
3772 (&None, &None, HalfOpen) => "RangeFull",
3773 (&Some(..), &None, HalfOpen) => "RangeFrom",
3774 (&None, &Some(..), HalfOpen) => "RangeTo",
3775 (&Some(..), &Some(..), HalfOpen) => "Range",
3776 (&None, &Some(..), Closed) => "RangeToInclusive",
3777 (&Some(..), &Some(..), Closed) => unreachable!(),
3778 (_, &None, Closed) => self.diagnostic()
3779 .span_fatal(e.span, "inclusive range with no end")
3783 let fields = e1.iter()
3784 .map(|e| ("start", e))
3785 .chain(e2.iter().map(|e| ("end", e)))
3787 let expr = P(self.lower_expr(&e));
3789 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3790 let ident = Ident::new(Symbol::intern(s), unstable_span);
3791 self.field(ident, expr, unstable_span)
3793 .collect::<P<[hir::Field]>>();
3795 let is_unit = fields.is_empty();
3797 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3798 let struct_path = iter::once("ops")
3799 .chain(iter::once(path))
3800 .collect::<Vec<_>>();
3801 let struct_path = self.std_path(unstable_span, &struct_path, None, is_unit);
3802 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3804 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3810 hir::ExprKind::Path(struct_path)
3812 hir::ExprKind::Struct(struct_path, fields, None)
3814 span: unstable_span,
3815 attrs: e.attrs.clone(),
3818 ExprKind::Path(ref qself, ref path) => hir::ExprKind::Path(self.lower_qpath(
3822 ParamMode::Optional,
3823 ImplTraitContext::Disallowed,
3825 ExprKind::Break(opt_label, ref opt_expr) => {
3826 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3829 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3832 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3834 hir::ExprKind::Break(
3836 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3839 ExprKind::Continue(opt_label) => {
3840 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
3843 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3846 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3849 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
3850 ExprKind::InlineAsm(ref asm) => {
3851 let hir_asm = hir::InlineAsm {
3852 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3853 outputs: asm.outputs
3855 .map(|out| hir::InlineAsmOutput {
3856 constraint: out.constraint.clone(),
3858 is_indirect: out.is_indirect,
3861 asm: asm.asm.clone(),
3862 asm_str_style: asm.asm_str_style,
3863 clobbers: asm.clobbers.clone().into(),
3864 volatile: asm.volatile,
3865 alignstack: asm.alignstack,
3866 dialect: asm.dialect,
3869 let outputs = asm.outputs
3871 .map(|out| self.lower_expr(&out.expr))
3873 let inputs = asm.inputs
3875 .map(|&(_, ref input)| self.lower_expr(input))
3877 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
3879 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
3884 ParamMode::Optional,
3885 ImplTraitContext::Disallowed,
3887 fields.iter().map(|x| self.lower_field(x)).collect(),
3888 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3890 ExprKind::Paren(ref ex) => {
3891 let mut ex = self.lower_expr(ex);
3892 // include parens in span, but only if it is a super-span.
3893 if e.span.contains(ex.span) {
3896 // merge attributes into the inner expression.
3897 let mut attrs = e.attrs.clone();
3898 attrs.extend::<Vec<_>>(ex.attrs.into());
3903 ExprKind::Yield(ref opt_expr) => {
3904 self.is_generator = true;
3907 .map(|x| self.lower_expr(x))
3909 self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
3911 hir::ExprKind::Yield(P(expr))
3914 // Desugar ExprIfLet
3915 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3916 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3919 // match <sub_expr> {
3921 // _ => [<else_opt> | ()]
3924 let mut arms = vec![];
3926 // `<pat> => <body>`
3928 let body = self.lower_block(body, false);
3929 let body_expr = P(self.expr_block(body, ThinVec::new()));
3930 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3931 arms.push(self.arm(pats, body_expr));
3934 // _ => [<else_opt>|()]
3936 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3937 let wildcard_pattern = self.pat_wild(e.span);
3938 let body = if let Some(else_expr) = wildcard_arm {
3939 P(self.lower_expr(else_expr))
3941 self.expr_tuple(e.span, hir_vec![])
3943 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3946 let contains_else_clause = else_opt.is_some();
3948 let sub_expr = P(self.lower_expr(sub_expr));
3950 hir::ExprKind::Match(
3953 hir::MatchSource::IfLetDesugar {
3954 contains_else_clause,
3959 // Desugar ExprWhileLet
3960 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3961 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3964 // [opt_ident]: loop {
3965 // match <sub_expr> {
3971 // Note that the block AND the condition are evaluated in the loop scope.
3972 // This is done to allow `break` from inside the condition of the loop.
3973 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3975 this.lower_block(body, false),
3976 this.expr_break(e.span, ThinVec::new()),
3977 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3981 // `<pat> => <body>`
3983 let body_expr = P(self.expr_block(body, ThinVec::new()));
3984 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3985 self.arm(pats, body_expr)
3990 let pat_under = self.pat_wild(e.span);
3991 self.arm(hir_vec![pat_under], break_expr)
3994 // `match <sub_expr> { ... }`
3995 let arms = hir_vec![pat_arm, break_arm];
3996 let match_expr = self.expr(
3998 hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4002 // `[opt_ident]: loop { ... }`
4003 let loop_block = P(self.block_expr(P(match_expr)));
4004 let loop_expr = hir::ExprKind::Loop(
4006 self.lower_label(opt_label),
4007 hir::LoopSource::WhileLet,
4009 // add attributes to the outer returned expr node
4013 // Desugar ExprForLoop
4014 // From: `[opt_ident]: for <pat> in <head> <body>`
4015 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4019 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4021 // [opt_ident]: loop {
4023 // match ::std::iter::Iterator::next(&mut iter) {
4024 // ::std::option::Option::Some(val) => __next = val,
4025 // ::std::option::Option::None => break
4027 // let <pat> = __next;
4028 // StmtKind::Expr(<body>);
4036 let head = self.lower_expr(head);
4037 let head_sp = head.span;
4039 let iter = self.str_to_ident("iter");
4041 let next_ident = self.str_to_ident("__next");
4042 let next_sp = self.allow_internal_unstable(
4043 CompilerDesugaringKind::ForLoop,
4046 let next_pat = self.pat_ident_binding_mode(
4049 hir::BindingAnnotation::Mutable,
4052 // `::std::option::Option::Some(val) => next = val`
4054 let val_ident = self.str_to_ident("val");
4055 let val_pat = self.pat_ident(pat.span, val_ident);
4056 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4057 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4058 let assign = P(self.expr(
4060 hir::ExprKind::Assign(next_expr, val_expr),
4063 let some_pat = self.pat_some(pat.span, val_pat);
4064 self.arm(hir_vec![some_pat], assign)
4067 // `::std::option::Option::None => break`
4070 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4071 let pat = self.pat_none(e.span);
4072 self.arm(hir_vec![pat], break_expr)
4077 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
4079 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4081 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4082 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4083 let next_path = &["iter", "Iterator", "next"];
4084 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4085 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4086 let arms = hir_vec![pat_arm, break_arm];
4090 hir::ExprKind::Match(
4093 hir::MatchSource::ForLoopDesugar
4098 let match_stmt = respan(
4100 hir::StmtKind::Expr(match_expr, self.next_id().node_id)
4103 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4107 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
4109 // `let <pat> = __next`
4110 let pat = self.lower_pat(pat);
4111 let pat_let = self.stmt_let_pat(
4115 hir::LocalSource::ForLoopDesugar,
4118 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4119 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4120 let body_stmt = respan(
4122 hir::StmtKind::Expr(body_expr, self.next_id().node_id)
4125 let loop_block = P(self.block_all(
4127 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4131 // `[opt_ident]: loop { ... }`
4132 let loop_expr = hir::ExprKind::Loop(
4134 self.lower_label(opt_label),
4135 hir::LoopSource::ForLoop,
4137 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4138 let loop_expr = P(hir::Expr {
4143 attrs: ThinVec::new(),
4146 // `mut iter => { ... }`
4147 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4149 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4150 let into_iter_expr = {
4151 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4152 let into_iter = P(self.expr_std_path(
4153 head_sp, into_iter_path, None, ThinVec::new()));
4154 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4157 let match_expr = P(self.expr_match(
4161 hir::MatchSource::ForLoopDesugar,
4164 // `{ let _result = ...; _result }`
4165 // underscore prevents an unused_variables lint if the head diverges
4166 let result_ident = self.str_to_ident("_result");
4167 let (let_stmt, let_stmt_binding) =
4168 self.stmt_let(e.span, false, result_ident, match_expr);
4170 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4171 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4172 // add the attributes to the outer returned expr node
4173 return self.expr_block(block, e.attrs.clone());
4176 // Desugar ExprKind::Try
4178 ExprKind::Try(ref sub_expr) => {
4181 // match Try::into_result(<expr>) {
4182 // Ok(val) => #[allow(unreachable_code)] val,
4183 // Err(err) => #[allow(unreachable_code)]
4184 // // If there is an enclosing `catch {...}`
4185 // break 'catch_target Try::from_error(From::from(err)),
4187 // return Try::from_error(From::from(err)),
4191 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4193 // Try::into_result(<expr>)
4196 let sub_expr = self.lower_expr(sub_expr);
4198 let path = &["ops", "Try", "into_result"];
4199 let path = P(self.expr_std_path(
4200 unstable_span, path, None, ThinVec::new()));
4201 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4204 // #[allow(unreachable_code)]
4206 // allow(unreachable_code)
4208 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4209 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4210 let uc_nested = attr::mk_nested_word_item(uc_ident);
4211 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4213 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4215 let attrs = vec![attr];
4217 // Ok(val) => #[allow(unreachable_code)] val,
4219 let val_ident = self.str_to_ident("val");
4220 let val_pat = self.pat_ident(e.span, val_ident);
4221 let val_expr = P(self.expr_ident_with_attrs(
4225 ThinVec::from(attrs.clone()),
4227 let ok_pat = self.pat_ok(e.span, val_pat);
4229 self.arm(hir_vec![ok_pat], val_expr)
4232 // Err(err) => #[allow(unreachable_code)]
4233 // return Try::from_error(From::from(err)),
4235 let err_ident = self.str_to_ident("err");
4236 let err_local = self.pat_ident(e.span, err_ident);
4238 let path = &["convert", "From", "from"];
4239 let from = P(self.expr_std_path(
4240 e.span, path, None, ThinVec::new()));
4241 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4243 self.expr_call(e.span, from, hir_vec![err_expr])
4246 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4247 let thin_attrs = ThinVec::from(attrs);
4248 let catch_scope = self.catch_scopes.last().map(|x| *x);
4249 let ret_expr = if let Some(catch_node) = catch_scope {
4252 hir::ExprKind::Break(
4255 target_id: Ok(catch_node),
4257 Some(from_err_expr),
4262 P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4265 let err_pat = self.pat_err(e.span, err_local);
4266 self.arm(hir_vec![err_pat], ret_expr)
4269 hir::ExprKind::Match(
4271 hir_vec![err_arm, ok_arm],
4272 hir::MatchSource::TryDesugar,
4276 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4279 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4286 attrs: e.attrs.clone(),
4290 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
4291 SmallVector::one(match s.node {
4292 StmtKind::Local(ref l) => Spanned {
4293 node: hir::StmtKind::Decl(
4295 node: hir::DeclKind::Local(self.lower_local(l)),
4298 self.lower_node_id(s.id).node_id,
4302 StmtKind::Item(ref it) => {
4303 // Can only use the ID once.
4304 let mut id = Some(s.id);
4305 return self.lower_item_id(it)
4307 .map(|item_id| Spanned {
4308 node: hir::StmtKind::Decl(
4310 node: hir::DeclKind::Item(item_id),
4314 .map(|id| self.lower_node_id(id).node_id)
4315 .unwrap_or_else(|| self.next_id().node_id),
4321 StmtKind::Expr(ref e) => Spanned {
4322 node: hir::StmtKind::Expr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4325 StmtKind::Semi(ref e) => Spanned {
4326 node: hir::StmtKind::Semi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4329 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4333 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4335 CaptureBy::Value => hir::CaptureByValue,
4336 CaptureBy::Ref => hir::CaptureByRef,
4340 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4341 /// the address space of that item instead of the item currently being
4342 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4343 /// lower a `Visibility` value although we haven't lowered the owning
4344 /// `ImplItem` in question yet.
4345 fn lower_visibility(
4348 explicit_owner: Option<NodeId>,
4349 ) -> hir::Visibility {
4350 let node = match v.node {
4351 VisibilityKind::Public => hir::VisibilityKind::Public,
4352 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4353 VisibilityKind::Restricted { ref path, id } => hir::VisibilityKind::Restricted {
4354 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4355 id: if let Some(owner) = explicit_owner {
4356 self.lower_node_id_with_owner(id, owner).node_id
4358 self.lower_node_id(id).node_id
4361 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4363 respan(v.span, node)
4366 fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4368 Defaultness::Default => hir::Defaultness::Default {
4369 has_value: has_value,
4371 Defaultness::Final => {
4373 hir::Defaultness::Final
4378 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4380 BlockCheckMode::Default => hir::DefaultBlock,
4381 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4385 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4387 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4388 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4389 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4390 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4394 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4396 CompilerGenerated => hir::CompilerGenerated,
4397 UserProvided => hir::UserProvided,
4401 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4403 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4404 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4408 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4410 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4411 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4415 // Helper methods for building HIR.
4417 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4426 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4428 id: self.next_id().node_id,
4432 is_shorthand: false,
4436 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4437 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4438 P(self.expr(span, expr_break, attrs))
4445 args: hir::HirVec<hir::Expr>,
4447 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4450 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4451 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4454 fn expr_ident_with_attrs(
4459 attrs: ThinVec<Attribute>,
4461 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4465 def: Def::Local(binding),
4466 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4470 self.expr(span, expr_path, attrs)
4473 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4474 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4480 components: &[&str],
4481 params: Option<P<hir::GenericArgs>>,
4482 attrs: ThinVec<Attribute>,
4484 let path = self.std_path(span, components, params, true);
4487 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4496 arms: hir::HirVec<hir::Arm>,
4497 source: hir::MatchSource,
4499 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4502 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4503 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4506 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4507 P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4510 fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4511 let LoweredNodeId { node_id, hir_id } = self.next_id();
4524 ex: Option<P<hir::Expr>>,
4526 source: hir::LocalSource,
4528 let LoweredNodeId { node_id, hir_id } = self.next_id();
4530 let local = P(hir::Local {
4537 attrs: ThinVec::new(),
4540 let decl = respan(sp, hir::DeclKind::Local(local));
4541 respan(sp, hir::StmtKind::Decl(P(decl), self.next_id().node_id))
4550 ) -> (hir::Stmt, NodeId) {
4551 let pat = if mutbl {
4552 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4554 self.pat_ident(sp, ident)
4556 let pat_id = pat.id;
4558 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4563 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4564 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4570 stmts: hir::HirVec<hir::Stmt>,
4571 expr: Option<P<hir::Expr>>,
4573 let LoweredNodeId { node_id, hir_id } = self.next_id();
4580 rules: hir::DefaultBlock,
4582 targeted_by_break: false,
4587 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4588 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4591 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4592 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4595 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4596 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4599 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4600 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4606 components: &[&str],
4607 subpats: hir::HirVec<P<hir::Pat>>,
4609 let path = self.std_path(span, components, None, true);
4610 let qpath = hir::QPath::Resolved(None, P(path));
4611 let pt = if subpats.is_empty() {
4612 hir::PatKind::Path(qpath)
4614 hir::PatKind::TupleStruct(qpath, subpats, None)
4619 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4620 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4623 fn pat_ident_binding_mode(
4627 bm: hir::BindingAnnotation,
4629 let LoweredNodeId { node_id, hir_id } = self.next_id();
4634 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4639 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4640 self.pat(span, hir::PatKind::Wild)
4643 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4644 let LoweredNodeId { node_id, hir_id } = self.next_id();
4653 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4654 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4655 /// The path is also resolved according to `is_value`.
4659 components: &[&str],
4660 params: Option<P<hir::GenericArgs>>,
4664 .resolve_str_path(span, self.crate_root, components, params, is_value)
4667 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4669 let node = match qpath {
4670 hir::QPath::Resolved(None, path) => {
4671 // Turn trait object paths into `TyKind::TraitObject` instead.
4672 if let Def::Trait(_) = path.def {
4673 let principal = hir::PolyTraitRef {
4674 bound_generic_params: hir::HirVec::new(),
4675 trait_ref: hir::TraitRef {
4676 path: path.and_then(|path| path),
4682 // The original ID is taken by the `PolyTraitRef`,
4683 // so the `Ty` itself needs a different one.
4684 id = self.next_id();
4685 hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4687 hir::TyKind::Path(hir::QPath::Resolved(None, path))
4690 _ => hir::TyKind::Path(qpath),
4700 /// Invoked to create the lifetime argument for a type `&T`
4701 /// with no explicit lifetime.
4702 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4703 match self.anonymous_lifetime_mode {
4704 // Intercept when we are in an impl header and introduce an in-band lifetime.
4705 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4707 AnonymousLifetimeMode::CreateParameter => {
4708 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4710 id: self.next_id().node_id,
4712 name: hir::LifetimeName::Param(fresh_name),
4716 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4720 /// Invoked to create the lifetime argument(s) for a path like
4721 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4722 /// sorts of cases are deprecated. This may therefore report a warning or an
4723 /// error, depending on the mode.
4724 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4725 match self.anonymous_lifetime_mode {
4726 // NB. We intentionally ignore the create-parameter mode here
4727 // and instead "pass through" to resolve-lifetimes, which will then
4728 // report an error. This is because we don't want to support
4729 // impl elision for deprecated forms like
4731 // impl Foo for std::cell::Ref<u32> // note lack of '_
4732 AnonymousLifetimeMode::CreateParameter => {}
4734 // This is the normal case.
4735 AnonymousLifetimeMode::PassThrough => {}
4739 .map(|_| self.new_implicit_lifetime(span))
4743 /// Invoked to create the lifetime argument(s) for an elided trait object
4744 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4745 /// when the bound is written, even if it is written with `'_` like in
4746 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4747 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4748 match self.anonymous_lifetime_mode {
4749 // NB. We intentionally ignore the create-parameter mode here.
4750 // and instead "pass through" to resolve-lifetimes, which will apply
4751 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4752 // do not act like other elided lifetimes. In other words, given this:
4754 // impl Foo for Box<dyn Debug>
4756 // we do not introduce a fresh `'_` to serve as the bound, but instead
4757 // ultimately translate to the equivalent of:
4759 // impl Foo for Box<dyn Debug + 'static>
4761 // `resolve_lifetime` has the code to make that happen.
4762 AnonymousLifetimeMode::CreateParameter => {}
4764 // This is the normal case.
4765 AnonymousLifetimeMode::PassThrough => {}
4768 self.new_implicit_lifetime(span)
4771 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4773 id: self.next_id().node_id,
4775 name: hir::LifetimeName::Implicit,
4779 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4780 self.sess.buffer_lint_with_diagnostic(
4781 builtin::BARE_TRAIT_OBJECTS,
4784 "trait objects without an explicit `dyn` are deprecated",
4785 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4789 fn wrap_in_try_constructor(
4791 method: &'static str,
4793 unstable_span: Span,
4795 let path = &["ops", "Try", method];
4796 let from_err = P(self.expr_std_path(unstable_span, path, None,
4798 P(self.expr_call(e.span, from_err, hir_vec![e]))
4802 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4803 // Sorting by span ensures that we get things in order within a
4804 // file, and also puts the files in a sensible order.
4805 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4806 body_ids.sort_by_key(|b| bodies[b].value.span);