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 use middle::cstore::CrateStore;
52 use rustc_data_structures::indexed_vec::IndexVec;
54 use util::common::FN_OUTPUT_NAME;
55 use util::nodemap::{DefIdMap, NodeMap};
57 use std::collections::{BTreeMap, HashSet};
65 use syntax::ext::hygiene::{Mark, SyntaxContext};
66 use syntax::print::pprust;
68 use syntax::codemap::{self, respan, CompilerDesugaringKind, Spanned};
69 use syntax::std_inject;
70 use syntax::symbol::{keywords, Symbol};
71 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
72 use syntax::parse::token::Token;
73 use syntax::util::small_vector::SmallVector;
74 use syntax::visit::{self, Visitor};
77 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
79 pub struct LoweringContext<'a> {
80 crate_root: Option<&'static str>,
82 // Use to assign ids to hir nodes that do not directly correspond to an ast node
85 cstore: &'a dyn CrateStore,
87 resolver: &'a mut dyn Resolver,
89 /// The items being lowered are collected here.
90 items: BTreeMap<NodeId, hir::Item>,
92 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
93 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
94 bodies: BTreeMap<hir::BodyId, hir::Body>,
95 exported_macros: Vec<hir::MacroDef>,
97 trait_impls: BTreeMap<DefId, Vec<NodeId>>,
98 trait_auto_impl: BTreeMap<DefId, NodeId>,
102 catch_scopes: Vec<NodeId>,
103 loop_scopes: Vec<NodeId>,
104 is_in_loop_condition: bool,
105 is_in_trait_impl: bool,
106 is_in_anon_const: 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 is_in_anon_const: false,
235 lifetimes_to_define: Vec::new(),
236 is_collecting_in_band_lifetimes: false,
237 in_scope_lifetimes: Vec::new(),
241 #[derive(Copy, Clone, PartialEq)]
243 /// Any path in a type context.
245 /// The `module::Type` in `module::Type::method` in an expression.
250 struct LoweredNodeId {
255 enum ParenthesizedGenericArgs {
261 /// What to do when we encounter an **anonymous** lifetime
262 /// reference. Anonymous lifetime references come in two flavors. You
263 /// have implicit, or fully elided, references to lifetimes, like the
264 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
265 /// or `Ref<'_, T>`. These often behave the same, but not always:
267 /// - certain usages of implicit references are deprecated, like
268 /// `Ref<T>`, and we sometimes just give hard errors in those cases
270 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
271 /// the same as `Box<dyn Foo + '_>`.
273 /// We describe the effects of the various modes in terms of three cases:
275 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
276 /// of a `&` (e.g., the missing lifetime in something like `&T`)
277 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
278 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
279 /// elided bounds follow special rules. Note that this only covers
280 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
281 /// '_>` is a case of "modern" elision.
282 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
283 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
284 /// non-deprecated equivalent.
286 /// Currently, the handling of lifetime elision is somewhat spread out
287 /// between HIR lowering and -- as described below -- the
288 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
289 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
290 /// everything into HIR lowering.
291 #[derive(Copy, Clone)]
292 enum AnonymousLifetimeMode {
293 /// For **Modern** cases, create a new anonymous region parameter
294 /// and reference that.
296 /// For **Dyn Bound** cases, pass responsibility to
297 /// `resolve_lifetime` code.
299 /// For **Deprecated** cases, report an error.
302 /// Pass responsibility to `resolve_lifetime` code for all cases.
306 impl<'a> LoweringContext<'a> {
307 fn lower_crate(mut self, c: &Crate) -> hir::Crate {
308 /// Full-crate AST visitor that inserts into a fresh
309 /// `LoweringContext` any information that may be
310 /// needed from arbitrary locations in the crate.
311 /// E.g. The number of lifetime generic parameters
312 /// declared for every type and trait definition.
313 struct MiscCollector<'lcx, 'interner: 'lcx> {
314 lctx: &'lcx mut LoweringContext<'interner>,
317 impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
318 fn visit_item(&mut self, item: &'lcx Item) {
319 self.lctx.allocate_hir_id_counter(item.id, item);
322 ItemKind::Struct(_, ref generics)
323 | ItemKind::Union(_, ref generics)
324 | ItemKind::Enum(_, ref generics)
325 | ItemKind::Ty(_, 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::Item_::ItemImpl(_, _, _, ref generics, ..)
388 | hir::Item_::ItemTrait(_, _, 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: &Vec<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::ExprClosure(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::ExprCall(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 = if self.is_in_anon_const {
974 Err(hir::LoopIdError::OutsideLoopScope)
978 if let Def::Label(loop_id) = self.expect_full_def(id) {
979 Ok(self.lower_node_id(loop_id).node_id)
981 Err(hir::LoopIdError::UnresolvedLabel)
987 .map(|innermost_loop_id| *innermost_loop_id)
988 .map(|id| Ok(self.lower_node_id(id).node_id))
989 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
995 label: self.lower_label(destination.map(|(_, label)| label)),
1000 fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1003 .map(|a| self.lower_attr(a))
1004 .collect::<Vec<_>>()
1008 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1012 path: attr.path.clone(),
1013 tokens: self.lower_token_stream(attr.tokens.clone()),
1014 is_sugared_doc: attr.is_sugared_doc,
1019 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1022 .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1026 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1028 TokenTree::Token(span, token) => self.lower_token(token, span),
1029 TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1032 delim: delimited.delim,
1033 tts: self.lower_token_stream(delimited.tts.into()).into(),
1039 fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1041 Token::Interpolated(_) => {}
1042 other => return TokenTree::Token(span, other).into(),
1045 let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1046 self.lower_token_stream(tts)
1049 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1051 attrs: self.lower_attrs(&arm.attrs),
1052 pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1053 guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
1054 body: P(self.lower_expr(&arm.body)),
1058 fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
1060 id: self.lower_node_id(b.id).node_id,
1062 ty: self.lower_ty(&b.ty, itctx),
1067 fn lower_generic_arg(&mut self,
1068 arg: &ast::GenericArg,
1069 itctx: ImplTraitContext)
1070 -> hir::GenericArg {
1072 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1073 ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1077 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
1078 P(self.lower_ty_direct(t, itctx))
1081 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext) -> hir::Ty {
1082 let kind = match t.node {
1083 TyKind::Infer => hir::TyInfer,
1084 TyKind::Err => hir::TyErr,
1085 TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty, itctx)),
1086 TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt, itctx)),
1087 TyKind::Rptr(ref region, ref mt) => {
1088 let span = t.span.shrink_to_lo();
1089 let lifetime = match *region {
1090 Some(ref lt) => self.lower_lifetime(lt),
1091 None => self.elided_ref_lifetime(span),
1093 hir::TyRptr(lifetime, self.lower_mt(mt, itctx))
1095 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1098 this.with_anonymous_lifetime_mode(
1099 AnonymousLifetimeMode::PassThrough,
1101 hir::TyBareFn(P(hir::BareFnTy {
1102 generic_params: this.lower_generic_params(
1105 ImplTraitContext::Disallowed,
1107 unsafety: this.lower_unsafety(f.unsafety),
1109 decl: this.lower_fn_decl(&f.decl, None, false, None),
1110 arg_names: this.lower_fn_args_to_names(&f.decl),
1116 TyKind::Never => hir::TyNever,
1117 TyKind::Tup(ref tys) => {
1118 hir::TyTup(tys.iter().map(|ty| {
1119 self.lower_ty_direct(ty, itctx.reborrow())
1122 TyKind::Paren(ref ty) => {
1123 return self.lower_ty_direct(ty, itctx);
1125 TyKind::Path(ref qself, ref path) => {
1126 let id = self.lower_node_id(t.id);
1127 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1128 let ty = self.ty_path(id, t.span, qpath);
1129 if let hir::TyTraitObject(..) = ty.node {
1130 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1134 TyKind::ImplicitSelf => hir::TyPath(hir::QPath::Resolved(
1137 def: self.expect_full_def(t.id),
1138 segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1142 TyKind::Array(ref ty, ref length) => {
1143 hir::TyArray(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1145 TyKind::Typeof(ref expr) => {
1146 hir::TyTypeof(self.lower_anon_const(expr))
1148 TyKind::TraitObject(ref bounds, kind) => {
1149 let mut lifetime_bound = None;
1152 .filter_map(|bound| match *bound {
1153 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1154 Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1156 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1157 GenericBound::Outlives(ref lifetime) => {
1158 if lifetime_bound.is_none() {
1159 lifetime_bound = Some(self.lower_lifetime(lifetime));
1165 let lifetime_bound =
1166 lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1167 if kind != TraitObjectSyntax::Dyn {
1168 self.maybe_lint_bare_trait(t.span, t.id, false);
1170 hir::TyTraitObject(bounds, lifetime_bound)
1172 TyKind::ImplTrait(def_node_id, ref bounds) => {
1175 ImplTraitContext::Existential(fn_def_id) => {
1176 self.lower_existential_impl_trait(
1177 span, fn_def_id, def_node_id,
1178 |this| this.lower_param_bounds(bounds, itctx),
1181 ImplTraitContext::Universal(in_band_ty_params) => {
1182 self.lower_node_id(def_node_id);
1183 // Add a definition for the in-band TyParam
1184 let def_index = self
1187 .opt_def_index(def_node_id)
1190 let hir_bounds = self.lower_param_bounds(
1192 ImplTraitContext::Universal(in_band_ty_params),
1194 // Set the name to `impl Bound1 + Bound2`
1195 let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1196 in_band_ty_params.push(hir::GenericParam {
1198 name: ParamName::Plain(ident),
1199 pure_wrt_drop: false,
1203 kind: hir::GenericParamKind::Type {
1205 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1209 hir::TyPath(hir::QPath::Resolved(
1213 def: Def::TyParam(DefId::local(def_index)),
1214 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1218 ImplTraitContext::Disallowed => {
1223 "`impl Trait` not allowed outside of function \
1224 and inherent method return types"
1230 TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1233 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1242 fn lower_existential_impl_trait(
1246 exist_ty_node_id: NodeId,
1247 lower_bounds: impl FnOnce(&mut LoweringContext) -> hir::GenericBounds,
1249 // Make sure we know that some funky desugaring has been going on here.
1250 // This is a first: there is code in other places like for loop
1251 // desugaring that explicitly states that we don't want to track that.
1252 // Not tracking it makes lints in rustc and clippy very fragile as
1253 // frequently opened issues show.
1254 let exist_ty_span = self.allow_internal_unstable(
1255 CompilerDesugaringKind::ExistentialReturnType,
1259 let exist_ty_def_index = self
1262 .opt_def_index(exist_ty_node_id)
1266 self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1268 let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1270 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1276 self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1277 let exist_ty_item_kind = hir::ItemExistential(hir::ExistTy {
1278 generics: hir::Generics {
1279 params: lifetime_defs,
1280 where_clause: hir::WhereClause {
1281 id: lctx.next_id().node_id,
1282 predicates: Vec::new().into(),
1287 impl_trait_fn: Some(fn_def_id),
1289 let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1290 // Generate an `existential type Foo: Trait;` declaration
1291 trace!("creating existential type with id {:#?}", exist_ty_id);
1293 trace!("exist ty def index: {:#?}", exist_ty_def_index);
1294 let exist_ty_item = hir::Item {
1295 id: exist_ty_id.node_id,
1296 hir_id: exist_ty_id.hir_id,
1297 name: keywords::Invalid.name(),
1298 attrs: Default::default(),
1299 node: exist_ty_item_kind,
1300 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1301 span: exist_ty_span,
1304 // Insert the item into the global list. This usually happens
1305 // automatically for all AST items. But this existential type item
1306 // does not actually exist in the AST.
1307 lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1309 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1310 let path = P(hir::Path {
1311 span: exist_ty_span,
1312 def: Def::Existential(DefId::local(exist_ty_def_index)),
1313 segments: hir_vec![hir::PathSegment {
1315 ident: Ident::new(keywords::Invalid.name(), exist_ty_span),
1316 args: Some(P(hir::GenericArgs {
1317 parenthesized: false,
1318 bindings: HirVec::new(),
1323 hir::TyPath(hir::QPath::Resolved(None, path))
1327 fn lifetimes_from_impl_trait_bounds(
1329 exist_ty_id: NodeId,
1330 parent_index: DefIndex,
1331 bounds: &hir::GenericBounds,
1332 ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1333 // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1334 // appear in the bounds, excluding lifetimes that are created within the bounds.
1335 // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1336 struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1337 context: &'r mut LoweringContext<'a>,
1339 exist_ty_id: NodeId,
1340 collect_elided_lifetimes: bool,
1341 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1342 already_defined_lifetimes: HashSet<hir::LifetimeName>,
1343 output_lifetimes: Vec<hir::GenericArg>,
1344 output_lifetime_params: Vec<hir::GenericParam>,
1347 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1348 fn nested_visit_map<'this>(
1350 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1351 hir::intravisit::NestedVisitorMap::None
1354 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1355 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1356 if parameters.parenthesized {
1357 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1358 self.collect_elided_lifetimes = false;
1359 hir::intravisit::walk_generic_args(self, span, parameters);
1360 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1362 hir::intravisit::walk_generic_args(self, span, parameters);
1366 fn visit_ty(&mut self, t: &'v hir::Ty) {
1367 // Don't collect elided lifetimes used inside of `fn()` syntax
1368 if let hir::Ty_::TyBareFn(_) = t.node {
1369 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1370 self.collect_elided_lifetimes = false;
1372 // Record the "stack height" of `for<'a>` lifetime bindings
1373 // to be able to later fully undo their introduction.
1374 let old_len = self.currently_bound_lifetimes.len();
1375 hir::intravisit::walk_ty(self, t);
1376 self.currently_bound_lifetimes.truncate(old_len);
1378 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1380 hir::intravisit::walk_ty(self, t)
1384 fn visit_poly_trait_ref(
1386 trait_ref: &'v hir::PolyTraitRef,
1387 modifier: hir::TraitBoundModifier,
1389 // Record the "stack height" of `for<'a>` lifetime bindings
1390 // to be able to later fully undo their introduction.
1391 let old_len = self.currently_bound_lifetimes.len();
1392 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1393 self.currently_bound_lifetimes.truncate(old_len);
1396 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1397 // Record the introduction of 'a in `for<'a> ...`
1398 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1399 // Introduce lifetimes one at a time so that we can handle
1400 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1401 let lt_name = hir::LifetimeName::Param(param.name);
1402 self.currently_bound_lifetimes.push(lt_name);
1405 hir::intravisit::walk_generic_param(self, param);
1408 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1409 let name = match lifetime.name {
1410 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1411 if self.collect_elided_lifetimes {
1412 // Use `'_` for both implicit and underscore lifetimes in
1413 // `abstract type Foo<'_>: SomeTrait<'_>;`
1414 hir::LifetimeName::Underscore
1419 hir::LifetimeName::Param(_) => lifetime.name,
1420 hir::LifetimeName::Static => return,
1423 if !self.currently_bound_lifetimes.contains(&name)
1424 && !self.already_defined_lifetimes.contains(&name) {
1425 self.already_defined_lifetimes.insert(name);
1427 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1428 id: self.context.next_id().node_id,
1429 span: lifetime.span,
1433 // We need to manually create the ids here, because the
1434 // definitions will go into the explicit `existential type`
1435 // declaration and thus need to have their owner set to that item
1436 let def_node_id = self.context.sess.next_node_id();
1437 let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1438 self.context.resolver.definitions().create_def_with_parent(
1441 DefPathData::LifetimeParam(name.ident().as_interned_str()),
1442 DefIndexAddressSpace::High,
1447 let name = match name {
1448 hir::LifetimeName::Underscore => {
1449 hir::ParamName::Plain(keywords::UnderscoreLifetime.ident())
1451 hir::LifetimeName::Param(param_name) => param_name,
1452 _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1455 self.output_lifetime_params.push(hir::GenericParam {
1458 span: lifetime.span,
1459 pure_wrt_drop: false,
1462 kind: hir::GenericParamKind::Lifetime {
1470 let mut lifetime_collector = ImplTraitLifetimeCollector {
1472 parent: parent_index,
1474 collect_elided_lifetimes: true,
1475 currently_bound_lifetimes: Vec::new(),
1476 already_defined_lifetimes: HashSet::new(),
1477 output_lifetimes: Vec::new(),
1478 output_lifetime_params: Vec::new(),
1481 for bound in bounds {
1482 hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1486 lifetime_collector.output_lifetimes.into(),
1487 lifetime_collector.output_lifetime_params.into(),
1491 fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1496 .map(|x| self.lower_foreign_item(x))
1501 fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1508 fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1510 node: hir::Variant_ {
1511 name: v.node.ident.name,
1512 attrs: self.lower_attrs(&v.node.attrs),
1513 data: self.lower_variant_data(&v.node.data),
1514 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1523 qself: &Option<QSelf>,
1525 param_mode: ParamMode,
1526 mut itctx: ImplTraitContext,
1528 let qself_position = qself.as_ref().map(|q| q.position);
1529 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1531 let resolution = self.resolver
1533 .unwrap_or(PathResolution::new(Def::Err));
1535 let proj_start = p.segments.len() - resolution.unresolved_segments();
1536 let path = P(hir::Path {
1537 def: resolution.base_def(),
1538 segments: p.segments[..proj_start]
1541 .map(|(i, segment)| {
1542 let param_mode = match (qself_position, param_mode) {
1543 (Some(j), ParamMode::Optional) if i < j => {
1544 // This segment is part of the trait path in a
1545 // qualified path - one of `a`, `b` or `Trait`
1546 // in `<X as a::b::Trait>::T::U::method`.
1552 // Figure out if this is a type/trait segment,
1553 // which may need lifetime elision performed.
1554 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1555 krate: def_id.krate,
1556 index: this.def_key(def_id).parent.expect("missing parent"),
1558 let type_def_id = match resolution.base_def() {
1559 Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1560 Some(parent_def_id(self, def_id))
1562 Def::Variant(def_id) if i + 1 == proj_start => {
1563 Some(parent_def_id(self, def_id))
1566 | Def::Union(def_id)
1568 | Def::TyAlias(def_id)
1569 | Def::Trait(def_id) if i + 1 == proj_start =>
1575 let parenthesized_generic_args = match resolution.base_def() {
1576 // `a::b::Trait(Args)`
1577 Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1578 // `a::b::Trait(Args)::TraitItem`
1579 Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1580 if i + 2 == proj_start =>
1582 ParenthesizedGenericArgs::Ok
1584 // Avoid duplicated errors
1585 Def::Err => ParenthesizedGenericArgs::Ok,
1591 | Def::Variant(..) if i + 1 == proj_start =>
1593 ParenthesizedGenericArgs::Err
1595 // A warning for now, for compatibility reasons
1596 _ => ParenthesizedGenericArgs::Warn,
1599 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1600 if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1603 assert!(!def_id.is_local());
1605 self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1606 let n = item_generics.own_counts().lifetimes;
1607 self.type_def_lifetime_params.insert(def_id, n);
1610 self.lower_path_segment(
1615 parenthesized_generic_args,
1623 // Simple case, either no projections, or only fully-qualified.
1624 // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1625 if resolution.unresolved_segments() == 0 {
1626 return hir::QPath::Resolved(qself, path);
1629 // Create the innermost type that we're projecting from.
1630 let mut ty = if path.segments.is_empty() {
1631 // If the base path is empty that means there exists a
1632 // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1633 qself.expect("missing QSelf for <T>::...")
1635 // Otherwise, the base path is an implicit `Self` type path,
1636 // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1637 // `<I as Iterator>::Item::default`.
1638 let new_id = self.next_id();
1639 P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1642 // Anything after the base path are associated "extensions",
1643 // out of which all but the last one are associated types,
1644 // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1645 // * base path is `std::vec::Vec<T>`
1646 // * "extensions" are `IntoIter`, `Item` and `clone`
1647 // * type nodes are:
1648 // 1. `std::vec::Vec<T>` (created above)
1649 // 2. `<std::vec::Vec<T>>::IntoIter`
1650 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1651 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1652 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1653 let segment = P(self.lower_path_segment(
1658 ParenthesizedGenericArgs::Warn,
1661 let qpath = hir::QPath::TypeRelative(ty, segment);
1663 // It's finished, return the extension of the right node type.
1664 if i == p.segments.len() - 1 {
1668 // Wrap the associated extension in another type node.
1669 let new_id = self.next_id();
1670 ty = P(self.ty_path(new_id, p.span, qpath));
1673 // Should've returned in the for loop above.
1676 "lower_qpath: no final extension segment in {}..{}",
1682 fn lower_path_extra(
1686 ident: Option<Ident>,
1687 param_mode: ParamMode,
1691 segments: p.segments
1694 self.lower_path_segment(
1699 ParenthesizedGenericArgs::Err,
1700 ImplTraitContext::Disallowed,
1703 .chain(ident.map(|ident| hir::PathSegment::from_ident(ident)))
1709 fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1710 let def = self.expect_full_def(id);
1711 self.lower_path_extra(def, p, None, param_mode)
1714 fn lower_path_segment(
1717 segment: &PathSegment,
1718 param_mode: ParamMode,
1719 expected_lifetimes: usize,
1720 parenthesized_generic_args: ParenthesizedGenericArgs,
1721 itctx: ImplTraitContext,
1722 ) -> hir::PathSegment {
1723 let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1724 let msg = "parenthesized parameters may only be used with a trait";
1725 match **generic_args {
1726 GenericArgs::AngleBracketed(ref data) => {
1727 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1729 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1730 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1731 ParenthesizedGenericArgs::Warn => {
1732 self.sess.buffer_lint(
1733 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1738 (hir::GenericArgs::none(), true)
1740 ParenthesizedGenericArgs::Err => {
1741 struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1742 .span_label(data.span, "only traits may use parentheses")
1744 (hir::GenericArgs::none(), true)
1749 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1752 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1753 GenericArg::Lifetime(_) => true,
1756 if !generic_args.parenthesized && !has_lifetimes {
1758 self.elided_path_lifetimes(path_span, expected_lifetimes)
1760 .map(|lt| GenericArg::Lifetime(lt))
1761 .chain(generic_args.args.into_iter())
1765 hir::PathSegment::new(
1772 fn lower_angle_bracketed_parameter_data(
1774 data: &AngleBracketedArgs,
1775 param_mode: ParamMode,
1776 mut itctx: ImplTraitContext,
1777 ) -> (hir::GenericArgs, bool) {
1778 let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1779 let has_types = args.iter().any(|arg| match arg {
1780 ast::GenericArg::Type(_) => true,
1784 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1785 bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1786 parenthesized: false,
1788 !has_types && param_mode == ParamMode::Optional)
1791 fn lower_parenthesized_parameter_data(
1793 data: &ParenthesisedArgs,
1794 ) -> (hir::GenericArgs, bool) {
1795 // Switch to `PassThrough` mode for anonymous lifetimes: this
1796 // means that we permit things like `&Ref<T>`, where `Ref` has
1797 // a hidden lifetime parameter. This is needed for backwards
1798 // compatibility, even in contexts like an impl header where
1799 // we generally don't permit such things (see #51008).
1800 self.with_anonymous_lifetime_mode(
1801 AnonymousLifetimeMode::PassThrough,
1803 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1804 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1805 let inputs = inputs.iter().map(|ty| this.lower_ty_direct(ty, DISALLOWED)).collect();
1806 let mk_tup = |this: &mut Self, tys, span| {
1807 let LoweredNodeId { node_id, hir_id } = this.next_id();
1808 hir::Ty { node: hir::TyTup(tys), id: node_id, hir_id, span }
1813 args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1816 id: this.next_id().node_id,
1817 ident: Ident::from_str(FN_OUTPUT_NAME),
1820 .map(|ty| this.lower_ty(&ty, DISALLOWED))
1821 .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1822 span: output.as_ref().map_or(span, |ty| ty.span),
1825 parenthesized: true,
1833 fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1834 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1840 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1841 pat: self.lower_pat(&l.pat),
1842 init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1844 attrs: l.attrs.clone(),
1845 source: hir::LocalSource::Normal,
1849 fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1851 Mutability::Mutable => hir::MutMutable,
1852 Mutability::Immutable => hir::MutImmutable,
1856 fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1857 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1861 pat: self.lower_pat(&arg.pat),
1865 fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1868 .map(|arg| match arg.pat.node {
1869 PatKind::Ident(_, ident, _) => ident,
1870 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
1875 // Lowers a function declaration.
1877 // decl: the unlowered (ast) function declaration.
1878 // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1879 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1880 // make_ret_async is also `Some`.
1881 // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1882 // This guards against trait declarations and implementations where impl Trait is
1884 // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1885 // return type. This is used for `async fn` declarations. The `NodeId` is the id of the
1886 // return type impl Trait item.
1890 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
1891 impl_trait_return_allow: bool,
1892 make_ret_async: Option<NodeId>,
1893 ) -> P<hir::FnDecl> {
1894 let inputs = decl.inputs
1897 if let Some((_, ref mut ibty)) = in_band_ty_params {
1898 self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
1900 self.lower_ty_direct(&arg.ty, ImplTraitContext::Disallowed)
1903 .collect::<HirVec<_>>();
1905 let output = if let Some(ret_id) = make_ret_async {
1906 self.lower_async_fn_ret_ty(
1909 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
1914 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
1915 Some((def_id, _)) if impl_trait_return_allow => {
1916 hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1918 _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1920 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1927 variadic: decl.variadic,
1928 has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1929 TyKind::ImplicitSelf => true,
1930 TyKind::Rptr(_, ref mt) => mt.ty.node.is_implicit_self(),
1936 // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
1938 // fn_span: the span of the async function declaration. Used for error reporting.
1939 // inputs: lowered types of arguments to the function. Used to collect lifetimes.
1940 // output: unlowered output type (`T` in `-> T`)
1941 // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
1942 fn lower_async_fn_ret_ty(
1945 output: &FunctionRetTy,
1947 return_impl_trait_id: NodeId,
1948 ) -> hir::FunctionRetTy {
1949 // Get lifetimes used in the input arguments to the function. Our output type must also
1950 // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
1951 // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
1952 // is a subset of the other. We really want some new lifetime that is a subset of all input
1953 // lifetimes, but that doesn't exist at the moment.
1955 struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
1956 context: &'r mut LoweringContext<'a>,
1957 // Lifetimes bound by HRTB
1958 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1959 // Whether to count elided lifetimes.
1960 // Disabled inside of `Fn` or `fn` syntax.
1961 collect_elided_lifetimes: bool,
1962 // The lifetime found.
1963 // Multiple different or elided lifetimes cannot appear in async fn for now.
1964 output_lifetime: Option<(hir::LifetimeName, Span)>,
1967 impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
1968 fn nested_visit_map<'this>(
1970 ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1971 hir::intravisit::NestedVisitorMap::None
1974 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1975 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1976 if parameters.parenthesized {
1977 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1978 self.collect_elided_lifetimes = false;
1979 hir::intravisit::walk_generic_args(self, span, parameters);
1980 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1982 hir::intravisit::walk_generic_args(self, span, parameters);
1986 fn visit_ty(&mut self, t: &'v hir::Ty) {
1987 // Don't collect elided lifetimes used inside of `fn()` syntax
1988 if let &hir::Ty_::TyBareFn(_) = &t.node {
1989 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1990 self.collect_elided_lifetimes = false;
1992 // Record the "stack height" of `for<'a>` lifetime bindings
1993 // to be able to later fully undo their introduction.
1994 let old_len = self.currently_bound_lifetimes.len();
1995 hir::intravisit::walk_ty(self, t);
1996 self.currently_bound_lifetimes.truncate(old_len);
1998 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2000 hir::intravisit::walk_ty(self, t);
2004 fn visit_poly_trait_ref(
2006 trait_ref: &'v hir::PolyTraitRef,
2007 modifier: hir::TraitBoundModifier,
2009 // Record the "stack height" of `for<'a>` lifetime bindings
2010 // to be able to later fully undo their introduction.
2011 let old_len = self.currently_bound_lifetimes.len();
2012 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2013 self.currently_bound_lifetimes.truncate(old_len);
2016 fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2017 // Record the introduction of 'a in `for<'a> ...`
2018 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2019 // Introduce lifetimes one at a time so that we can handle
2020 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2021 let lt_name = hir::LifetimeName::Param(param.name);
2022 self.currently_bound_lifetimes.push(lt_name);
2025 hir::intravisit::walk_generic_param(self, param);
2028 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2029 let name = match lifetime.name {
2030 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2031 if self.collect_elided_lifetimes {
2032 // Use `'_` for both implicit and underscore lifetimes in
2033 // `abstract type Foo<'_>: SomeTrait<'_>;`
2034 hir::LifetimeName::Underscore
2039 hir::LifetimeName::Param(_) => lifetime.name,
2040 hir::LifetimeName::Static => return,
2043 if !self.currently_bound_lifetimes.contains(&name) {
2044 if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2045 // We don't currently have a reliable way to desugar `async fn` with
2046 // multiple potentially unrelated input lifetimes into
2047 // `-> impl Trait + 'lt`, so we report an error in this case.
2048 if current_lt_name != name {
2051 current_lt_span.between(lifetime.span),
2053 "multiple different lifetimes used in arguments of `async fn`",
2055 .span_label(current_lt_span, "first lifetime here")
2056 .span_label(lifetime.span, "different lifetime here")
2057 .help("`async fn` can only accept borrowed values \
2058 with identical lifetimes")
2060 } else if current_lt_name.is_elided() && name.is_elided() {
2063 current_lt_span.between(lifetime.span),
2065 "multiple elided lifetimes used in arguments of `async fn`",
2067 .span_label(current_lt_span, "first lifetime here")
2068 .span_label(lifetime.span, "different lifetime here")
2069 .help("consider giving these arguments named lifetimes")
2073 self.output_lifetime = Some((name, lifetime.span));
2079 let bound_lifetime = {
2080 let mut lifetime_collector = AsyncFnLifetimeCollector {
2082 currently_bound_lifetimes: Vec::new(),
2083 collect_elided_lifetimes: true,
2084 output_lifetime: None,
2088 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2090 lifetime_collector.output_lifetime
2093 let span = match output {
2094 FunctionRetTy::Ty(ty) => ty.span,
2095 FunctionRetTy::Default(span) => *span,
2098 let impl_trait_ty = self.lower_existential_impl_trait(
2099 span, fn_def_id, return_impl_trait_id, |this| {
2100 let output_ty = match output {
2101 FunctionRetTy::Ty(ty) =>
2102 this.lower_ty(ty, ImplTraitContext::Existential(fn_def_id)),
2103 FunctionRetTy::Default(span) => {
2104 let LoweredNodeId { node_id, hir_id } = this.next_id();
2108 node: hir::TyTup(hir_vec![]),
2115 let future_params = P(hir::GenericArgs {
2117 bindings: hir_vec![hir::TypeBinding {
2118 ident: Ident::from_str(FN_OUTPUT_NAME),
2120 id: this.next_id().node_id,
2123 parenthesized: false,
2127 this.std_path(span, &["future", "Future"], Some(future_params), false);
2129 let mut bounds = vec![
2130 hir::GenericBound::Trait(
2132 trait_ref: hir::TraitRef {
2134 ref_id: this.next_id().node_id,
2136 bound_generic_params: hir_vec![],
2139 hir::TraitBoundModifier::None
2143 if let Some((name, span)) = bound_lifetime {
2144 bounds.push(hir::GenericBound::Outlives(
2145 hir::Lifetime { id: this.next_id().node_id, name, span }));
2148 hir::HirVec::from(bounds)
2151 let LoweredNodeId { node_id, hir_id } = self.next_id();
2152 let impl_trait_ty = P(hir::Ty {
2154 node: impl_trait_ty,
2159 hir::FunctionRetTy::Return(impl_trait_ty)
2162 fn lower_param_bound(
2165 itctx: ImplTraitContext,
2166 ) -> hir::GenericBound {
2168 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2169 self.lower_poly_trait_ref(ty, itctx),
2170 self.lower_trait_bound_modifier(modifier),
2172 GenericBound::Outlives(ref lifetime) => {
2173 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2178 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2179 let span = l.ident.span;
2181 ident if ident.name == keywords::StaticLifetime.name() =>
2182 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2183 ident if ident.name == keywords::UnderscoreLifetime.name() =>
2184 match self.anonymous_lifetime_mode {
2185 AnonymousLifetimeMode::CreateParameter => {
2186 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2187 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2190 AnonymousLifetimeMode::PassThrough => {
2191 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2195 self.maybe_collect_in_band_lifetime(ident);
2196 let param_name = ParamName::Plain(ident);
2197 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2202 fn new_named_lifetime(
2206 name: hir::LifetimeName,
2207 ) -> hir::Lifetime {
2209 id: self.lower_node_id(id).node_id,
2215 fn lower_generic_params(
2217 params: &Vec<GenericParam>,
2218 add_bounds: &NodeMap<Vec<GenericBound>>,
2219 mut itctx: ImplTraitContext,
2220 ) -> hir::HirVec<hir::GenericParam> {
2221 params.iter().map(|param| {
2222 self.lower_generic_param(param, add_bounds, itctx.reborrow())
2226 fn lower_generic_param(&mut self,
2227 param: &GenericParam,
2228 add_bounds: &NodeMap<Vec<GenericBound>>,
2229 mut itctx: ImplTraitContext)
2230 -> hir::GenericParam {
2231 let mut bounds = self.lower_param_bounds(¶m.bounds, itctx.reborrow());
2233 GenericParamKind::Lifetime => {
2234 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2235 self.is_collecting_in_band_lifetimes = false;
2237 let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
2238 let param_name = match lt.name {
2239 hir::LifetimeName::Param(param_name) => param_name,
2240 _ => hir::ParamName::Plain(lt.name.ident()),
2242 let param = hir::GenericParam {
2246 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2247 attrs: self.lower_attrs(¶m.attrs),
2249 kind: hir::GenericParamKind::Lifetime { in_band: false }
2252 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2256 GenericParamKind::Type { ref default, .. } => {
2257 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2258 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2259 // Instead, use gensym("Self") to create a distinct name that looks the same.
2260 let ident = if param.ident.name == keywords::SelfType.name() {
2261 param.ident.gensym()
2266 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2267 if !add_bounds.is_empty() {
2268 let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2269 bounds = bounds.into_iter()
2275 id: self.lower_node_id(param.id).node_id,
2276 name: hir::ParamName::Plain(ident),
2277 pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"),
2278 attrs: self.lower_attrs(¶m.attrs),
2281 kind: hir::GenericParamKind::Type {
2282 default: default.as_ref().map(|x| {
2283 self.lower_ty(x, ImplTraitContext::Disallowed)
2285 synthetic: param.attrs.iter()
2286 .filter(|attr| attr.check_name("rustc_synthetic"))
2287 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2297 generics: &Generics,
2298 itctx: ImplTraitContext)
2301 // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2302 // FIXME: This could probably be done with less rightward drift. Also looks like two control
2303 // paths where report_error is called are also the only paths that advance to after
2304 // the match statement, so the error reporting could probably just be moved there.
2305 let mut add_bounds = NodeMap();
2306 for pred in &generics.where_clause.predicates {
2307 if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2308 'next_bound: for bound in &bound_pred.bounds {
2309 if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2310 let report_error = |this: &mut Self| {
2311 this.diagnostic().span_err(
2312 bound_pred.bounded_ty.span,
2313 "`?Trait` bounds are only permitted at the \
2314 point where a type parameter is declared",
2317 // Check if the where clause type is a plain type parameter.
2318 match bound_pred.bounded_ty.node {
2319 TyKind::Path(None, ref path)
2320 if path.segments.len() == 1
2321 && bound_pred.bound_generic_params.is_empty() =>
2323 if let Some(Def::TyParam(def_id)) = self.resolver
2324 .get_resolution(bound_pred.bounded_ty.id)
2325 .map(|d| d.base_def())
2327 if let Some(node_id) =
2328 self.resolver.definitions().as_local_node_id(def_id)
2330 for param in &generics.params {
2332 GenericParamKind::Type { .. } => {
2333 if node_id == param.id {
2334 add_bounds.entry(param.id)
2335 .or_insert(Vec::new())
2336 .push(bound.clone());
2337 continue 'next_bound;
2347 _ => report_error(self),
2355 params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2356 where_clause: self.lower_where_clause(&generics.where_clause),
2357 span: generics.span,
2361 fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2363 id: self.lower_node_id(wc.id).node_id,
2364 predicates: wc.predicates
2366 .map(|predicate| self.lower_where_predicate(predicate))
2371 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2373 WherePredicate::BoundPredicate(WhereBoundPredicate {
2374 ref bound_generic_params,
2379 self.with_in_scope_lifetime_defs(
2380 &bound_generic_params,
2382 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2383 bound_generic_params: this.lower_generic_params(
2384 bound_generic_params,
2386 ImplTraitContext::Disallowed,
2388 bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2391 .filter_map(|bound| match *bound {
2392 // Ignore `?Trait` bounds.
2393 // Tthey were copied into type parameters already.
2394 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2395 _ => Some(this.lower_param_bound(
2397 ImplTraitContext::Disallowed,
2406 WherePredicate::RegionPredicate(WhereRegionPredicate {
2410 }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2412 lifetime: self.lower_lifetime(lifetime),
2413 bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2415 WherePredicate::EqPredicate(WhereEqPredicate {
2420 }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2421 id: self.lower_node_id(id).node_id,
2422 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2423 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2429 fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2431 VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2435 .map(|f| self.lower_struct_field(f))
2437 self.lower_node_id(id).node_id,
2439 VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2443 .map(|f| self.lower_struct_field(f))
2445 self.lower_node_id(id).node_id,
2447 VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2451 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2452 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2453 hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2454 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2458 ref_id: self.lower_node_id(p.ref_id).node_id,
2462 fn lower_poly_trait_ref(
2465 mut itctx: ImplTraitContext,
2466 ) -> hir::PolyTraitRef {
2467 let bound_generic_params =
2468 self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx.reborrow());
2469 let trait_ref = self.with_parent_impl_lifetime_defs(
2470 &bound_generic_params,
2471 |this| this.lower_trait_ref(&p.trait_ref, itctx),
2475 bound_generic_params,
2481 fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2484 id: self.lower_node_id(f.id).node_id,
2485 ident: match f.ident {
2486 Some(ident) => ident,
2487 // FIXME(jseyfried) positional field hygiene
2488 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2490 vis: self.lower_visibility(&f.vis, None),
2491 ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2492 attrs: self.lower_attrs(&f.attrs),
2496 fn lower_field(&mut self, f: &Field) -> hir::Field {
2498 id: self.next_id().node_id,
2500 expr: P(self.lower_expr(&f.expr)),
2502 is_shorthand: f.is_shorthand,
2506 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2508 ty: self.lower_ty(&mt.ty, itctx),
2509 mutbl: self.lower_mutability(mt.mutbl),
2513 fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext)
2514 -> hir::GenericBounds {
2515 bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2518 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2519 let mut expr = None;
2521 let mut stmts = vec![];
2523 for (index, stmt) in b.stmts.iter().enumerate() {
2524 if index == b.stmts.len() - 1 {
2525 if let StmtKind::Expr(ref e) = stmt.node {
2526 expr = Some(P(self.lower_expr(e)));
2528 stmts.extend(self.lower_stmt(stmt));
2531 stmts.extend(self.lower_stmt(stmt));
2535 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2540 stmts: stmts.into(),
2542 rules: self.lower_block_check_mode(&b.rules),
2545 recovered: b.recovered,
2549 fn lower_async_body(
2555 self.lower_body(Some(decl), |this| {
2556 if let IsAsync::Async { closure_id, .. } = asyncness {
2557 let async_expr = this.make_async_expr(
2558 CaptureBy::Value, closure_id, None,
2560 let body = this.lower_block(body, false);
2561 this.expr_block(body, ThinVec::new())
2563 this.expr(body.span, async_expr, ThinVec::new())
2565 let body = this.lower_block(body, false);
2566 this.expr_block(body, ThinVec::new())
2575 attrs: &hir::HirVec<Attribute>,
2576 vis: &mut hir::Visibility,
2580 ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2581 ItemKind::Use(ref use_tree) => {
2582 // Start with an empty prefix
2585 span: use_tree.span,
2588 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2590 ItemKind::Static(ref t, m, ref e) => {
2591 let value = self.lower_body(None, |this| this.lower_expr(e));
2593 self.lower_ty(t, ImplTraitContext::Disallowed),
2594 self.lower_mutability(m),
2598 ItemKind::Const(ref t, ref e) => {
2599 let value = self.lower_body(None, |this| this.lower_expr(e));
2600 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2602 ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2603 let fn_def_id = self.resolver.definitions().local_def_id(id);
2605 self.with_new_scopes(|this| {
2606 // Note: we don't need to change the return type from `T` to
2607 // `impl Future<Output = T>` here because lower_body
2608 // only cares about the input argument patterns in the function
2609 // declaration (decl), not the return types.
2610 let body_id = this.lower_async_body(decl, header.asyncness, body);
2612 let (generics, fn_decl) = this.add_in_band_defs(
2615 AnonymousLifetimeMode::PassThrough,
2616 |this, idty| this.lower_fn_decl(
2617 decl, Some((fn_def_id, idty)), true, header.asyncness.opt_return_id()),
2622 this.lower_fn_header(header),
2628 ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2629 ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2630 ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2631 ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2632 self.lower_ty(t, ImplTraitContext::Disallowed),
2633 self.lower_generics(generics, ImplTraitContext::Disallowed),
2635 ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2637 variants: enum_definition
2640 .map(|x| self.lower_variant(x))
2643 self.lower_generics(generics, ImplTraitContext::Disallowed),
2645 ItemKind::Struct(ref struct_def, ref generics) => {
2646 let struct_def = self.lower_variant_data(struct_def);
2649 self.lower_generics(generics, ImplTraitContext::Disallowed),
2652 ItemKind::Union(ref vdata, ref generics) => {
2653 let vdata = self.lower_variant_data(vdata);
2656 self.lower_generics(generics, ImplTraitContext::Disallowed),
2668 let def_id = self.resolver.definitions().local_def_id(id);
2670 // Lower the "impl header" first. This ordering is important
2671 // for in-band lifetimes! Consider `'a` here:
2673 // impl Foo<'a> for u32 {
2674 // fn method(&'a self) { .. }
2677 // Because we start by lowering the `Foo<'a> for u32`
2678 // part, we will add `'a` to the list of generics on
2679 // the impl. When we then encounter it later in the
2680 // method, it will not be considered an in-band
2681 // lifetime to be added, but rather a reference to a
2683 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2686 AnonymousLifetimeMode::CreateParameter,
2688 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2689 this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2692 if let Some(ref trait_ref) = trait_ref {
2693 if let Def::Trait(def_id) = trait_ref.path.def {
2694 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2698 let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2700 (trait_ref, lowered_ty)
2704 let new_impl_items = self.with_in_scope_lifetime_defs(
2705 &ast_generics.params,
2709 .map(|item| this.lower_impl_item_ref(item))
2715 self.lower_unsafety(unsafety),
2716 self.lower_impl_polarity(polarity),
2717 self.lower_defaultness(defaultness, true /* [1] */),
2724 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2725 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
2728 .map(|item| self.lower_trait_item_ref(item))
2731 self.lower_is_auto(is_auto),
2732 self.lower_unsafety(unsafety),
2733 self.lower_generics(generics, ImplTraitContext::Disallowed),
2738 ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2739 self.lower_generics(generics, ImplTraitContext::Disallowed),
2740 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2742 ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2745 // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2746 // not cause an assertion failure inside the `lower_defaultness` function
2754 vis: &mut hir::Visibility,
2756 attrs: &hir::HirVec<Attribute>,
2758 let path = &tree.prefix;
2761 UseTreeKind::Simple(rename, id1, id2) => {
2762 *name = tree.ident().name;
2764 // First apply the prefix to the path
2765 let mut path = Path {
2769 .chain(path.segments.iter())
2775 // Correctly resolve `self` imports
2776 if path.segments.len() > 1
2777 && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2779 let _ = path.segments.pop();
2780 if rename.is_none() {
2781 *name = path.segments.last().unwrap().ident.name;
2785 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2786 let mut defs = self.expect_full_def_from_use(id);
2787 // we want to return *something* from this function, so hang onto the first item
2789 let mut ret_def = defs.next().unwrap_or(Def::Err);
2791 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2792 let vis = vis.clone();
2793 let name = name.clone();
2794 let span = path.span;
2795 self.resolver.definitions().create_def_with_parent(
2799 DefIndexAddressSpace::High,
2802 self.allocate_hir_id_counter(new_node_id, &path);
2804 self.with_hir_id_owner(new_node_id, |this| {
2805 let new_id = this.lower_node_id(new_node_id);
2806 let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2807 let item = hir::ItemUse(P(path), hir::UseKind::Single);
2808 let vis_kind = match vis.node {
2809 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2810 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2811 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2812 hir::VisibilityKind::Restricted { ref path, id: _ } => {
2813 hir::VisibilityKind::Restricted {
2815 // We are allocating a new NodeId here
2816 id: this.next_id().node_id,
2820 let vis = respan(vis.span, vis_kind);
2826 hir_id: new_id.hir_id,
2828 attrs: attrs.clone(),
2837 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2838 hir::ItemUse(path, hir::UseKind::Single)
2840 UseTreeKind::Glob => {
2841 let path = P(self.lower_path(
2847 .chain(path.segments.iter())
2852 ParamMode::Explicit,
2854 hir::ItemUse(path, hir::UseKind::Glob)
2856 UseTreeKind::Nested(ref trees) => {
2861 .chain(path.segments.iter())
2864 span: prefix.span.to(path.span),
2867 // Add all the nested PathListItems in the HIR
2868 for &(ref use_tree, id) in trees {
2869 self.allocate_hir_id_counter(id, &use_tree);
2873 } = self.lower_node_id(id);
2875 let mut vis = vis.clone();
2876 let mut name = name.clone();
2878 self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2880 self.with_hir_id_owner(new_id, |this| {
2881 let vis_kind = match vis.node {
2882 hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2883 hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2884 hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2885 hir::VisibilityKind::Restricted { ref path, id: _ } => {
2886 hir::VisibilityKind::Restricted {
2888 // We are allocating a new NodeId here
2889 id: this.next_id().node_id,
2893 let vis = respan(vis.span, vis_kind);
2901 attrs: attrs.clone(),
2904 span: use_tree.span,
2910 // Privatize the degenerate import base, used only to check
2911 // the stability of `use a::{};`, to avoid it showing up as
2912 // a re-export by accident when `pub`, e.g. in documentation.
2913 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2914 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
2915 hir::ItemUse(path, hir::UseKind::ListStem)
2920 fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2921 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2922 let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2924 let (generics, node) = match i.node {
2925 TraitItemKind::Const(ref ty, ref default) => (
2926 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2927 hir::TraitItemKind::Const(
2928 self.lower_ty(ty, ImplTraitContext::Disallowed),
2931 .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2934 TraitItemKind::Method(ref sig, None) => {
2935 let names = self.lower_fn_args_to_names(&sig.decl);
2936 let (generics, sig) = self.lower_method_sig(
2943 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
2945 TraitItemKind::Method(ref sig, Some(ref body)) => {
2946 let body_id = self.lower_body(Some(&sig.decl), |this| {
2947 let body = this.lower_block(body, false);
2948 this.expr_block(body, ThinVec::new())
2951 let (generics, sig) = self.lower_method_sig(
2959 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
2961 TraitItemKind::Type(ref bounds, ref default) => (
2962 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2963 hir::TraitItemKind::Type(
2964 self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
2967 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2970 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2977 attrs: self.lower_attrs(&i.attrs),
2984 fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2985 let (kind, has_default) = match i.node {
2986 TraitItemKind::Const(_, ref default) => {
2987 (hir::AssociatedItemKind::Const, default.is_some())
2989 TraitItemKind::Type(_, ref default) => {
2990 (hir::AssociatedItemKind::Type, default.is_some())
2992 TraitItemKind::Method(ref sig, ref default) => (
2993 hir::AssociatedItemKind::Method {
2994 has_self: sig.decl.has_self(),
2998 TraitItemKind::Macro(..) => unimplemented!(),
3001 id: hir::TraitItemId { node_id: i.id },
3004 defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3009 fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3010 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3011 let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3013 let (generics, node) = match i.node {
3014 ImplItemKind::Const(ref ty, ref expr) => {
3015 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3017 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3018 hir::ImplItemKind::Const(
3019 self.lower_ty(ty, ImplTraitContext::Disallowed),
3024 ImplItemKind::Method(ref sig, ref body) => {
3025 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3026 let impl_trait_return_allow = !self.is_in_trait_impl;
3027 let (generics, sig) = self.lower_method_sig(
3031 impl_trait_return_allow,
3032 sig.header.asyncness.opt_return_id(),
3034 (generics, hir::ImplItemKind::Method(sig, body_id))
3036 ImplItemKind::Type(ref ty) => (
3037 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
3038 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
3040 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3047 attrs: self.lower_attrs(&i.attrs),
3049 vis: self.lower_visibility(&i.vis, None),
3050 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3055 // [1] since `default impl` is not yet implemented, this is always true in impls
3058 fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3060 id: hir::ImplItemId { node_id: i.id },
3063 vis: self.lower_visibility(&i.vis, Some(i.id)),
3064 defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3065 kind: match i.node {
3066 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3067 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3068 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3069 has_self: sig.decl.has_self(),
3071 ImplItemKind::Macro(..) => unimplemented!(),
3075 // [1] since `default impl` is not yet implemented, this is always true in impls
3078 fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3081 item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3085 /// Lowers `impl Trait` items and appends them to the list
3086 fn lower_impl_trait_ids(
3090 ids: &mut SmallVector<hir::ItemId>,
3092 if let Some(id) = header.asyncness.opt_return_id() {
3093 ids.push(hir::ItemId { id });
3095 struct IdVisitor<'a> { ids: &'a mut SmallVector<hir::ItemId> }
3096 impl<'a, 'b> Visitor<'a> for IdVisitor<'b> {
3097 fn visit_ty(&mut self, ty: &'a Ty) {
3103 TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
3106 visit::walk_ty(self, ty);
3108 fn visit_path_segment(
3111 path_segment: &'v PathSegment,
3113 if let Some(ref p) = path_segment.args {
3114 if let GenericArgs::Parenthesized(_) = **p {
3118 visit::walk_path_segment(self, path_span, path_segment)
3121 let mut visitor = IdVisitor { ids };
3123 FunctionRetTy::Default(_) => {},
3124 FunctionRetTy::Ty(ref ty) => visitor.visit_ty(ty),
3128 fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
3130 ItemKind::Use(ref use_tree) => {
3131 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
3132 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3135 ItemKind::MacroDef(..) => SmallVector::new(),
3136 ItemKind::Fn(ref decl, ref header, ..) => {
3137 let mut ids = SmallVector::one(hir::ItemId { id: i.id });
3138 self.lower_impl_trait_ids(decl, header, &mut ids);
3141 ItemKind::Impl(.., None, _, ref items) => {
3142 let mut ids = SmallVector::one(hir::ItemId { id: i.id });
3144 if let ImplItemKind::Method(ref sig, _) = item.node {
3145 self.lower_impl_trait_ids(&sig.decl, &sig.header, &mut ids);
3150 _ => SmallVector::one(hir::ItemId { id: i.id }),
3154 fn lower_item_id_use_tree(&mut self,
3157 vec: &mut SmallVector<hir::ItemId>)
3160 UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3161 vec.push(hir::ItemId { id });
3162 self.lower_item_id_use_tree(nested, id, vec);
3164 UseTreeKind::Glob => {}
3165 UseTreeKind::Simple(_, id1, id2) => {
3166 for (_, &id) in self.expect_full_def_from_use(base_id)
3168 .zip([id1, id2].iter())
3170 vec.push(hir::ItemId { id });
3176 pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3177 let mut name = i.ident.name;
3178 let mut vis = self.lower_visibility(&i.vis, None);
3179 let attrs = self.lower_attrs(&i.attrs);
3180 if let ItemKind::MacroDef(ref def) = i.node {
3181 if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
3182 let body = self.lower_token_stream(def.stream());
3183 self.exported_macros.push(hir::MacroDef {
3196 let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3198 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3211 fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3212 let node_id = self.lower_node_id(i.id).node_id;
3213 let def_id = self.resolver.definitions().local_def_id(node_id);
3217 attrs: self.lower_attrs(&i.attrs),
3218 node: match i.node {
3219 ForeignItemKind::Fn(ref fdec, ref generics) => {
3220 let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3223 AnonymousLifetimeMode::PassThrough,
3226 // Disallow impl Trait in foreign items
3227 this.lower_fn_decl(fdec, None, false, None),
3228 this.lower_fn_args_to_names(fdec),
3233 hir::ForeignItemFn(fn_dec, fn_args, generics)
3235 ForeignItemKind::Static(ref t, m) => {
3236 hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
3238 ForeignItemKind::Ty => hir::ForeignItemType,
3239 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3241 vis: self.lower_visibility(&i.vis, None),
3246 fn lower_method_sig(
3248 generics: &Generics,
3251 impl_trait_return_allow: bool,
3252 is_async: Option<NodeId>,
3253 ) -> (hir::Generics, hir::MethodSig) {
3254 let header = self.lower_fn_header(sig.header);
3255 let (generics, decl) = self.add_in_band_defs(
3258 AnonymousLifetimeMode::PassThrough,
3259 |this, idty| this.lower_fn_decl(
3261 Some((fn_def_id, idty)),
3262 impl_trait_return_allow,
3266 (generics, hir::MethodSig { header, decl })
3269 fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3271 IsAuto::Yes => hir::IsAuto::Yes,
3272 IsAuto::No => hir::IsAuto::No,
3276 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3278 unsafety: self.lower_unsafety(h.unsafety),
3279 asyncness: self.lower_asyncness(h.asyncness),
3280 constness: self.lower_constness(h.constness),
3285 fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3287 Unsafety::Unsafe => hir::Unsafety::Unsafe,
3288 Unsafety::Normal => hir::Unsafety::Normal,
3292 fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3294 Constness::Const => hir::Constness::Const,
3295 Constness::NotConst => hir::Constness::NotConst,
3299 fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3301 IsAsync::Async { .. } => hir::IsAsync::Async,
3302 IsAsync::NotAsync => hir::IsAsync::NotAsync,
3306 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3308 UnOp::Deref => hir::UnDeref,
3309 UnOp::Not => hir::UnNot,
3310 UnOp::Neg => hir::UnNeg,
3314 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3316 node: match b.node {
3317 BinOpKind::Add => hir::BinOpKind::Add,
3318 BinOpKind::Sub => hir::BinOpKind::Sub,
3319 BinOpKind::Mul => hir::BinOpKind::Mul,
3320 BinOpKind::Div => hir::BinOpKind::Div,
3321 BinOpKind::Rem => hir::BinOpKind::Rem,
3322 BinOpKind::And => hir::BinOpKind::And,
3323 BinOpKind::Or => hir::BinOpKind::Or,
3324 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3325 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3326 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3327 BinOpKind::Shl => hir::BinOpKind::Shl,
3328 BinOpKind::Shr => hir::BinOpKind::Shr,
3329 BinOpKind::Eq => hir::BinOpKind::Eq,
3330 BinOpKind::Lt => hir::BinOpKind::Lt,
3331 BinOpKind::Le => hir::BinOpKind::Le,
3332 BinOpKind::Ne => hir::BinOpKind::Ne,
3333 BinOpKind::Ge => hir::BinOpKind::Ge,
3334 BinOpKind::Gt => hir::BinOpKind::Gt,
3340 fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3341 let node = match p.node {
3342 PatKind::Wild => hir::PatKind::Wild,
3343 PatKind::Ident(ref binding_mode, ident, ref sub) => {
3344 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3345 // `None` can occur in body-less function signatures
3346 def @ None | def @ Some(Def::Local(_)) => {
3347 let canonical_id = match def {
3348 Some(Def::Local(id)) => id,
3351 hir::PatKind::Binding(
3352 self.lower_binding_mode(binding_mode),
3355 sub.as_ref().map(|x| self.lower_pat(x)),
3358 Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3363 segments: hir_vec![hir::PathSegment::from_ident(ident)],
3368 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3369 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3370 let qpath = self.lower_qpath(
3374 ParamMode::Optional,
3375 ImplTraitContext::Disallowed,
3377 hir::PatKind::TupleStruct(
3379 pats.iter().map(|x| self.lower_pat(x)).collect(),
3383 PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3387 ParamMode::Optional,
3388 ImplTraitContext::Disallowed,
3390 PatKind::Struct(ref path, ref fields, etc) => {
3391 let qpath = self.lower_qpath(
3395 ParamMode::Optional,
3396 ImplTraitContext::Disallowed,
3403 node: hir::FieldPat {
3404 id: self.next_id().node_id,
3405 ident: f.node.ident,
3406 pat: self.lower_pat(&f.node.pat),
3407 is_shorthand: f.node.is_shorthand,
3411 hir::PatKind::Struct(qpath, fs, etc)
3413 PatKind::Tuple(ref elts, ddpos) => {
3414 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3416 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3417 PatKind::Ref(ref inner, mutbl) => {
3418 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3420 PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3421 P(self.lower_expr(e1)),
3422 P(self.lower_expr(e2)),
3423 self.lower_range_end(end),
3425 PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3426 before.iter().map(|x| self.lower_pat(x)).collect(),
3427 slice.as_ref().map(|x| self.lower_pat(x)),
3428 after.iter().map(|x| self.lower_pat(x)).collect(),
3430 PatKind::Paren(ref inner) => return self.lower_pat(inner),
3431 PatKind::Mac(_) => panic!("Shouldn't exist here"),
3434 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3443 fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3445 RangeEnd::Included(_) => hir::RangeEnd::Included,
3446 RangeEnd::Excluded => hir::RangeEnd::Excluded,
3450 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3451 let was_in_loop_condition = self.is_in_loop_condition;
3452 self.is_in_loop_condition = false;
3453 let was_in_anon_const = self.is_in_anon_const;
3454 self.is_in_anon_const = true;
3456 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3457 let anon_const = hir::AnonConst {
3460 body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3463 self.is_in_anon_const = was_in_anon_const;
3464 self.is_in_loop_condition = was_in_loop_condition;
3469 fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3470 let kind = match e.node {
3471 ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
3472 ExprKind::ObsoleteInPlace(..) => {
3473 self.sess.abort_if_errors();
3474 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3476 ExprKind::Array(ref exprs) => {
3477 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
3479 ExprKind::Repeat(ref expr, ref count) => {
3480 let expr = P(self.lower_expr(expr));
3481 let count = self.lower_anon_const(count);
3482 hir::ExprRepeat(expr, count)
3484 ExprKind::Tup(ref elts) => {
3485 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
3487 ExprKind::Call(ref f, ref args) => {
3488 let f = P(self.lower_expr(f));
3489 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
3491 ExprKind::MethodCall(ref seg, ref args) => {
3492 let hir_seg = self.lower_path_segment(
3495 ParamMode::Optional,
3497 ParenthesizedGenericArgs::Err,
3498 ImplTraitContext::Disallowed,
3500 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3501 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
3503 ExprKind::Binary(binop, ref lhs, ref rhs) => {
3504 let binop = self.lower_binop(binop);
3505 let lhs = P(self.lower_expr(lhs));
3506 let rhs = P(self.lower_expr(rhs));
3507 hir::ExprBinary(binop, lhs, rhs)
3509 ExprKind::Unary(op, ref ohs) => {
3510 let op = self.lower_unop(op);
3511 let ohs = P(self.lower_expr(ohs));
3512 hir::ExprUnary(op, ohs)
3514 ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
3515 ExprKind::Cast(ref expr, ref ty) => {
3516 let expr = P(self.lower_expr(expr));
3517 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3519 ExprKind::Type(ref expr, ref ty) => {
3520 let expr = P(self.lower_expr(expr));
3521 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3523 ExprKind::AddrOf(m, ref ohs) => {
3524 let m = self.lower_mutability(m);
3525 let ohs = P(self.lower_expr(ohs));
3526 hir::ExprAddrOf(m, ohs)
3528 // More complicated than you might expect because the else branch
3529 // might be `if let`.
3530 ExprKind::If(ref cond, ref blk, ref else_opt) => {
3531 let else_opt = else_opt.as_ref().map(|els| {
3533 ExprKind::IfLet(..) => {
3534 // wrap the if-let expr in a block
3535 let span = els.span;
3536 let els = P(self.lower_expr(els));
3537 let LoweredNodeId { node_id, hir_id } = self.next_id();
3538 let blk = P(hir::Block {
3543 rules: hir::DefaultBlock,
3545 targeted_by_break: false,
3546 recovered: blk.recovered,
3548 P(self.expr_block(blk, ThinVec::new()))
3550 _ => P(self.lower_expr(els)),
3554 let then_blk = self.lower_block(blk, false);
3555 let then_expr = self.expr_block(then_blk, ThinVec::new());
3557 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3559 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3561 this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3562 this.lower_block(body, false),
3563 this.lower_label(opt_label),
3566 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3568 this.lower_block(body, false),
3569 this.lower_label(opt_label),
3570 hir::LoopSource::Loop,
3573 ExprKind::Catch(ref body) => {
3574 self.with_catch_scope(body.id, |this| {
3576 this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3577 let mut block = this.lower_block(body, true).into_inner();
3578 let tail = block.expr.take().map_or_else(
3580 let LoweredNodeId { node_id, hir_id } = this.next_id();
3581 let span = this.sess.codemap().end_point(unstable_span);
3585 node: hir::ExprTup(hir_vec![]),
3586 attrs: ThinVec::new(),
3590 |x: P<hir::Expr>| x.into_inner(),
3592 block.expr = Some(this.wrap_in_try_constructor(
3593 "from_ok", tail, unstable_span));
3594 hir::ExprBlock(P(block), None)
3597 ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3598 P(self.lower_expr(expr)),
3599 arms.iter().map(|x| self.lower_arm(x)).collect(),
3600 hir::MatchSource::Normal,
3602 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3603 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3604 this.with_new_scopes(|this| {
3605 let block = this.lower_block(block, false);
3606 this.expr_block(block, ThinVec::new())
3611 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3613 if let IsAsync::Async { closure_id, .. } = asyncness {
3614 let outer_decl = FnDecl {
3615 inputs: decl.inputs.clone(),
3616 output: FunctionRetTy::Default(fn_decl_span),
3619 // We need to lower the declaration outside the new scope, because we
3620 // have to conserve the state of being inside a loop condition for the
3621 // closure argument types.
3622 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3624 self.with_new_scopes(|this| {
3625 // FIXME(cramertj) allow `async` non-`move` closures with
3626 if capture_clause == CaptureBy::Ref &&
3627 !decl.inputs.is_empty()
3633 "`async` non-`move` closures with arguments \
3634 are not currently supported",
3636 .help("consider using `let` statements to manually capture \
3637 variables by reference before entering an \
3638 `async move` closure")
3642 // Transform `async |x: u8| -> X { ... }` into
3643 // `|x: u8| future_from_generator(|| -> X { ... })`
3644 let body_id = this.lower_body(Some(&outer_decl), |this| {
3645 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3648 let async_body = this.make_async_expr(
3649 capture_clause, closure_id, async_ret_ty,
3651 this.with_new_scopes(|this| this.lower_expr(body))
3653 this.expr(fn_decl_span, async_body, ThinVec::new())
3656 this.lower_capture_clause(capture_clause),
3664 // Lower outside new scope to preserve `is_in_loop_condition`.
3665 let fn_decl = self.lower_fn_decl(decl, None, false, None);
3667 self.with_new_scopes(|this| {
3668 let mut is_generator = false;
3669 let body_id = this.lower_body(Some(decl), |this| {
3670 let e = this.lower_expr(body);
3671 is_generator = this.is_generator;
3674 let generator_option = if is_generator {
3675 if !decl.inputs.is_empty() {
3680 "generators cannot have explicit arguments"
3682 this.sess.abort_if_errors();
3684 Some(match movability {
3685 Movability::Movable => hir::GeneratorMovability::Movable,
3686 Movability::Static => hir::GeneratorMovability::Static,
3689 if movability == Movability::Static {
3694 "closures cannot be static"
3700 this.lower_capture_clause(capture_clause),
3709 ExprKind::Block(ref blk, opt_label) => {
3710 hir::ExprBlock(self.lower_block(blk,
3711 opt_label.is_some()),
3712 self.lower_label(opt_label))
3714 ExprKind::Assign(ref el, ref er) => {
3715 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3717 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3718 self.lower_binop(op),
3719 P(self.lower_expr(el)),
3720 P(self.lower_expr(er)),
3722 ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3723 ExprKind::Index(ref el, ref er) => {
3724 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3726 // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3727 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3728 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3729 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3730 let id = self.next_id();
3731 let e1 = self.lower_expr(e1);
3732 let e2 = self.lower_expr(e2);
3733 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], None, false));
3734 let ty = P(self.ty_path(id, span, hir::QPath::Resolved(None, ty_path)));
3735 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3736 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3737 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3738 hir::ExprCall(new, hir_vec![e1, e2])
3740 ExprKind::Range(ref e1, ref e2, lims) => {
3741 use syntax::ast::RangeLimits::*;
3743 let path = match (e1, e2, lims) {
3744 (&None, &None, HalfOpen) => "RangeFull",
3745 (&Some(..), &None, HalfOpen) => "RangeFrom",
3746 (&None, &Some(..), HalfOpen) => "RangeTo",
3747 (&Some(..), &Some(..), HalfOpen) => "Range",
3748 (&None, &Some(..), Closed) => "RangeToInclusive",
3749 (&Some(..), &Some(..), Closed) => unreachable!(),
3750 (_, &None, Closed) => self.diagnostic()
3751 .span_fatal(e.span, "inclusive range with no end")
3755 let fields = e1.iter()
3756 .map(|e| ("start", e))
3757 .chain(e2.iter().map(|e| ("end", e)))
3759 let expr = P(self.lower_expr(&e));
3761 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3762 let ident = Ident::new(Symbol::intern(s), unstable_span);
3763 self.field(ident, expr, unstable_span)
3765 .collect::<P<[hir::Field]>>();
3767 let is_unit = fields.is_empty();
3769 self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3770 let struct_path = iter::once("ops")
3771 .chain(iter::once(path))
3772 .collect::<Vec<_>>();
3773 let struct_path = self.std_path(unstable_span, &struct_path, None, is_unit);
3774 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3776 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3782 hir::ExprPath(struct_path)
3784 hir::ExprStruct(struct_path, fields, None)
3786 span: unstable_span,
3787 attrs: e.attrs.clone(),
3790 ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3794 ParamMode::Optional,
3795 ImplTraitContext::Disallowed,
3797 ExprKind::Break(opt_label, ref opt_expr) => {
3798 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3801 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3804 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3808 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3811 ExprKind::Continue(opt_label) => {
3812 hir::ExprContinue(if self.is_in_loop_condition && opt_label.is_none() {
3815 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3818 self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3821 ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3822 ExprKind::InlineAsm(ref asm) => {
3823 let hir_asm = hir::InlineAsm {
3824 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3825 outputs: asm.outputs
3827 .map(|out| hir::InlineAsmOutput {
3828 constraint: out.constraint.clone(),
3830 is_indirect: out.is_indirect,
3833 asm: asm.asm.clone(),
3834 asm_str_style: asm.asm_str_style,
3835 clobbers: asm.clobbers.clone().into(),
3836 volatile: asm.volatile,
3837 alignstack: asm.alignstack,
3838 dialect: asm.dialect,
3841 let outputs = asm.outputs
3843 .map(|out| self.lower_expr(&out.expr))
3845 let inputs = asm.inputs
3847 .map(|&(_, ref input)| self.lower_expr(input))
3849 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3851 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3856 ParamMode::Optional,
3857 ImplTraitContext::Disallowed,
3859 fields.iter().map(|x| self.lower_field(x)).collect(),
3860 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3862 ExprKind::Paren(ref ex) => {
3863 let mut ex = self.lower_expr(ex);
3864 // include parens in span, but only if it is a super-span.
3865 if e.span.contains(ex.span) {
3868 // merge attributes into the inner expression.
3869 let mut attrs = e.attrs.clone();
3870 attrs.extend::<Vec<_>>(ex.attrs.into());
3875 ExprKind::Yield(ref opt_expr) => {
3876 self.is_generator = true;
3879 .map(|x| self.lower_expr(x))
3880 .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3881 hir::ExprYield(P(expr))
3884 // Desugar ExprIfLet
3885 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3886 ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3889 // match <sub_expr> {
3891 // _ => [<else_opt> | ()]
3894 let mut arms = vec![];
3896 // `<pat> => <body>`
3898 let body = self.lower_block(body, false);
3899 let body_expr = P(self.expr_block(body, ThinVec::new()));
3900 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3901 arms.push(self.arm(pats, body_expr));
3904 // _ => [<else_opt>|()]
3906 let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3907 let wildcard_pattern = self.pat_wild(e.span);
3908 let body = if let Some(else_expr) = wildcard_arm {
3909 P(self.lower_expr(else_expr))
3911 self.expr_tuple(e.span, hir_vec![])
3913 arms.push(self.arm(hir_vec![wildcard_pattern], body));
3916 let contains_else_clause = else_opt.is_some();
3918 let sub_expr = P(self.lower_expr(sub_expr));
3923 hir::MatchSource::IfLetDesugar {
3924 contains_else_clause,
3929 // Desugar ExprWhileLet
3930 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3931 ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3934 // [opt_ident]: loop {
3935 // match <sub_expr> {
3941 // Note that the block AND the condition are evaluated in the loop scope.
3942 // This is done to allow `break` from inside the condition of the loop.
3943 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3945 this.lower_block(body, false),
3946 this.expr_break(e.span, ThinVec::new()),
3947 this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3951 // `<pat> => <body>`
3953 let body_expr = P(self.expr_block(body, ThinVec::new()));
3954 let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3955 self.arm(pats, body_expr)
3960 let pat_under = self.pat_wild(e.span);
3961 self.arm(hir_vec![pat_under], break_expr)
3964 // `match <sub_expr> { ... }`
3965 let arms = hir_vec![pat_arm, break_arm];
3966 let match_expr = self.expr(
3968 hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3972 // `[opt_ident]: loop { ... }`
3973 let loop_block = P(self.block_expr(P(match_expr)));
3974 let loop_expr = hir::ExprLoop(
3976 self.lower_label(opt_label),
3977 hir::LoopSource::WhileLet,
3979 // add attributes to the outer returned expr node
3983 // Desugar ExprForLoop
3984 // From: `[opt_ident]: for <pat> in <head> <body>`
3985 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3989 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3991 // [opt_ident]: loop {
3993 // match ::std::iter::Iterator::next(&mut iter) {
3994 // ::std::option::Option::Some(val) => __next = val,
3995 // ::std::option::Option::None => break
3997 // let <pat> = __next;
3998 // StmtExpr(<body>);
4006 let head = self.lower_expr(head);
4007 let head_sp = head.span;
4009 let iter = self.str_to_ident("iter");
4011 let next_ident = self.str_to_ident("__next");
4012 let next_pat = self.pat_ident_binding_mode(
4015 hir::BindingAnnotation::Mutable,
4018 // `::std::option::Option::Some(val) => next = val`
4020 let val_ident = self.str_to_ident("val");
4021 let val_pat = self.pat_ident(pat.span, val_ident);
4022 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4023 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4024 let assign = P(self.expr(
4026 hir::ExprAssign(next_expr, val_expr),
4029 let some_pat = self.pat_some(pat.span, val_pat);
4030 self.arm(hir_vec![some_pat], assign)
4033 // `::std::option::Option::None => break`
4036 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4037 let pat = self.pat_none(e.span);
4038 self.arm(hir_vec![pat], break_expr)
4043 self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
4045 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4047 let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4048 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4049 let next_path = &["iter", "Iterator", "next"];
4050 let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4051 let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4052 let arms = hir_vec![pat_arm, break_arm];
4056 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
4060 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
4062 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4066 self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
4068 // `let <pat> = __next`
4069 let pat = self.lower_pat(pat);
4070 let pat_let = self.stmt_let_pat(
4074 hir::LocalSource::ForLoopDesugar,
4077 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4078 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4079 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
4081 let loop_block = P(self.block_all(
4083 hir_vec![next_let, match_stmt, pat_let, body_stmt],
4087 // `[opt_ident]: loop { ... }`
4088 let loop_expr = hir::ExprLoop(
4090 self.lower_label(opt_label),
4091 hir::LoopSource::ForLoop,
4093 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4094 let loop_expr = P(hir::Expr {
4099 attrs: ThinVec::new(),
4102 // `mut iter => { ... }`
4103 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4105 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4106 let into_iter_expr = {
4107 let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4108 let into_iter = P(self.expr_std_path(
4109 head_sp, into_iter_path, None, ThinVec::new()));
4110 P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4113 let match_expr = P(self.expr_match(
4117 hir::MatchSource::ForLoopDesugar,
4120 // `{ let _result = ...; _result }`
4121 // underscore prevents an unused_variables lint if the head diverges
4122 let result_ident = self.str_to_ident("_result");
4123 let (let_stmt, let_stmt_binding) =
4124 self.stmt_let(e.span, false, result_ident, match_expr);
4126 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4127 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4128 // add the attributes to the outer returned expr node
4129 return self.expr_block(block, e.attrs.clone());
4132 // Desugar ExprKind::Try
4134 ExprKind::Try(ref sub_expr) => {
4137 // match Try::into_result(<expr>) {
4138 // Ok(val) => #[allow(unreachable_code)] val,
4139 // Err(err) => #[allow(unreachable_code)]
4140 // // If there is an enclosing `catch {...}`
4141 // break 'catch_target Try::from_error(From::from(err)),
4143 // return Try::from_error(From::from(err)),
4147 self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4149 // Try::into_result(<expr>)
4152 let sub_expr = self.lower_expr(sub_expr);
4154 let path = &["ops", "Try", "into_result"];
4155 let path = P(self.expr_std_path(
4156 unstable_span, path, None, ThinVec::new()));
4157 P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4160 // #[allow(unreachable_code)]
4162 // allow(unreachable_code)
4164 let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4165 let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4166 let uc_nested = attr::mk_nested_word_item(uc_ident);
4167 attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4169 attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4171 let attrs = vec![attr];
4173 // Ok(val) => #[allow(unreachable_code)] val,
4175 let val_ident = self.str_to_ident("val");
4176 let val_pat = self.pat_ident(e.span, val_ident);
4177 let val_expr = P(self.expr_ident_with_attrs(
4181 ThinVec::from(attrs.clone()),
4183 let ok_pat = self.pat_ok(e.span, val_pat);
4185 self.arm(hir_vec![ok_pat], val_expr)
4188 // Err(err) => #[allow(unreachable_code)]
4189 // return Try::from_error(From::from(err)),
4191 let err_ident = self.str_to_ident("err");
4192 let err_local = self.pat_ident(e.span, err_ident);
4194 let path = &["convert", "From", "from"];
4195 let from = P(self.expr_std_path(
4196 e.span, path, None, ThinVec::new()));
4197 let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4199 self.expr_call(e.span, from, hir_vec![err_expr])
4202 self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4203 let thin_attrs = ThinVec::from(attrs);
4204 let catch_scope = self.catch_scopes.last().map(|x| *x);
4205 let ret_expr = if let Some(catch_node) = catch_scope {
4211 target_id: Ok(catch_node),
4213 Some(from_err_expr),
4218 P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
4221 let err_pat = self.pat_err(e.span, err_local);
4222 self.arm(hir_vec![err_pat], ret_expr)
4227 hir_vec![err_arm, ok_arm],
4228 hir::MatchSource::TryDesugar,
4232 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4235 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4242 attrs: e.attrs.clone(),
4246 fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
4247 SmallVector::one(match s.node {
4248 StmtKind::Local(ref l) => Spanned {
4249 node: hir::StmtDecl(
4251 node: hir::DeclLocal(self.lower_local(l)),
4254 self.lower_node_id(s.id).node_id,
4258 StmtKind::Item(ref it) => {
4259 // Can only use the ID once.
4260 let mut id = Some(s.id);
4261 return self.lower_item_id(it)
4263 .map(|item_id| Spanned {
4264 node: hir::StmtDecl(
4266 node: hir::DeclItem(item_id),
4270 .map(|id| self.lower_node_id(id).node_id)
4271 .unwrap_or_else(|| self.next_id().node_id),
4277 StmtKind::Expr(ref e) => Spanned {
4278 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4281 StmtKind::Semi(ref e) => Spanned {
4282 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4285 StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4289 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4291 CaptureBy::Value => hir::CaptureByValue,
4292 CaptureBy::Ref => hir::CaptureByRef,
4296 /// If an `explicit_owner` is given, this method allocates the `HirId` in
4297 /// the address space of that item instead of the item currently being
4298 /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4299 /// lower a `Visibility` value although we haven't lowered the owning
4300 /// `ImplItem` in question yet.
4301 fn lower_visibility(
4304 explicit_owner: Option<NodeId>,
4305 ) -> hir::Visibility {
4306 let node = match v.node {
4307 VisibilityKind::Public => hir::VisibilityKind::Public,
4308 VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4309 VisibilityKind::Restricted { ref path, id } => hir::VisibilityKind::Restricted {
4310 path: P(self.lower_path(id, path, ParamMode::Explicit)),
4311 id: if let Some(owner) = explicit_owner {
4312 self.lower_node_id_with_owner(id, owner).node_id
4314 self.lower_node_id(id).node_id
4317 VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4319 respan(v.span, node)
4322 fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4324 Defaultness::Default => hir::Defaultness::Default {
4325 has_value: has_value,
4327 Defaultness::Final => {
4329 hir::Defaultness::Final
4334 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4336 BlockCheckMode::Default => hir::DefaultBlock,
4337 BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4341 fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4343 BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4344 BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4345 BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4346 BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4350 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4352 CompilerGenerated => hir::CompilerGenerated,
4353 UserProvided => hir::UserProvided,
4357 fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4359 ImplPolarity::Positive => hir::ImplPolarity::Positive,
4360 ImplPolarity::Negative => hir::ImplPolarity::Negative,
4364 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4366 TraitBoundModifier::None => hir::TraitBoundModifier::None,
4367 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4371 // Helper methods for building HIR.
4373 fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4382 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4384 id: self.next_id().node_id,
4388 is_shorthand: false,
4392 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4393 let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
4394 P(self.expr(span, expr_break, attrs))
4401 args: hir::HirVec<hir::Expr>,
4403 self.expr(span, hir::ExprCall(e, args), ThinVec::new())
4406 fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4407 self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4410 fn expr_ident_with_attrs(
4415 attrs: ThinVec<Attribute>,
4417 let expr_path = hir::ExprPath(hir::QPath::Resolved(
4421 def: Def::Local(binding),
4422 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4426 self.expr(span, expr_path, attrs)
4429 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4430 self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
4436 components: &[&str],
4437 params: Option<P<hir::GenericArgs>>,
4438 attrs: ThinVec<Attribute>,
4440 let path = self.std_path(span, components, params, true);
4443 hir::ExprPath(hir::QPath::Resolved(None, P(path))),
4452 arms: hir::HirVec<hir::Arm>,
4453 source: hir::MatchSource,
4455 self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
4458 fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4459 self.expr(b.span, hir::ExprBlock(b, None), attrs)
4462 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4463 P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
4466 fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
4467 let LoweredNodeId { node_id, hir_id } = self.next_id();
4480 ex: Option<P<hir::Expr>>,
4482 source: hir::LocalSource,
4484 let LoweredNodeId { node_id, hir_id } = self.next_id();
4486 let local = P(hir::Local {
4493 attrs: ThinVec::new(),
4496 let decl = respan(sp, hir::DeclLocal(local));
4497 respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
4506 ) -> (hir::Stmt, NodeId) {
4507 let pat = if mutbl {
4508 self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4510 self.pat_ident(sp, ident)
4512 let pat_id = pat.id;
4514 self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4519 fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4520 self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4526 stmts: hir::HirVec<hir::Stmt>,
4527 expr: Option<P<hir::Expr>>,
4529 let LoweredNodeId { node_id, hir_id } = self.next_id();
4536 rules: hir::DefaultBlock,
4538 targeted_by_break: false,
4543 fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4544 self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4547 fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4548 self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4551 fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4552 self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4555 fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4556 self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4562 components: &[&str],
4563 subpats: hir::HirVec<P<hir::Pat>>,
4565 let path = self.std_path(span, components, None, true);
4566 let qpath = hir::QPath::Resolved(None, P(path));
4567 let pt = if subpats.is_empty() {
4568 hir::PatKind::Path(qpath)
4570 hir::PatKind::TupleStruct(qpath, subpats, None)
4575 fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4576 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4579 fn pat_ident_binding_mode(
4583 bm: hir::BindingAnnotation,
4585 let LoweredNodeId { node_id, hir_id } = self.next_id();
4590 node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4595 fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4596 self.pat(span, hir::PatKind::Wild)
4599 fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4600 let LoweredNodeId { node_id, hir_id } = self.next_id();
4609 /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4610 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4611 /// The path is also resolved according to `is_value`.
4615 components: &[&str],
4616 params: Option<P<hir::GenericArgs>>,
4620 .resolve_str_path(span, self.crate_root, components, params, is_value)
4623 fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4625 let node = match qpath {
4626 hir::QPath::Resolved(None, path) => {
4627 // Turn trait object paths into `TyTraitObject` instead.
4628 if let Def::Trait(_) = path.def {
4629 let principal = hir::PolyTraitRef {
4630 bound_generic_params: hir::HirVec::new(),
4631 trait_ref: hir::TraitRef {
4632 path: path.and_then(|path| path),
4638 // The original ID is taken by the `PolyTraitRef`,
4639 // so the `Ty` itself needs a different one.
4640 id = self.next_id();
4641 hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4643 hir::TyPath(hir::QPath::Resolved(None, path))
4646 _ => hir::TyPath(qpath),
4656 /// Invoked to create the lifetime argument for a type `&T`
4657 /// with no explicit lifetime.
4658 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4659 match self.anonymous_lifetime_mode {
4660 // Intercept when we are in an impl header and introduce an in-band lifetime.
4661 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4663 AnonymousLifetimeMode::CreateParameter => {
4664 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4666 id: self.next_id().node_id,
4668 name: hir::LifetimeName::Param(fresh_name),
4672 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4676 /// Invoked to create the lifetime argument(s) for a path like
4677 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4678 /// sorts of cases are deprecated. This may therefore report a warning or an
4679 /// error, depending on the mode.
4680 fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4681 match self.anonymous_lifetime_mode {
4682 // NB. We intentionally ignore the create-parameter mode here
4683 // and instead "pass through" to resolve-lifetimes, which will then
4684 // report an error. This is because we don't want to support
4685 // impl elision for deprecated forms like
4687 // impl Foo for std::cell::Ref<u32> // note lack of '_
4688 AnonymousLifetimeMode::CreateParameter => {}
4690 // This is the normal case.
4691 AnonymousLifetimeMode::PassThrough => {}
4695 .map(|_| self.new_implicit_lifetime(span))
4699 /// Invoked to create the lifetime argument(s) for an elided trait object
4700 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4701 /// when the bound is written, even if it is written with `'_` like in
4702 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4703 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4704 match self.anonymous_lifetime_mode {
4705 // NB. We intentionally ignore the create-parameter mode here.
4706 // and instead "pass through" to resolve-lifetimes, which will apply
4707 // the object-lifetime-defaulting rules. Elided object lifetime defaults
4708 // do not act like other elided lifetimes. In other words, given this:
4710 // impl Foo for Box<dyn Debug>
4712 // we do not introduce a fresh `'_` to serve as the bound, but instead
4713 // ultimately translate to the equivalent of:
4715 // impl Foo for Box<dyn Debug + 'static>
4717 // `resolve_lifetime` has the code to make that happen.
4718 AnonymousLifetimeMode::CreateParameter => {}
4720 // This is the normal case.
4721 AnonymousLifetimeMode::PassThrough => {}
4724 self.new_implicit_lifetime(span)
4727 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4729 id: self.next_id().node_id,
4731 name: hir::LifetimeName::Implicit,
4735 fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4736 self.sess.buffer_lint_with_diagnostic(
4737 builtin::BARE_TRAIT_OBJECTS,
4740 "trait objects without an explicit `dyn` are deprecated",
4741 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4745 fn wrap_in_try_constructor(
4747 method: &'static str,
4749 unstable_span: Span,
4751 let path = &["ops", "Try", method];
4752 let from_err = P(self.expr_std_path(unstable_span, path, None,
4754 P(self.expr_call(e.span, from_err, hir_vec![e]))
4758 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4759 // Sorting by span ensures that we get things in order within a
4760 // file, and also puts the files in a sensible order.
4761 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4762 body_ids.sort_by_key(|b| bodies[b].value.span);